소스 검색

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

LAPTOP-KB9HII50\70708 1 년 전
부모
커밋
f94802298a
38개의 변경된 파일4614개의 추가작업 그리고 668개의 파일을 삭제
  1. 13 1
      business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java
  2. 60 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientHealthGuidanceDao.java
  3. 8 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientHealthGuidanceRecordDao.java
  4. 16 0
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  5. 63 0
      business/im-service/src/main/java/com/yihu/jw/im/util/SendPatientUtil.java
  6. 117 33
      common/common-entity/src/db/2024.sql
  7. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java
  8. 53 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/PatientDoctorRelationEntity.java
  9. 145 0
      common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientHealthGuidance.java
  10. 135 0
      common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientHealthGuidanceRecord.java
  11. 102 0
      common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorGuidanceTemp.java
  12. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorGuidanceTempLabel.java
  13. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorTeamGuidanceDetail.java
  14. 130 0
      common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorTeamGuidanceTemplate.java
  15. 1 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/patient/PatientVO.java
  16. 73 0
      common/common-util/src/main/java/com/yihu/jw/util/SqlReplaceService.java
  17. 39 0
      common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java
  18. 3 0
      starter/mysql-starter/src/main/java/com/yihu/jw/mysql/query/BaseJpaService.java
  19. 1 1
      svr/svr-base/src/main/resources/bootstrap.yml
  20. 3 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java
  21. 104 31
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/ChronicDiseaseController.java
  22. 15 8
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java
  23. 11 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/dao/TrackPatientDao.java
  24. 437 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientHealthGuidanceService.java
  25. 666 593
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/scheme/DoctorSchemeService.java
  26. 59 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorFeldsherTemplateController.java
  27. 235 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorGuidanceTempController.java
  28. 131 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorGuidanceTempLabelController.java
  29. 202 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorRegistrationTempController.java
  30. 323 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorTeamGuidanceController.java
  31. 47 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorGuidanceTempDao.java
  32. 38 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorGuidanceTempLabelDao.java
  33. 22 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorTeamGuidanceDetailDao.java
  34. 83 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorTeamGuidanceTemplateDao.java
  35. 140 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorFeldsherTemplateService.java
  36. 87 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorGuidanceTempLableService.java
  37. 304 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorGuidanceTempService.java
  38. 560 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorTeamGuidanceService.java

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

@ -23,5 +23,17 @@ public interface DevicePatientHealthIndexDao
	@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);
	@Query(value= "SELECT DISTINCT\n" +
			"	a.* \n" +
			"FROM\n" +
			"	wlyy_patient_health_index  a \n" +
			"	INNER JOIN base_patient b ON a.`user`=b.id \n" +
			"	INNER JOIN base_patient_doctor_relation c ON b.id=c.patient_id\n" +
			"WHERE\n" +
			"	a.type IN ('1', '2' ) \n" +
			"	AND a.record_date BETWEEN ?1 AND ?2 \n" +
			"	AND c.doctor_id =?3 \n" +
			"	AND b.disease IN('1','2','3')\n" +
			"	AND b.disease_condition IN ('1','2','1,2')",nativeQuery = true)
	List<DevicePatientHealthIndex> findByDoctor(Date start, Date end, String doctorcode);
}

+ 60 - 0
business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientHealthGuidanceDao.java

@ -0,0 +1,60 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.patient.dao;
import com.yihu.jw.entity.patient.PatientHealthGuidance;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface PatientHealthGuidanceDao extends PagingAndSortingRepository<PatientHealthGuidance, Long>, JpaSpecificationExecutor<PatientHealthGuidance> {
    @Query("select b.name, b.photo, a.id, a.content, a.createTime,b.level,a.readStatus from PatientHealthGuidance a, BaseDoctorDO b where a.patient = ?1 and a.doctor = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByPatient(String patient, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.createTime,b.level,a.readStatus from PatientHealthGuidance a, BaseDoctorDO b where a.patient = ?1 and a.doctor = b.id and a.id < ?2 and a.del = '1' order by a.id desc")
    Page<Object> findByPatient(String patient, long id, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.id < ?2 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, long id, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.patient = ?2 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, String patient, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.patient = ?2 and a.patient = b.id and a.id < ?3 and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, String patient, long id, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.czrq between ?2 and ?3 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, Date begin, Date end, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.czrq between ?2 and ?3 and a.id < ?4 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, Date begin, Date end, long id, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.patient = ?2 and a.czrq between ?3 and ?4 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, String patient, Date begin, Date end, PageRequest pageRequest);
    @Query("select b.name, b.photo, a.id, a.content, a.czrq from PatientHealthGuidance a, BasePatientDO b where a.doctor = ?1 and a.patient = ?2 and a.czrq between ?3 and ?4 and a.id < ?5 and a.patient = b.id and a.del = '1' order by a.id desc")
    Page<Object> findByDoctor(String doctor, String patient, Date begin, Date end, long id, PageRequest pageRequest);
    //查找昨天的健康指导
    @Query("SELECT a FROM PatientHealthGuidance a WHERE unix_timestamp(a.czrq)>=unix_timestamp(?1) and unix_timestamp(a.czrq)<unix_timestamp(?2) ")
    List<PatientHealthGuidance> findByCzrqyYesterday(String yesterday, String now);
    @Query("SELECT count(a) from PatientHealthGuidance a WHERE  a.patient=?2 and a.doctor=?1 ")
    Integer findbydoctorAndPatient(String doctor, String patientCode);
//    @Query("select b.name, b.photo, a.id, substring(a.content, 1, 50) as content, a.createTime,b.level,b.id,a.adminTeamCode,a.readStatus from PatientHealthGuidance a, BaseDoctorDO b where a.doctor = b.id and a.patient = ?1 and a.adminTeamCode = ?2 and a.del = '1'")
//    Page<Object> findByPatientAndTeamCode(String patient, Long teamCode, PageRequest pageable);
}

+ 8 - 0
business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientHealthGuidanceRecordDao.java

@ -0,0 +1,8 @@
package com.yihu.jw.patient.dao;
import com.yihu.jw.entity.patient.PatientHealthGuidanceRecord;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PatientHealthGuidanceRecordDao extends PagingAndSortingRepository<PatientHealthGuidanceRecord, Long>, JpaSpecificationExecutor<PatientHealthGuidanceRecord> {
}

+ 16 - 0
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -3,6 +3,7 @@ package com.yihu.jw.patient.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.hospital.prescription.WlyyInspectionDO;
@ -882,4 +883,19 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        return null;
    }
    /**
     * 获取慢病关联的居民
     */
    public List<BasePatientDO> findAllPatient(String doctorId) {
        String sql="SELECT DISTINCT a.*\n" +
                "FROM\n" +
                "	base_patient a \n" +
                "	INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('1','2','1,2','2,1')\n" +
                "AND b.doctor_id ='"+doctorId+"'";
        List<BasePatientDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BasePatientDO.class));
        return list;
    }
}

+ 63 - 0
business/im-service/src/main/java/com/yihu/jw/im/util/SendPatientUtil.java

@ -0,0 +1,63 @@
package com.yihu.jw.im.util;
import com.alibaba.fastjson.JSONArray;
import org.json.JSONObject;
import java.util.Objects;
public class SendPatientUtil extends  Thread {
	private String from;
	private String fromName;
	private String to;
	private String contentType;
	private String content;
	private String title;
	private String type;
	private String teamCode;
	private ImUtil imUtill;
	public SendPatientUtil(String from, String fromName, String to, String contentType, String content, String title, String type, String teamCode, ImUtil imUtill){
		this.from = from;
		this.fromName = fromName;
		this.to = to;
		this.contentType = contentType;
		this.content = content;
		this.title = title;
		this.type = type;
		this.teamCode =teamCode;
		this.imUtill=imUtill;
	}
	public String sendToPatient(String from,String fromName,String to,String contentType,String content,String title,String type,String teamCode){
		JSONArray jsonArray = imUtill.getParticipants(to + "_" + teamCode + "_" + type);
		com.alibaba.fastjson.JSONObject participants = new com.alibaba.fastjson.JSONObject();
		for(Object object:jsonArray){
			JSONObject jsonObject = (JSONObject)object;
			participants.put(jsonObject.getString("id"),jsonObject.get("role"));
		}
		if(Objects.isNull(participants.get(from))){
			participants.put(from,0);
		}
		if(Objects.isNull(participants.get(to))){
			participants.put(from,0);
		}
		participants.put(to,0);
		if(!"4".equals(contentType)){
			contentType = "0";
		}
		com.alibaba.fastjson.JSONObject sessionJson = ImUtil.createSession(participants, ImUtil.SESSION_TYPE_MUC, title, to + "_" + teamCode + "_" + type);
		if("-1".equals(sessionJson.getString("status"))){
			throw  new RuntimeException(sessionJson.getString("message"));
		}
		com.alibaba.fastjson.JSONObject session = sessionJson.getJSONObject("data");
		return ImUtil.sendImMsg(from,fromName,session.getString("id"),contentType,content,"1");
	}
	@Override
	public void run(){
		this.sendToPatient(from,fromName,to,contentType,content,title,type,teamCode);
	}
}

+ 117 - 33
common/common-entity/src/db/2024.sql

@ -56,39 +56,6 @@ ALTER TABLE `base`.`wlyy_knowledge_category`
    ADD COLUMN `is_check` tinyint(1) NULL COMMENT '是否开启审核1开启 0关闭, 默认开启' ;
--20240227
CREATE TABLE `wlyy_doctor_scheme_blood_sugger` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '数据库主键,与业务主键无关',
  `name` varchar(20) DEFAULT NULL COMMENT '方案名称',
  `code` varchar(50) NOT NULL COMMENT '业务主键UUID',
  `doctorcode` varchar(50) DEFAULT NULL COMMENT '医生CODE',
  `dayofweek` tinyint(4) NOT NULL COMMENT '1到7递增,1为星期日,7为星期六',
  `before_breakfast` tinyint(4) DEFAULT '0' COMMENT '早餐前:0为否,1为是',
  `before_breakfast_time` time DEFAULT NULL COMMENT '早餐前测量时间',
  `after_breakfast` tinyint(4) DEFAULT '0' COMMENT '早餐后:0为否,1为是',
  `after_breakfast_time` time DEFAULT NULL COMMENT '早餐后测量时间',
  `before_lunch` tinyint(4) DEFAULT '0' COMMENT '午餐前:0为否,1为是',
  `before_lunch_time` time DEFAULT NULL COMMENT '午餐前测量时间',
  `after_lunch` tinyint(4) DEFAULT '0' COMMENT '午餐后:0为否,1为是',
  `after_lunch_time` time DEFAULT NULL COMMENT '午餐后测量时间',
  `before_dinner` tinyint(4) DEFAULT '0' COMMENT '晚餐前:0为否,1为是',
  `before_dinner_time` time DEFAULT NULL COMMENT '晚餐前测量时间',
  `after_dinner` tinyint(4) DEFAULT '0' COMMENT '晚餐后:0为否,1为是',
  `after_dinner_time` time DEFAULT NULL COMMENT '晚餐后测量时间',
  `before_sleep` tinyint(4) DEFAULT '0' COMMENT '睡前:0为否,1为是',
  `before_sleep_time` time DEFAULT NULL COMMENT '睡前测量时间',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `alert_tag` tinyint(4) DEFAULT '0' COMMENT '是否提醒居民:0为否,1为是',
  `content` varchar(30) DEFAULT NULL COMMENT '方案说明',
  `del` tinyint(4) DEFAULT '0' COMMENT '0为正常,1为被删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=113 DEFAULT CHARSET=utf8mb4 COMMENT='医生-血糖监测方案表';
INSERT INTO `base`.`oauth_wlyy_config`(`id`, `app_id`, `app_secret`, `token_url`, `url`, `remark`)
VALUES ('getChronicDiseaseData', '019bd04d-3cb2-433f-a530-03f0cdb083e5', '08cc3ec2-736b-4732-a8f0-f99eb6f9d311', 'https://ehr.yihu.com/wlyy/gc/accesstoken', 'https://ehr.yihu.com/wlyy/wlyygc/tongan/hospital/getChronicDiseaseData', '获取同安签约慢病数据');
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('patient_lable_custom1', NULL, 'patient_lable_custom', '1', '儿童', NULL, '1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '居民标签自定义');
@ -124,3 +91,120 @@ CREATE TABLE `wlyy_patient_label_log` (
     KEY `index` (`patient`,`doctor`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-------- 慢病管理------
CREATE TABLE `wlyy_doctor_switch` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `doctor` varchar(50) DEFAULT NULL COMMENT '关联医生',
  `alert_patient_switch` varchar(2) DEFAULT '0' COMMENT '0不自动跟踪居民,1自动跟踪预警居民',
  `dispatch_order_switch` varchar(2) DEFAULT '0' COMMENT '0关闭分派订单功能,1开启分派订单功能',
  `create_time` timestamp NULL DEFAULT NULL,
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=870 DEFAULT CHARSET=utf8;
CREATE TABLE `wlyy_doctor_scheme_blood_sugger` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '数据库主键,与业务主键无关',
  `name` varchar(20) DEFAULT NULL COMMENT '方案名称',
  `code` varchar(50) NOT NULL COMMENT '业务主键UUID',
  `doctorcode` varchar(50) DEFAULT NULL COMMENT '医生CODE',
  `dayofweek` tinyint(4) NOT NULL COMMENT '1到7递增,1为星期日,7为星期六',
  `before_breakfast` tinyint(4) DEFAULT '0' COMMENT '早餐前:0为否,1为是',
  `before_breakfast_time` time DEFAULT NULL COMMENT '早餐前测量时间',
  `after_breakfast` tinyint(4) DEFAULT '0' COMMENT '早餐后:0为否,1为是',
  `after_breakfast_time` time DEFAULT NULL COMMENT '早餐后测量时间',
  `before_lunch` tinyint(4) DEFAULT '0' COMMENT '午餐前:0为否,1为是',
  `before_lunch_time` time DEFAULT NULL COMMENT '午餐前测量时间',
  `after_lunch` tinyint(4) DEFAULT '0' COMMENT '午餐后:0为否,1为是',
  `after_lunch_time` time DEFAULT NULL COMMENT '午餐后测量时间',
  `before_dinner` tinyint(4) DEFAULT '0' COMMENT '晚餐前:0为否,1为是',
  `before_dinner_time` time DEFAULT NULL COMMENT '晚餐前测量时间',
  `after_dinner` tinyint(4) DEFAULT '0' COMMENT '晚餐后:0为否,1为是',
  `after_dinner_time` time DEFAULT NULL COMMENT '晚餐后测量时间',
  `before_sleep` tinyint(4) DEFAULT '0' COMMENT '睡前:0为否,1为是',
  `before_sleep_time` time DEFAULT NULL COMMENT '睡前测量时间',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `alert_tag` tinyint(4) DEFAULT '0' COMMENT '是否提醒居民:0为否,1为是',
  `content` varchar(30) DEFAULT NULL COMMENT '方案说明',
  `del` tinyint(4) DEFAULT '0' COMMENT '0为正常,1为被删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=113 DEFAULT CHARSET=utf8mb4 COMMENT='医生-血糖监测方案表';
INSERT INTO `base`.`oauth_wlyy_config`(`id`, `app_id`, `app_secret`, `token_url`, `url`, `remark`)
VALUES ('getChronicDiseaseData', '019bd04d-3cb2-433f-a530-03f0cdb083e5', '08cc3ec2-736b-4732-a8f0-f99eb6f9d311', 'https://ehr.yihu.com/wlyy/gc/accesstoken', 'https://ehr.yihu.com/wlyy/wlyygc/tongan/hospital/getChronicDiseaseData', '获取同安签约慢病数据');
CREATE TABLE `base_patient_doctor_relation` (
  `id` int NOT NULL AUTO_INCREMENT,
  `patient_id` varchar(100) DEFAULT NULL COMMENT '患者id',
  `doctor_id` varchar(100) DEFAULT NULL COMMENT '医生id',
  `source_type` varchar(10) DEFAULT NULL COMMENT '来源类型,1线上就诊 , 2i健康签约',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `wlyy_track_patient` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `patient_code` varchar(50) DEFAULT NULL COMMENT '关联居民code,医生的重点关注对象',
  `patient_name` varchar(50) DEFAULT NULL COMMENT '患者姓名',
  `doctor_code` varchar(50) DEFAULT NULL COMMENT '所属医生',
  `doctor_name` varchar(50) DEFAULT NULL COMMENT '所属医生名',
  `team_code` int(11) DEFAULT NULL COMMENT '居民签约团队',
  `idcard` varchar(50) DEFAULT NULL COMMENT '身份证号',
  `ssc` varchar(50) DEFAULT NULL COMMENT '社保卡号',
  `del` varchar(1) DEFAULT NULL COMMENT '1正常,0删除',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `uk_patient_doctor` (`patient_code`,`doctor_code`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1946 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `wlyy_doctor_health_standard` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '业务无关主键',
  `doctor` varchar(50) NOT NULL COMMENT '患者标识',
  `type` int(11) NOT NULL COMMENT '健康指标类型:1血糖,2血压,3体重,4腰围',
  `min_value_1` double DEFAULT NULL COMMENT '最低安全值(血糖餐前收缩压体重腰围)',
  `max_value_1` double DEFAULT NULL COMMENT '最高安全值(血糖餐前收缩压体重腰围)',
  `min_value_2` double DEFAULT NULL COMMENT '最低安全值(血糖餐后舒张压)',
  `max_value_2` double DEFAULT NULL COMMENT '最高安全值(血糖餐后舒张压)',
  `czrq` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '设置时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `idx_wlyy_doctor_health_standard_1` (`doctor`,`type`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=359 DEFAULT CHARSET=utf8mb4 COMMENT='医生健康指标预警值方案';
CREATE TABLE `wlyy_doctor_scheme_blood_pressure` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id主键,与业务主键CODE无关',
  `name` varchar(20) DEFAULT NULL COMMENT '方案名称',
  `code` varchar(50) DEFAULT NULL COMMENT '业务主键CODE,UUID',
  `doctorcode` varchar(50) DEFAULT NULL COMMENT '医生CODE',
  `dayofweek` tinyint(4) NOT NULL COMMENT '1至7递增,1为星期日,7位星期六',
  `early_morning` tinyint(4) DEFAULT '0' COMMENT '清晨:0为否,1为是',
  `early_morning_time` time DEFAULT NULL COMMENT '清晨测量时间',
  `morning` tinyint(4) DEFAULT '0' COMMENT '上午:0为否,1为是',
  `morning_time` time DEFAULT NULL COMMENT '上午测量时间',
  `noon` tinyint(4) DEFAULT '0' COMMENT '中午:0为否,1为是',
  `noon_time` time DEFAULT NULL COMMENT '中午测量时间',
  `after_noon` tinyint(4) DEFAULT '0' COMMENT '下午:0为否,1为是',
  `after_noon_time` time DEFAULT NULL COMMENT '下午测量时间',
  `night` tinyint(4) DEFAULT '0' COMMENT '晚上:0为否,1为是',
  `night_time` time DEFAULT NULL COMMENT '晚上测量时间',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `alert_tag` tinyint(4) DEFAULT NULL COMMENT '是否提醒居民:0为否,1为是',
  `content` varchar(20) DEFAULT NULL COMMENT '方案说明',
  `del` tinyint(4) DEFAULT '0' COMMENT '0为正常,1为被删除',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=78 DEFAULT CHARSET=utf8mb4 COMMENT='医生-血压监测方案';
CREATE TABLE `wlyy_patient_scheme_list` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id主键,与业务逻辑无关',
  `code` varchar(50) NOT NULL COMMENT '业务逻辑主键UUID',
  `patientcode` varchar(50) NOT NULL COMMENT '患者CODE',
  `schemecode` varchar(50) NOT NULL COMMENT '监测方案CODE',
  `type` tinyint(4) NOT NULL COMMENT '方案类型:1为血糖,2为血压',
  `doctorcode` varchar(50) DEFAULT NULL COMMENT '医生CODE',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COMMENT='患者-监测方案关联关系表';

+ 11 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java

@ -303,12 +303,23 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
    private String verifyCode;//眼科token
    private String disease ;//'疾病类型,0健康,1高血压,2糖尿病,3高血压+糖尿病',
    // 病情:0绿标,1黄标,2红标
    private Integer diseaseCondition;
    //外部数据-年龄数据
    private Integer age;
    public String getDisease() {
        return disease;
    }
    public void setDisease(String disease) {
        this.disease = disease;
    }
    @Column(name = "medical_state")
    public String getMedicalState() {
        return medicalState;

+ 53 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/PatientDoctorRelationEntity.java

@ -0,0 +1,53 @@
package com.yihu.jw.entity.base.patient;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author suqinyi
 * @Date 2024/3/5
 */
@Entity
@Table(name = "base_patient_doctor_relation")
public class PatientDoctorRelationEntity extends IdEntity {
    private String patientId;  //患者id
    private String doctorId; // 医生id
    private String sourceType;//来源类型,1线上就诊 , 2i健康签约
    private Date createTime;//创建时间
    public String getPatientId() {
        return patientId;
    }
    public void setPatientId(String patientId) {
        this.patientId = patientId;
    }
    public String getDoctorId() {
        return doctorId;
    }
    public void setDoctorId(String doctorId) {
        this.doctorId = doctorId;
    }
    public String getSourceType() {
        return sourceType;
    }
    public void setSourceType(String sourceType) {
        this.sourceType = sourceType;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 145 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientHealthGuidance.java

@ -0,0 +1,145 @@
package com.yihu.jw.entity.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 健康指导
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_guidance")
public class PatientHealthGuidance extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4187769034437765691L;
	// 患者标识
	private String patient;
	// 医生标识
	private String doctor;
	// 指导内容
	private String content;
	// 咨询图片URL,多图以逗号分隔
	private String images;
	// 咨询语音URL
	private String voice;
	// 作废标识:1正常,0作废
	private String del;
	// 添加时间
	private Date czrq;
	// 签约类型 1三师 2家庭
	private Integer signType;
	// 行政团队
	private Long adminTeamCode;
//	指导阅读状态
	private int readStatus;
//	指导创建时间
	private Date createTime;
	//签约表Code
	private String signCode;
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public int getReadStatus() {
		return readStatus;
	}
	public void setReadStatus(int readStatus) {
		this.readStatus = readStatus;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@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 getImages() {
		return images;
	}
	public void setImages(String images) {
		this.images = images;
	}
	public String getVoice() {
		return voice;
	}
	public void setVoice(String voice) {
		this.voice = voice;
	}
	public Integer getSignType() {
		return signType;
	}
	public void setSignType(Integer signType) {
		this.signType = signType;
	}
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
}

+ 135 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientHealthGuidanceRecord.java

@ -0,0 +1,135 @@
package com.yihu.jw.entity.patient;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 健康指导记录本
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_guidance_record")
public class PatientHealthGuidanceRecord extends IdEntity {
    private static final long serialVersionUID = -4187769034437765691L;
    private String code;
    // 患者标识
    private String patient;
    // 患者标识
    private String patientOpenid;
    // 医生标识
    private String doctor;
    // 指导内容
    private String content;
    // 咨询图片URL,多图以逗号分隔
    private String images;
    // 咨询语音URL
    private String voice;
    // 作废标识:1正常,0作废
    private Integer del;
    // 行政团队
    private Long adminTeamCode;
    //	指导阅读状态
    private int readStatus;
    //	指导创建时间
    private Date createTime;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "read_status")
    public int getReadStatus() {
        return readStatus;
    }
    public void setReadStatus(int readStatus) {
        this.readStatus = readStatus;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "patient_openid")
    public String getPatientOpenid() {
        return patientOpenid;
    }
    public void setPatientOpenid(String patientOpenid) {
        this.patientOpenid = patientOpenid;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    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;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getVoice() {
        return voice;
    }
    public void setVoice(String voice) {
        this.voice = voice;
    }
    @Column(name = "admin_team_code")
    public Long getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(Long adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
}

+ 102 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorGuidanceTemp.java

@ -0,0 +1,102 @@
package com.yihu.jw.entity.template;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by lyr-pc on 2017/2/3.
 */
@Entity
@Table(name = "wlyy_doctor_guidance_temp")
public class DoctorGuidanceTemp extends IdEntity{
    // 模板编码
    private String code;
    // 所属医生 system为系统标签
    private String owner;
    // 内容
    private String content;
    // 发送次数
    private Integer sendTimes;
    // 创建时间
    private Date createTime;
    // 最后一次发送时间
    private Date lastTime;
//    模板名称
    private String modelName;
//    图片地址
    private String imagesUrl;
    public String getModelName() {
        return modelName;
    }
    public void setModelName(String modelName) {
        this.modelName = modelName;
    }
    public String getImagesUrl() {
        return imagesUrl;
    }
    public void setImagesUrl(String imagesUrl) {
        this.imagesUrl = imagesUrl;
    }
    public String getCode() {
        return code;
    }
//=================
    public void setCode(String code) {
        this.code = code;
    }
    public String getOwner() {
        return owner;
    }
    public void setOwner(String owner) {
        this.owner = owner;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getSendTimes() {
        return sendTimes;
    }
    public void setSendTimes(Integer sendTimes) {
        this.sendTimes = sendTimes;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getLastTime() {
        return lastTime;
    }
    public void setLastTime(Date lastTime) {
        this.lastTime = lastTime;
    }
}

+ 86 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorGuidanceTempLabel.java

@ -0,0 +1,86 @@
package com.yihu.jw.entity.template;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by 刘文彬 on 2018/5/17.
 */
@Entity
@Table(name = "wlyy_doctor_guidance_temp_label")
public class DoctorGuidanceTempLabel extends IdEntity {
    private String code;//业务编码
    private String name;//标签名称
    private Date createTime;// 创建时间
    private String doctorCode;//创建人code
    private Integer del;//作废标识1、正常 ,0、作废
    private Integer teamId;//医生团队Id
    @Column(name = "code", length = 50)
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "name", length = 100)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "doctor_code", length = 50)
    public String getDoctorCode() {
        return doctorCode;
    }
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
    @Column(name = "del", length = 2)
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Column(name = "team_id", length = 11)
    public Integer getTeamId() {
        return teamId;
    }
    public void setTeamId(Integer teamId) {
        this.teamId = teamId;
    }
    public DoctorGuidanceTempLabel(String code, String name) {
        this.code = code;
        this.name = name;
    }
    public DoctorGuidanceTempLabel() {
    }
}

+ 91 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorTeamGuidanceDetail.java

@ -0,0 +1,91 @@
package com.yihu.jw.entity.template;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Reece on 2017/6/8.
 */
@Entity
@Table(name = "wlyy_team_guidance_detail")
public class DoctorTeamGuidanceDetail extends IdEntity {
    //    指导模板编码
    private String code;
    //    所属医生
    private String creater;
    //    模板名称(前端限10 后端限50)
    private String title;
    //    指导内容
    private String content;
    //    健康指导图片URL,多图以逗号分隔(至多9图)
    private String imagesUrl;
    //            创建时间
    private Date createTime;
    //    操作时间
    private Date czrq;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getCreater() {
        return creater;
    }
    public void setCreater(String creater) {
        this.creater = creater;
    }
    @Column(name = "title", length = 50)
    public String getTitle() {
        return title;
    }
    @Column(name = "title", length = 50)
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getImagesUrl() {
        return imagesUrl;
    }
    public void setImagesUrl(String imagesUrl) {
        this.imagesUrl = imagesUrl;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @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;
    }
}

+ 130 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/template/DoctorTeamGuidanceTemplate.java

@ -0,0 +1,130 @@
package com.yihu.jw.entity.template;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Reece on 2017/6/8.
 * 医生端团队健康指导模板 团队与模板对应关系
 */
@Entity
@Table(name = "wlyy_team_guidance_template")
public class DoctorTeamGuidanceTemplate extends IdEntity {
    //    团队ID
    private int teamId;
    //    团队ID名称
    private String teamName;
    //    团队指导模板code
    private String teamTemplateCode;
    //    团队模板创建者
    private String creater;
    //     团队模板的标题
    private String title;
    //        团队内该模板被使用次数
    private int useTimes;
    //  模板创建时间
    private Date createTime;
    //        操作时间
    private Date czrq;
    //        团队内的团队模板状态  0删除  1正常
    private int del;
    private String labelCode;//指导标签code
    private String labelName;//指导标签name
    public String getTeamName() {
        return teamName;
    }
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
    public int getTeamId() {
        return teamId;
    }
    public void setTeamId(int teamId) {
        this.teamId = teamId;
    }
    public String getTeamTemplateCode() {
        return teamTemplateCode;
    }
    public void setTeamTemplateCode(String teamTemplateCode) {
        this.teamTemplateCode = teamTemplateCode;
    }
    public String getCreater() {
        return creater;
    }
    public void setCreater(String creater) {
        this.creater = creater;
    }
    @Column(name = "title", length = 50)
    public String getTitle() {
        return title;
    }
    @Column(name = "title", length = 50)
    public void setTitle(String title) {
        this.title = title;
    }
    public int getUseTimes() {
        return useTimes;
    }
    public void setUseTimes(int useTimes) {
        this.useTimes = useTimes;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @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 int getDel() {
        return del;
    }
    public void setDel(int del) {
        this.del = del;
    }
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
}

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

@ -13,6 +13,7 @@ public class PatientVO {
	
	// 业务主键
	private String code;
	// 身份证号
	private String idcard;
	// 登录密码

+ 73 - 0
common/common-util/src/main/java/com/yihu/jw/util/SqlReplaceService.java

@ -0,0 +1,73 @@
package com.yihu.jw.util;
import com.yihu.jw.entity.util.AesEncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * Created by liub on 2021/2/3.
 */
@Service
public class SqlReplaceService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     *
     * @param sql select i.* from tableName i where 1=1
     * @param tableAlias i 表别名添加顺序与Map<tableName,DataBaseName>添加的顺序一致
     * @param tableList Map<tableName,DataBaseName>
     * @param encryptColumnList i.idcard
     * @param decryptColumnList i.name
     * @return
     */
//    public String sqlReplace(String sql, List<String> tableAlias, List<Map<String,String>> tableList, List<String> encryptColumnList, List<String> decryptColumnList) {
//
//        if (tableList.size() > 1) {
//            sql = sqlReplace(sql, tableAlias.subList(1, tableAlias.size()), tableList.subList(1, tableList.size()), encryptColumnList, decryptColumnList);
//        }
//        sql = sql.replace("from", "FROM");
//        String sqlSelect = sql.substring(0, sql.indexOf("FROM"));
//        String sqlWHERE = sql.substring(sql.indexOf("FROM"));
//        String tableAlia = tableAlias.size()>0?tableAlias.get(0):"";
//        if (tableList.size() > 0 && tableAlias.size() > 0) {
//            Map<String, String> tab = tableList.get(0);
//            String tableName = "";
//            String tableSchema = "";
//            for (Map.Entry<String, String> vo : tab.entrySet()) {
//                tableName = vo.getKey();
//                tableSchema = vo.getValue();
//            }
//            String sqlColumn = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '" + tableName + "' and table_schema = '" + tableSchema+"'";
//            List<String> columns = jdbcTemplate.queryForList(sqlColumn, String.class);
//            StringBuilder sqlReplaceStringBulider = new StringBuilder();
//            for (String tmp : columns) {
//                sqlReplaceStringBulider.append(tableAlia + "." + tmp + " "+tmp+",");
//            }
//            if (sqlReplaceStringBulider.length() > 0) {
//                sqlReplaceStringBulider.deleteCharAt(sqlReplaceStringBulider.length() - 1);
//            }
//            String sqlReplaceString = sqlReplaceStringBulider.toString();
//            sqlSelect=sqlSelect.replace(tableAlia + ".*", sqlReplaceString);
//        }
//
//        for (String encry : encryptColumnList) {
//            if (encry.contains(tableAlia+".")){
//                sqlSelect= sqlSelect.replace(encry, "to_base64(AES_ENCRYPT(" + encry + ",'" + AesEncryptUtils.DBKEY + "'))");
//            }
//        }
//        for (String decry : decryptColumnList) {
//            if (decry.contains(tableAlia+".")){
//                sqlSelect= sqlSelect.replace(decry, "AES_DECRYPT(from_base64(" + decry + "),'" + AesEncryptUtils.DBKEY + "')");
//            }
//        }
//
//        return sqlSelect + sqlWHERE;
//    }
}

+ 39 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java

@ -338,4 +338,43 @@ public class CommonUtil {
            return fileUrls;
        }
    }
    /**
     * 校验图片本地路径掺杂网络路径,统一返回网路路径
     *
     * @param images
     * @throws Exception
     */
    public  String validateImages(String images) throws Exception {
        String imagePath = "";
        String imageUrls = "";
        String imageRow = "";
        String[] imgs = images.split(",");
        for (String image : imgs) {
            if (image.contains("group1")) {
                imageUrls += image + ",";
            } else {
                try {
                    imageRow += copyTempImage(image) + ",";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        imagePath += imageUrls + imageRow;
        imagePath = imagePath.substring(0, imagePath.length() - 1);
        return imagePath;
    }
    public String getSubString(String content, int min, int max) {
        if (StringUtils.isBlank(content)) {
            return "";
        } else if (content.length() <= max) {
            return content;
        } else {
            return content.substring(min, max);
        }
    }
}

+ 3 - 0
starter/mysql-starter/src/main/java/com/yihu/jw/mysql/query/BaseJpaService.java

@ -1,5 +1,6 @@
package com.yihu.jw.mysql.query;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.lang.SpringContext;
import org.hibernate.query.Query;
import org.hibernate.Session;
@ -349,4 +350,6 @@ public abstract class BaseJpaService<T, R extends CrudRepository> {
        }
        return buffer.toString();
    }
}

+ 1 - 1
svr/svr-base/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name: svr-base
    name: svr-base --
  cloud:
    config:
      failFast: true

+ 3 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java

@ -2,9 +2,11 @@
package com.yihu.jw.hospital.module.consult.service;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.im.util.SendPatientUtil;
import com.yihu.jw.order.dao.ConsultOrderDao;
import com.yihu.jw.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
@ -147,7 +149,7 @@ public class ConsultService {
//    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
//        Doctor d = doctorDao.findByCode(doctor);
//        BaseDoctorDO d = doctorDao.findById(doctor).orElse(null)
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);//当前签约团队
//        if (signFamily == null) {
//            List<SignFamily> signFamilys = signFamilyDao.findLastJySignByPatient(patient, 2);//获取旧的家庭签约关系

+ 104 - 31
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/ChronicDiseaseController.java

@ -4,7 +4,6 @@ import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodPressureVO;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodSuggerVO;
import com.yihu.jw.hospital.module.health.service.scheme.DoctorSchemeService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -15,7 +14,9 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author suqinyi
@ -42,9 +43,13 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @RequestMapping(value = "getDoctorSwitchTrackPatient", method = RequestMethod.GET)
    @ApiOperation("医生跟踪预警居民开关接口")
    public String getDoctorSwitchTrackPatient() {
    public String getDoctorSwitchTrackPatient(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getDoctorSwitchTrackPatient(getUID()));
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getDoctorSwitchTrackPatient(doctorId));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -52,9 +57,15 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @RequestMapping(value = "setDoctorSwitchTrackPatient", method = RequestMethod.POST)
    @ApiOperation("医生跟踪预警居民开关接口")
    public String setDoctorSwitchTrackPatient(@ApiParam(name = "state", value = "0不自动跟踪居民,1自动跟踪预警居民") @RequestParam(value = "state", required = true) String state) {
    public String setDoctorSwitchTrackPatient(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId,
            @ApiParam(name = "state", value = "0不自动跟踪居民,1自动跟踪预警居民") @RequestParam(value = "state", required = true) String state
    ) {
        try {
            return write(200, "操作成功", "data", doctorSchemeService.setDoctorSwitchTrackPatient(getUID(), state));
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            return write(200, "操作成功", "data", doctorSchemeService.setDoctorSwitchTrackPatient(doctorId, state));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -64,20 +75,19 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @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();
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(doctorId, getcolor, getstands, gethealthindex, startdate, enddate, getUID());
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(null, getcolor, getstands, gethealthindex, startdate, enddate, doctorId);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, e.getMessage());
        }
    }
@ -86,14 +96,17 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @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 = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false, defaultValue = "") String doctorId,
            @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);
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            List<String> result = doctorSchemeService.getPatientsByDiseaseConditionDiseaseDeviceType(null, disease, diseaseCondition, deviceType, doctorId, trackFlag);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
@ -235,11 +248,15 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @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) {
    public String getTrackPatientCountTitle(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = true) String doctorId,
            @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));
            if (StringUtils.isNotBlank(doctorId)) {
                doctorId = getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientCountTitle(doctorId, startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -247,11 +264,15 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @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) {
    public String getTrackPatientServerCount(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId,
            @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));
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientServerCount(null, doctorId, startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -259,24 +280,33 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @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) {
    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 = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = true) String doctorId) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getPatientHealthIndex(startDate, endDate, type, teamCode, getUID()));
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getPatientHealthIndexNew(startDate, endDate, type, doctorId));
        } 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) {
    public String getTrackPatientAimByteam(
            @ApiParam(name = "doctorId", value = "团队Code") @RequestParam(value = "doctorId", required = true) String doctorId,
            @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));
            if (StringUtils.isBlank(doctorId)){
                doctorId=getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientAimByteam(doctorId,startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -284,9 +314,13 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @RequestMapping(value = "getDeviceStateByTeam", method = RequestMethod.GET)
    @ApiOperation("获取团队医生下,居民设备绑定情况")
    public String getDeviceStateByTeam(@ApiParam(name = "teamCode", value = "团队Code") @RequestParam(value = "teamCode", required = true) Long teamCode) {
    public String getDeviceStateByTeam(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getDeviceStateByTeam(getUID(), teamCode));
            if (StringUtils.isBlank(doctorId)){
                doctorId=getUID();
            }
            return write(200, "查询成功", "data", doctorSchemeService.getDeviceStateByTeam(doctorId));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
@ -338,4 +372,43 @@ public class ChronicDiseaseController extends EnvelopRestEndpoint {
    // --------------------------------------------------------
    /**
     * 获取红黄绿标高血压糖尿病的指标人数
     */
    @RequestMapping(value = "getLabelCount", method = RequestMethod.GET)
    @ApiOperation("获取红黄绿标高血压糖尿病的指标人数")
    public String getLabelCount(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId) {
        try {
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            HashMap<String, Object> result = doctorSchemeService.getLabelCount(doctorId);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getLabelDetail", method = RequestMethod.GET)
    @ApiOperation("获取红黄绿标高血压糖尿病明细")
    public String getLabelDetail(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId,
            @ApiParam(name = "labelType", value = "1高血压 2糖尿病 空全部") @RequestParam(value = "labelType", required = false) String labelType,
            @ApiParam(name = "searchContent", value = "检索内容") @RequestParam(value = "labelType", required = false) String searchContent,
            @ApiParam(name = "page", value = "页码") @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "pageSize", value = "数量") @RequestParam(value = "pageSize", required = false) int pageSize
    ) {
        try {
            if (StringUtils.isBlank(doctorId)) {
                doctorId = getUID();
            }
            List<Map<String, Object>> result = doctorSchemeService.getLabelDetail(doctorId, labelType, searchContent, page, pageSize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
}

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

@ -8,7 +8,9 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.util.entity.ServiceException;
import com.yihu.jw.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -31,6 +33,8 @@ public class DoctorHealthController extends BaseController {
	private PatientHealthIndexService healthIndexService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	BasePatientService patientService;
	@RequestMapping(value = "recent",method = RequestMethod.GET)
@ -560,20 +564,23 @@ public class DoctorHealthController extends BaseController {
	@RequestMapping(value = "savastandbyteamcode",method = RequestMethod.POST)
	@ApiOperation("医生保存团队下所有居民的预警方案")
	public String doctorSaveStandardByTeamCode(
			@ApiParam("团队代码") @RequestParam String teamcode,
			@ApiParam("团队代码") @RequestParam String doctorId,
			@ApiParam("预警值Json") @RequestParam String json
	) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(teamcode) || array == null || array.length() == 0) {
			if (StringUtils.isEmpty(doctorId) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
			List<BasePatientDO> patients = new ArrayList<>();
			if (StringUtils.isBlank(doctorId)){
				doctorId=getUID();
			}
			List<BasePatientDO> patients = patientService.findAllPatient(doctorId);
			System.out.println("数量==>"+patients.size());
			if(!patients.isEmpty()){
				// 生成数据对象
				//生成数据对象
				List<PatientHealthStandard> list = new ArrayList<>();
				//保存患者的数据时,同时医生的预警值方案
				List<DoctorHealthStandard> doclist = new ArrayList<>();
@ -585,7 +592,7 @@ public class DoctorHealthController extends BaseController {
					for (BasePatientDO patient: patients) {
						PatientHealthStandard standard = new PatientHealthStandard();
						standard.setDoctor(getUID());
						standard.setDoctor(doctorId);
						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);
@ -597,7 +604,7 @@ public class DoctorHealthController extends BaseController {
					}
					DoctorHealthStandard doctorHealthStandard = new DoctorHealthStandard();
					doctorHealthStandard.setDoctor(getUID());
					doctorHealthStandard.setDoctor(doctorId);
					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);
@ -615,7 +622,7 @@ public class DoctorHealthController extends BaseController {
					return error(-1, "保存失败!");
				}
				Iterable<DoctorHealthStandard> dociterable = healthIndexService.saveDocStandard(doclist, getUID());
				Iterable<DoctorHealthStandard> dociterable = healthIndexService.saveDocStandard(doclist, doctorId);
				if (dociterable == null || dociterable.iterator() == null || !dociterable.iterator().hasNext()) {
					return error(-1, "保存失败!");
				}

+ 11 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/dao/TrackPatientDao.java

@ -3,6 +3,7 @@ package com.yihu.jw.hospital.module.health.dao;
import com.yihu.jw.entity.scheme.TrackPatient;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
@ -16,4 +17,14 @@ public interface TrackPatientDao extends PagingAndSortingRepository<TrackPatient
    public List<TrackPatient> findByDoctorCodeAndTeamCodeAndDel(String doctorCode, Integer teamCode, String del);
    List<TrackPatient> findByDoctorCodeAndDel(String doctorCode, String del);
    @Query(value= "SELECT DISTINCT a.*\n" +
            "FROM wlyy_track_patient a  \n" +
            "INNER JOIN base_patient b ON a.patient_code=b.id \n" +
            "INNER JOIN base_patient_doctor_relation c ON b.id=c.patient_id  \n" +
            "WHERE 1=1\n" +
            "AND c.doctor_id=?1 \n" +
            "AND a.del=?2 ",nativeQuery = true)
    List<TrackPatient> findByDoctor(String doctor,String del);
}

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

@ -0,0 +1,437 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.patient.PatientHealthGuidance;
import com.yihu.jw.entity.patient.PatientHealthGuidanceRecord;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.PatientHealthGuidanceDao;
import com.yihu.jw.patient.dao.PatientHealthGuidanceRecordDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.util.date.DateUtil;
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;
import java.util.UUID;
/**
 * 健康指导业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthGuidanceService {
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
    JdbcTemplate jdbcTemplate;
	@Autowired
	WeiXinOpenIdUtils weiXinOpenIdUtils;
	@Autowired
	private BasePatientService patientService;
	@Autowired
	private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
	@Autowired
	private PushMsgTask pushMsgTask;
	@Autowired
	private WechatTemplateConfigDao templateConfigDao;
	@Autowired
	private PatientHealthGuidanceDao patientHealthGuidanceDao;
	@Autowired
	private PatientHealthGuidanceRecordDao patientHealthGuidanceRecordDao;
	//	@Autowired
//	SignFamilyDao signFamilyDao;
	public JSONObject findById(Long id){
		PatientHealthGuidance guidance = patientHealthGuidanceDao.findById(id).orElse(null);
		if(guidance != null){
			JSONObject obj = new JSONObject(guidance);
			BaseDoctorDO doc = doctorDao.findById(guidance.getDoctor()).orElse(null);
			BasePatientDO p = patientDao.findById(guidance.getPatient()).orElse(null);
			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 {
		BaseDoctorDO doctor = doctorDao.findById(guidance.getDoctor()).orElse(null);
		BasePatientDO patient = patientDao.findById(guidance.getPatient()).orElse(null);
//		//家庭医生
//		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.getId());
			json.put("represented",patient.getId());//被代理人
			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.getId());
				guidanceRecord.setPatientOpenid(openId);
				guidanceRecord.setDoctor(doctor.getId());
				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.getId(), patient.getOpenid());
				if (jsonArray != null && jsonArray.length() > 0) {
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject j = jsonArray.getJSONObject(i);
						BasePatientDO member = (BasePatientDO) j.get("member");
						//保存健康指导推送记录
						PatientHealthGuidanceRecord guidanceRecord = new PatientHealthGuidanceRecord();
						guidanceRecord.setCode(getCode());
						guidanceRecord.setPatient(patient.getId());
						guidanceRecord.setPatientOpenid(member.getOpenid());
						guidanceRecord.setDoctor(doctor.getId());
						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.getId());
						//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 =  PageRequest.of(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 =  Sort.by(Sort.Direction.DESC,"createTime");
		PageRequest pageRequest =  PageRequest.of(page, pageSize, sort);
//		Page<Object> result = patientHealthGuidanceDao.findByPatientAndTeamCode(patient,teamCode,pageRequest);
		Page<Object> result =null;
		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 =  PageRequest.of(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 {
		BasePatientDO patient = patientDao.findByIdcard(idcard);
		
		if(patient == null || StringUtils.isBlank(patient.getId())){
			throw new RuntimeException("找不到该身份证号的居民!");
		}
		
		JSONArray array = new JSONArray();
		// 分页信息,排序
		Sort sort =  Sort.by(Sort.Direction.DESC,"createTime");
		// 分页信息
		PageRequest pageRequest =  PageRequest.of(Integer.valueOf(page) - 1, Integer.valueOf(pageSize), sort);
		Page<Object> pageObj = null;
		pageObj = patientHealthGuidanceDao.findByPatient(patient.getId(), 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;
	}
	public String getCode() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}

+ 666 - 593
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/scheme/DoctorSchemeService.java

@ -17,7 +17,6 @@ import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodPressureVO;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodSuggerVO;
import com.yihu.jw.hospital.module.health.dao.*;
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;
@ -36,9 +35,14 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 医生监测方案相关业务层方法
 *
 * @author huangwenjie
 * @date 2017/9/13 15:46
 */
@ -89,60 +93,57 @@ public class DoctorSchemeService {
    /**
     * 根据团队CODE/居民标签/病情/设备绑定状态查询团队具名CODE列表
     * @param teamCode 团队CODE
     * @param disease  病情
     *
     * @param teamCode         团队CODE
     * @param disease          病情
     * @param diseaseCondition 居民标签
     * @param deviceType 设备绑定状态
     * @param deviceType       设备绑定状态
     * @return
     * @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 ";
    public List<String> getPatientsByDiseaseConditionDiseaseDeviceType(String teamCode, Integer disease, String diseaseCondition, Integer deviceType, String doctorcode, String trackFlag) throws Exception {
        String sql = "SELECT  a.id\n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n";
        //1.4.2加入跟踪居民过滤
        if(StringUtils.isNotBlank(trackFlag)&&"1".equals(trackFlag)){
            sql = sql + " JOIN wlyy_track_patient tp ON tp.patient_code = p.code ";
        if (StringUtils.isNotBlank(trackFlag) && "1".equals(trackFlag)) {
            sql = sql + " INNER JOIN wlyy_track_patient tp ON tp.patient_code = a.id ";
        }
        if(-1 != deviceType){
            sql = sql + " LEFT JOIN wlyy_patient_device dev on dev.user = p.code ";
        if (-1 != deviceType) {
            sql = sql + " LEFT JOIN wlyy_patient_device dev on dev.user = a.id ";
        }
        sql += "WHERE 1=1\n";
        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) ";
        //疾病类型,-1全部,0健康,1高血压,2糖尿病,3高血压+糖尿病
        if (-1 == disease) {
            sql += " AND a.disease IN ('1','2','1,2','2,1') ";
        } else {
            if (disease == 3) {
                sql += " AND a.disease IN ('1,2','2,1') ";
            } else {
                sql += " and a.disease ='" + disease + "' ";
            }
        }
        if(StringUtils.isNotBlank(diseaseCondition) && !"-1".equals(diseaseCondition)){
            sql = sql + " and p.disease_condition IN ("+diseaseCondition +")";
        if (StringUtils.isNotBlank(diseaseCondition) && !"-1".equals(diseaseCondition)) {
            sql += " AND a.disease_condition IN (" + diseaseCondition + ") ";
        }
        if(-1 != deviceType){
            if( 0 == deviceType){
        if (-1 != deviceType) {
            if (0 == deviceType) {
                sql = sql + " and dev.user is null ";
            }else{
            } 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 ";
        sql += " AND b.doctor_id ='" + doctorcode + "' ";
        //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;
        if (StringUtils.isNotBlank(trackFlag) && "1".equals(trackFlag)) {
            sql += " AND tp.del='1' AND tp.doctor_code = '" + doctorcode + "' ";
        }
        List<String> result = jdbcTemplate.queryForList(sql,new Object[]{},String.class);
        List<String> result = jdbcTemplate.queryForList(sql, new Object[]{}, String.class);
        return result;
@ -151,34 +152,35 @@ public class DoctorSchemeService {
    /**
     * 获取医生的血糖监测方案,根据创建时间降序排序,系统方案放最后
     *
     * @param doctorcode
     * @return
     * @throws Exception
     */
    public List<DoctorSchemeBloodSuggerVO> getDoctorScheBloodSuggerList(String doctorcode)  throws Exception {
    public List<DoctorSchemeBloodSuggerVO> getDoctorScheBloodSuggerList(String doctorcode) throws Exception {
        List<DoctorSchemeBloodSuggerVO> result = new ArrayList<>();
        HashMap<String,List<DoctorSchemeBloodSugger>> mapresult = new HashMap<>();
        HashMap<String, List<DoctorSchemeBloodSugger>> mapresult = new HashMap<>();
        LinkedList<String> keys = new LinkedList<>();
        List<DoctorSchemeBloodSugger> schemelist = doctroSchemeBloodSuggerDao.getListByDoctorcode(doctorcode);
        if(!schemelist.isEmpty()){
        if (!schemelist.isEmpty()) {
            for (DoctorSchemeBloodSugger doctorSchemeBloodSugger : schemelist) {
                if(keys.contains(doctorSchemeBloodSugger.getCode())){
                if (keys.contains(doctorSchemeBloodSugger.getCode())) {
                    mapresult.get(doctorSchemeBloodSugger.getCode()).add(doctorSchemeBloodSugger);
                }else{
                } else {
                    List<DoctorSchemeBloodSugger> list = new ArrayList<>();
                    list.add(doctorSchemeBloodSugger);
                    mapresult.put(doctorSchemeBloodSugger.getCode(),list);
                    mapresult.put(doctorSchemeBloodSugger.getCode(), list);
                    keys.add(doctorSchemeBloodSugger.getCode());
                }
            }
            for (String key :keys) {
            for (String key : keys) {
                DoctorSchemeBloodSuggerVO doctorSchemeBloodSuggerVO = new DoctorSchemeBloodSuggerVO();
                doctorSchemeBloodSuggerVO.setCode(key);
                doctorSchemeBloodSuggerVO.setName(mapresult.get(key).get(0).getName());
@ -192,33 +194,31 @@ public class DoctorSchemeService {
    /**
     * 获取医生的血压监测方案,根据创建时间降序排序,系统方案放最后
     *
     * @param doctorcode
     * @return
     * @throws Exception
     */
    public  List<DoctorSchemeBloodPressureVO>  getDoctorSchemeBloodPressureList(String doctorcode) throws Exception{
    public List<DoctorSchemeBloodPressureVO> getDoctorSchemeBloodPressureList(String doctorcode) throws Exception {
        List<DoctorSchemeBloodPressureVO> result = new ArrayList<>();
        HashMap<String,List<DoctorSchemeBloodPressure>> mapresult = new HashMap<>();
        HashMap<String, List<DoctorSchemeBloodPressure>> mapresult = new HashMap<>();
        List<DoctorSchemeBloodPressure> schemelist = doctoreSchemeBloodPressureDao.getListByDoctorcode(doctorcode);
        LinkedList<String> keys = new LinkedList<>();
        if(!schemelist.isEmpty()){
        if (!schemelist.isEmpty()) {
            for (DoctorSchemeBloodPressure doctorSchemeBloodPressure : schemelist) {
                if(keys.contains(doctorSchemeBloodPressure.getCode())){
                if (keys.contains(doctorSchemeBloodPressure.getCode())) {
                    mapresult.get(doctorSchemeBloodPressure.getCode()).add(doctorSchemeBloodPressure);
                }else{
                } else {
                    List<DoctorSchemeBloodPressure> list = new ArrayList<>();
                    list.add(doctorSchemeBloodPressure);
                    mapresult.put(doctorSchemeBloodPressure.getCode(),list);
                    mapresult.put(doctorSchemeBloodPressure.getCode(), list);
                    keys.add(doctorSchemeBloodPressure.getCode());
                }
            }
            for (String key :keys) {
            for (String key : keys) {
                DoctorSchemeBloodPressureVO doctorSchemeBloodPressureVO = new DoctorSchemeBloodPressureVO();
                doctorSchemeBloodPressureVO.setCode(key);
                doctorSchemeBloodPressureVO.setName(mapresult.get(key).get(0).getName());
@ -227,46 +227,37 @@ public class DoctorSchemeService {
                result.add(doctorSchemeBloodPressureVO);
            }
        }
        return result;
    }
    /**
     * 医生保存血糖监测方案
     *
     * @param data
     * @throws Exception
     */
    public void saveDoctorSchemeBloodSugger(String data) throws Exception{
        JSONObject dataObj =  JSON.parseObject(data);
    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)){
        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 (datalist.getJSONObject(i).containsKey("id")) {
                id = datalist.getJSONObject(i).getLong("id");
            }
            if(id != 0){
            if (id != 0) {
                doctorSchemeBloodSugger.setId(datalist.getJSONObject(i).getLong("id"));
            }
            doctorSchemeBloodSugger.setName(name);
            doctorSchemeBloodSugger.setCode(code);
            doctorSchemeBloodSugger.setDoctorcode(doctorcode);
@ -286,52 +277,44 @@ public class DoctorSchemeService {
            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()) {
        if (!results.isEmpty()) {
            doctroSchemeBloodSuggerDao.saveAll(results);
        }
    }
    /**
     * 医生保存血压监测方案
     *
     * @param data
     * @throws Exception
     */
    public void saveDoctorSchemeBloodPressure(String data) throws Exception{
        JSONObject dataObj =  JSON.parseObject(data);
    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)){
        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 (datalist.getJSONObject(i).containsKey("id")) {
                id = datalist.getJSONObject(i).getLong("id");
            }
            if(id != 0){
            if (id != 0) {
                doctorSchemeBloodPressure.setId(datalist.getJSONObject(i).getLong("id"));
            }
            doctorSchemeBloodPressure.setName(name);
            doctorSchemeBloodPressure.setCode(code);
            doctorSchemeBloodPressure.setDoctorcode(doctorcode);
@ -352,8 +335,7 @@ public class DoctorSchemeService {
            doctorSchemeBloodPressure.setDel(0);
            results.add(doctorSchemeBloodPressure);
        }
        if(!results.isEmpty()) {
        if (!results.isEmpty()) {
            doctoreSchemeBloodPressureDao.saveAll(results);
        }
    }
@ -368,30 +350,23 @@ public class DoctorSchemeService {
     * @throws Exception
     */
    @Transactional
    public void savePatientScheme(String doctorcode, String schemecode, String type,String patientcodes) throws Exception {
    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(",")){
        if (patientcodes.contains(",")) {
            for (String code : codes) {
                patientcodeList.add(code);
            }
        }else{
        } 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();
@ -413,8 +388,10 @@ public class DoctorSchemeService {
        }
    }
    /**
     * 医生端-获取慢病管理居民管理端数据
     *
     * @param teamCode
     * @param getcolor
     * @param getstands
@ -423,33 +400,34 @@ public class DoctorSchemeService {
     * @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);
    public JSONObject getSlowDiseaseTeaminfos(String teamCode, int getcolor, int getstands, int gethealthindex, String startdate, String enddate, String doctorcode) throws Exception {
        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));
        String patientsql = "SELECT DISTINCT\n" +
                "	a.id 'code',\n" +
                "	a.standard_status ,\n" +
                "	a.disease,\n" +
                "	a.disease_condition \n" +
                "FROM\n" +
                "	base_patient a \n" +
                "	INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('1','2','1,2','2,1')\n" +
                "AND b.doctor_id ='" + doctorcode + "'";
        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_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();//血糖体征总数
        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();
        //绿标居民
@ -463,11 +441,11 @@ public class DoctorSchemeService {
        //高血糖居民预警居民CODE
        List<String> bloodsugar_patientcodes = new ArrayList<>();
        if(!patients.isEmpty()){
        if (!patients.isEmpty()) {
            for (PatientVO patient : patients) {
                //获取居民颜色标签
                if(1 == getcolor && patient.getDiseaseCondition() != null){
                    switch (patient.getDiseaseCondition()){
                if (1 == getcolor && patient.getDiseaseCondition() != null) {
                    switch (patient.getDiseaseCondition()) {
                        case 0:
                            green_patients.add(patient);
                            break;
@ -481,40 +459,36 @@ public class DoctorSchemeService {
                }
                //获取预警居民CODES
                if(1 == getstands && (patient.getStandardStatus() !=null && patient.getStandardStatus() ==1)){
                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())){
                    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())){
                        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 == getcolor) {
            result.put("greencount", green_patients.size());
            result.put("yellowcount", yellow_patients.size());
            result.put("redcount", red_patients.size());
        }
        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 == getstands) {
            result.put("pressure_standard", bloodpressure_patientcodes);
            result.put("sugar_standard", bloodsugar_patientcodes);
        }
        if(1 == gethealthindex){
        if (1 == gethealthindex) {
            Date start = DateUtil.strToDate(startdate);
            Date end = DateUtil.strToDate(enddate);
            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByTeamcodeAndRecordDate(start,end,teamCode,doctorcode);
//            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByTeamcodeAndRecordDate(start,end,teamCode,doctorcode);
            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByDoctor(start, end, doctorcode);
            int sugar = 0;
            int sugar_unusual = 0;
@ -522,73 +496,69 @@ public class DoctorSchemeService {
            int pressure = 0;
            int pressure_unusual = 0;
            if(!devicePatientHealthIndices.isEmpty()){
            if (!devicePatientHealthIndices.isEmpty()) {
                for (DevicePatientHealthIndex devicePatientHealthIndex : devicePatientHealthIndices) {
                    if( 1 == devicePatientHealthIndex.getType()){
                    if (1 == devicePatientHealthIndex.getType()) {
                        sugar++;
                        if( devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                        if (devicePatientHealthIndex.getStatus() != null && 0 == devicePatientHealthIndex.getStatus()) {
                            sugar_unusual++;
                        }
                    }
                    if( 2 == devicePatientHealthIndex.getType()){
                    if (2 == devicePatientHealthIndex.getType()) {
                        pressure++;
                        if(devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                        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);
            result.put("pressure_count", pressure);
            result.put("pressure_unusual_count", pressure_unusual);
            result.put("sugar_count", sugar);
            result.put("sugar_unusual_count", sugar_unusual);
        }
        //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);
        List<TrackPatient> list = trackPatientDao.findByDoctor(doctorcode, "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{
    public void delDoctorScheme(String doctorcode, String schemecode, String type) throws Exception {
        if("1".equals(type)){
            doctroSchemeBloodSuggerDao.updateDelStatus(1,doctorcode,schemecode);
        if ("1".equals(type)) {
            doctroSchemeBloodSuggerDao.updateDelStatus(1, doctorcode, schemecode);
        }
        if("2".equals(type)){
            doctoreSchemeBloodPressureDao.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){
        if (list != null && list.size() > 0) {
            patientSchemeListDao.deleteAll(list);
        }
    }
    public Map<String,Object> getPatientHealthIndex(String patient,String startDate,String endDate,String type){
    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  " +
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String highSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS highCount " +
                " FROM " +
                " ( " +
@ -601,9 +571,9 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -615,11 +585,11 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) aft";
        String stdSql ="SELECT  " +
        String stdSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS stdCount " +
                " FROM " +
                " ( " +
@ -633,9 +603,9 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -648,11 +618,11 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) aft";
        String lowSql ="SELECT  " +
        String lowSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS lowCount " +
                " FROM " +
                " ( " +
@ -665,9 +635,9 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -679,12 +649,12 @@ public class DoctorSchemeService {
                " 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+"'" +
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'" +
                " ) aft";
        String pHighSql ="SELECT " +
        String pHighSql = "SELECT " +
                " count(1) AS highCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
@ -692,10 +662,10 @@ public class DoctorSchemeService {
                " 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 " +
                " 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 " +
@ -704,10 +674,10 @@ public class DoctorSchemeService {
                " 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 " +
                " 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 " +
@ -715,61 +685,61 @@ public class DoctorSchemeService {
                " 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+"'";
                " AND i.record_date >='" + startDate + "'" +
                " AND i.record_date <='" + endDate + "'" +
                " AND i.user ='" + patient + "'";
        Map<String,Object> rs = new HashedMap();
        Map<String, Object> rs = new HashedMap();
        //0血檀
        if ("0".equals(type)){
        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"));
            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"));
            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"));
            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{
        } 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"));
            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"));
            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"));
            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){
    public Map<String, Object> getPatientHealthIndexNew(String startDate, String endDate, String type, String doctor) {
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String highSql ="SELECT  " +
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String highSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS highCount " +
                " FROM " +
                " ( " +
@ -782,9 +752,10 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -796,11 +767,11 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) aft";
        String stdSql ="SELECT  " +
        String stdSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS stdCount " +
                " FROM " +
                " ( " +
@ -814,9 +785,9 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -829,11 +800,11 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) aft";
        String lowSql ="SELECT  " +
        String lowSql = "SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS lowCount " +
                " FROM " +
                " ( " +
@ -846,9 +817,9 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) bf, " +
                " (  " +
                " SELECT " +
@ -860,12 +831,12 @@ public class DoctorSchemeService {
                " 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+")" +
                " 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 + "' )" +
                " ) aft";
        String pHighSql ="SELECT " +
        String pHighSql = "SELECT " +
                " count(1) AS highCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
@ -873,10 +844,10 @@ public class DoctorSchemeService {
                " 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 " +
                " 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 + "' )";
        String pStdSql = "SELECT " +
                " count(1) AS stdCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
@ -885,10 +856,10 @@ public class DoctorSchemeService {
                " 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 " +
                " 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 + "' )";
        String pLowSql = "SELECT " +
                " count(1) AS lowCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
@ -896,60 +867,60 @@ public class DoctorSchemeService {
                " 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+")";
                " 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 + "')";
        Map<String,Object> rs = new HashedMap();
        Map<String, Object> rs = new HashedMap();
        //0血檀
        if ("0".equals(type)){
        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"));
            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"));
            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"));
            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{
            //其他血压
        } 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"));
            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"));
            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"));
            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();
    public Map<String, Object> getTrackPatientInfo(String patient) {
        Map<String, Object> rs = new HashedMap();
        rs.put("wxSport",0);
        rs.put("wxSport", 0);
        String hsql = "SELECT " +
                " i.value1 AS weight, " +
@ -960,66 +931,65 @@ public class DoctorSchemeService {
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '3'  " +
                " AND i.user ='"+patient+"'" +
                " AND i.user ='" + patient + "'" +
                " ORDER BY " +
                " i.record_date DESC LIMIT 0,1";
        String xtSchSql="SELECT " +
        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 " +
                " 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);
                " 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>> 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);
        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;
        return rs;
    }
    public Map<String,Object> getControlObjectives(String patient){
        Map<String,Object> rs = new HashedMap();
        PatientAimBloodSugger patientAimBloodSugger =  patientAimBloodSuggerDao.findByPatientcode(patient);
    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);
        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";
    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, " +
@ -1031,20 +1001,20 @@ public class DoctorSchemeService {
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = 3 " +
                " AND i.`user` = '"+patient+"' " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'"+
                " 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);
                " 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){
    public String setDoctorSwitchTrackPatient(String doctor, String state) {
        DoctorSwitch doctorSwitch = doctorSwitchDao.findByDoctor(doctor);
        if (doctorSwitch != null) {
            doctorSwitch.setAlertPatientSwitch(state);
        }else{
        } else {
            DoctorSwitch dw = new DoctorSwitch();
            dw.setDoctor(doctor);
            dw.setAlertPatientSwitch(state);
@ -1054,12 +1024,12 @@ public class DoctorSchemeService {
        return "0";
    }
    public Map<String,Object> getDoctorSwitchTrackPatient(String doctor){
    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{
        Map<String, Object> rs = new HashedMap();
        if (doctorSwitch != null) {
            rs.put("alertPatientSwitch", doctorSwitch.getAlertPatientSwitch());
        } else {
            DoctorSwitch dw = new DoctorSwitch();
            dw.setDoctor(doctor);
@ -1067,52 +1037,53 @@ public class DoctorSchemeService {
            dw.setCreateTime(new Date());
            doctorSwitchDao.save(dw);
            rs.put("alertPatientSwitch","0");
            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());
    public Map<String, Object> getTrackPatientCountTitle(String doctor, String startDate, String endDate) {
//        List<TrackPatient> trackPatients = trackPatientDao.findByDoctorCodeAndTeamCodeAndDel(doctor, teamCode, "1");
        List<TrackPatient> trackPatients = trackPatientDao.findByDoctor(doctor, "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);
                " 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){
    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();
        Map<String, Object> rs = new HashedMap();
        //咨询
        rs.put("consultCount",getConsultByteam(teamCode,doctor,startDate,endDate));
        rs.put("consultCount", getConsultByteam(teamCode, doctor, startDate, endDate));
        //随访
        rs.put("followupCount",getFollowByTeam(teamCode,doctor,startDate,endDate));
        rs.put("followupCount", getFollowByTeam(teamCode, doctor, startDate, endDate));
        //获取健康指导
        rs.put("guidanceCount",getGuidanceByTeam(teamCode,doctor,startDate,endDate));
        rs.put("guidanceCount", getGuidanceByTeam(teamCode, doctor, startDate, endDate));
        //获取待预约
        rs.put("reservationCount",getReservationByteam(teamCode,doctor,startDate,endDate));
        rs.put("reservationCount", getReservationByteam(teamCode, doctor, startDate, endDate));
        //续方审核
        rs.put("reviewedCount",getPresCount(teamCode,doctor,startDate,endDate));
        rs.put("reviewedCount", getPresCount(teamCode, doctor, startDate, endDate));
        return rs;
    }
@ -1126,7 +1097,7 @@ public class DoctorSchemeService {
     * @param endDate
     * @return
     */
    public Long getConsultByteam(Long id, String doctor,String startDate, String endDate) {
    public Long getConsultByteam(Long id, String doctor, String startDate, String endDate) {
        String imDataBaseName = im_dataBase_name;
        //咨询量
        String consult_sql = "SELECT " +
@ -1149,98 +1120,98 @@ public class DoctorSchemeService {
                " 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+
                "  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+"'" ;
                " 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");
        return (Long) consultCout.get("consultCount");
    }
    public Long getReservationByteam(Long id,String doctor, String startDate, String endDate) {
    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+") ";
                " 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");
        return (Long) reservationCout.get("reservationCount");
    }
    public Long getEduArticleByTeam(Long id,String doctor, String startDate, String endDate) {
    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+") ";
                " 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");
        return (Long) articleCout.get("articleCount");
    }
    public Long getGuidanceByTeam(Long id,String doctor, String startDate, String endDate) {
    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+") ";
                " 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");
        return (Long) guidanceCout.get("guidanceCount");
    }
    public Long getFollowByTeam(Long id,String doctor, String startDate, String endDate) {
    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+") ";
                " 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");
        return (Long) followupCout.get("followupCount");
    }
    public Long getPresCount(Long id,String doctor, String startDate, String endDate){
        String sql ="SELECT " +
    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+"' " +
                " r.doctor = '" + doctor + "' " +
                " AND p.admin_team_id = " + id +
                " AND r.reviewed_time >= '"+startDate+"' " +
                " AND r.reviewed_time <= '"+endDate+"' " +
                " 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+")";
                " 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");
        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";
    public Map<String, Object> getTrackPatientAimByteam(String doctor, String startDate, String endDate) {
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        String presSql="SELECT " +
        String presSql = "SELECT " +
                " COUNT(1) AS dbCount " +
                " FROM " +
                " ( " +
@ -1252,12 +1223,11 @@ public class DoctorSchemeService {
                "    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+
                "    ) " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='" + doctor + "'   ) " +
                "  AND i.del ='1' " +
                "  AND i.type = 2  " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                "  AND i.record_date >= '" + startDate + "' " +
                "  AND i.record_date <= '" + endDate + "' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
@ -1272,58 +1242,56 @@ public class DoctorSchemeService {
                " 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+
                "    ) " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='" + doctor + "'   ) " +
                "  AND i.value1 <= cast(p.sbp as SIGNED INTEGER) " +
                "  AND i.value1 >= cast(p.sbp_min 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+"' " +
                "  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);
        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));
        List<Map<String, Object>> cqXT = jdbcTemplate.queryForList(getXTAimSQL(doctor, startDate, endDate));
        Long dbSuggerCount;
        if(cqXT!=null&&cqXT.size()>0){
            dbSuggerCount = (Long)cqXT.get(0).get("total");
        }else{
        if (cqXT != null && cqXT.size() > 0) {
            dbSuggerCount = (Long) cqXT.get(0).get("total");
        } else {
            dbSuggerCount = 0L;
        }
        rs.put("dbSuggerCount",dbSuggerCount);
        rs.put("dbSuggerCount", dbSuggerCount);
        return rs;
    }
    /**
     *
     * @param doctor
     * @param teamCode
     * @param startDate
     * @param endDate
     * @param state 0 餐前,1餐_后
     * @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)){
    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)";
            value1min = "cast(p.hpg_min AS SIGNED INTEGER)";
        }
        //餐前血糖达标数
        String xtSql = "SELECT " +
@ -1338,13 +1306,13 @@ public class DoctorSchemeService {
                "    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+
                "     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.value2 in(" + value2 + ") " +
                "  AND i.type = 1  " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                "  AND i.record_date >= '" + startDate + "' " +
                "  AND i.record_date <= '" + endDate + "' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
@ -1359,17 +1327,17 @@ public class DoctorSchemeService {
                " 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+
                "     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+
                "  i.value1 <= " + value1 +
                "  AND  " +
                "  i.value1 >= " +value1min +
                "  AND i.value2 in("+value2+") " +
                "  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+"' " +
                "  AND i.record_date >= '" + startDate + "' " +
                "  AND i.record_date <= '" + endDate + "' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) dbt ON tt.`user`=dbt.`user` " +
@ -1377,7 +1345,7 @@ public class DoctorSchemeService {
        return xtSql;
    }
    public String getXTAimSQL(String doctor ,Long teamCode,String startDate,String endDate){
    public String getXTAimSQL(String doctor,  String startDate, String endDate) {
        String sql = "SELECT " +
                " COUNT(1) total " +
                " FROM " +
@ -1395,13 +1363,13 @@ public class DoctorSchemeService {
                "     wlyy_track_patient p " +
                "    WHERE " +
                "     p.del = '1' " +
                "    AND p.doctor_code = '"+doctor+"' " +
                "    AND p.team_code = " +teamCode+
                "    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+"' " +
                "  AND i.record_date >= '" + startDate + "' " +
                "  AND i.record_date <= '" + endDate + "' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
@ -1420,16 +1388,16 @@ public class DoctorSchemeService {
                "    wlyy_track_patient p " +
                "   WHERE " +
                "    p.del = '1' " +
                "   AND p.doctor_code = '"+doctor+"' " +
                "   AND p.team_code = " +teamCode+
                "   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+"' " +
                " AND i.record_date >= '" + startDate + "' " +
                " AND i.record_date <= '" + endDate + "' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) dbt ON tt.`user` = dbt.`user`  " +
@ -1448,16 +1416,16 @@ public class DoctorSchemeService {
                "    wlyy_track_patient p " +
                "   WHERE " +
                "    p.del = '1' " +
                "   AND p.doctor_code = '"+doctor+"' " +
                "   AND p.team_code =  " +teamCode +
                "   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+"' " +
                " AND i.record_date >= '" + startDate + "' " +
                " AND i.record_date <= '" + endDate + "' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) cht ON tt.`user` = cht.`user` " +
@ -1466,8 +1434,8 @@ public class DoctorSchemeService {
        return sql;
    }
    public Map<String,Object> getDeviceStateByTeam(String doctor ,Long teamCode){
        String sql ="SELECT " +
    public Map<String, Object> getDeviceStateByTeam(String doctor) {
        String sql = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wlyy_patient_device d JOIN  " +
@ -1475,51 +1443,51 @@ public class DoctorSchemeService {
                " WHERE  " +
                " t.del='1' " +
                " AND d.category_code = ? " +
                " AND t.doctor_code = '"+doctor+"' " +
                " AND t.team_code = "+teamCode;
        Map<String,Object> rs = new HashedMap();
                " 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>> 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);
        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 ){
    public String setSinglePatientAim(String patient, String suggerJson, String presJson, String sportJson) {
        PatientAimBloodSugger sugger = patientAimBloodSuggerDao.findByPatientcode(patient);
        if(sugger!=null){
        if (sugger != null) {
            patientAimBloodSuggerDao.delete(sugger);
        }
        PatientAimBloodPressure pres = patientAimBloodPressureDao.findByPatientcode(patient);
        if(pres!=null){
        if (pres != null) {
            patientAimBloodPressureDao.delete(pres);
        }
        PatientAimSports sport = patientAimSportsDao.getPatientAimSportsByPatientCode(patient);
        if(sport!=null){
        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);
        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 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());
@ -1540,30 +1508,29 @@ public class DoctorSchemeService {
    }
    public String setPatientAim(String patients ,String suggerJson,String presJson,String sportJson){
        if(StringUtils.isNotBlank(patients)){
    public String setPatientAim(String patients, String suggerJson, String presJson, String sportJson) {
        if (StringUtils.isNotBlank(patients)) {
            String[] patient = patients.split(",");
            for(String p : patient){
            for (String p : patient) {
                PatientAimBloodSugger sugger = patientAimBloodSuggerDao.findByPatientcode(p);
                if(sugger!=null){
                if (sugger != null) {
                    patientAimBloodSuggerDao.delete(sugger);
                }
                PatientAimBloodPressure pres = patientAimBloodPressureDao.findByPatientcode(p);
                if(pres!=null){
                if (pres != null) {
                    patientAimBloodPressureDao.delete(pres);
                }
                PatientAimSports sport = patientAimSportsDao.getPatientAimSportsByPatientCode(p);
                if(sport!=null){
                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);
                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());
@ -1585,56 +1552,56 @@ public class DoctorSchemeService {
    }
    public Map<String,Object> getPatientScheme(String patient,String type){
        Map<String,Object> rs = new HashedMap();
        String sql =null;
        if("1".equals(type)){
            sql =  "SELECT " +
    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+"'" +
                    " AND l.patientcode='" + patient + "'" +
                    " ORDER BY s.dayofweek ASC";
        }else{
            sql =  "SELECT " +
        } 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+"'" +
                    " AND l.patientcode='" + patient + "'" +
                    " ORDER BY s.dayofweek ASC";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        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);
        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";
    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));
        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));
        } 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){
    public String getXTTrackPatientIndexCountListSql(String doctor, Integer teamCode, String startDate, String endDate, String keyword, Integer page, Integer size) {
        String sql = "SELECT  " +
                " tt1.patient_code, " +
@ -1666,8 +1633,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code = " +teamCode+
                "    AND tp.doctor_code = '" + doctor + "' " +
                "    AND tp.team_code = " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1680,8 +1647,8 @@ public class DoctorSchemeService {
                "   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+"'" +
                "   AND i.record_date >='" + startDate + "'" +
                "   AND i.record_date <='" + endDate + "'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
@ -1701,8 +1668,8 @@ public class DoctorSchemeService {
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code =" +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code =" + teamCode +
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
@ -1715,8 +1682,8 @@ public class DoctorSchemeService {
                "  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+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
@ -1743,8 +1710,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code =  " +teamCode+
                "    AND tp.doctor_code = '" + doctor + "' " +
                "    AND tp.team_code =  " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1757,8 +1724,8 @@ public class DoctorSchemeService {
                "   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+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
@ -1778,8 +1745,8 @@ public class DoctorSchemeService {
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code =  " +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code =  " + teamCode +
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
@ -1792,8 +1759,8 @@ public class DoctorSchemeService {
                "  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+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
@ -1821,8 +1788,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code = " +teamCode +
                "    AND tp.doctor_code = '" + doctor + "' " +
                "    AND tp.team_code = " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1836,8 +1803,8 @@ public class DoctorSchemeService {
                "   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+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
@ -1857,8 +1824,8 @@ public class DoctorSchemeService {
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code = " + teamCode +
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
@ -1872,8 +1839,8 @@ public class DoctorSchemeService {
                "  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+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
@ -1882,20 +1849,20 @@ public class DoctorSchemeService {
                " )tt3 ON tt1.patient_code = tt3.patient_code " +
                " " +
                " JOIN wlyy_patient p On tt1.patient_code =p.code";
        if(StringUtils.isNotBlank(keyword)){
        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+"%' ";
            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 ;
        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  " +
    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, " +
@ -1918,8 +1885,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code = " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1931,8 +1898,8 @@ public class DoctorSchemeService {
                "    i.del = '1' " +
                "   AND i.type = 2 " +
                "   AND i.value1 < 90 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
@ -1950,8 +1917,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code = " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1964,8 +1931,8 @@ public class DoctorSchemeService {
                "   AND i.type = 2 " +
                "   AND i.value1 >= 90 " +
                "   AND i.value1 <=139 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  AND i.record_date >='" + startDate + "'" +
                "  AND i.record_date <='" + endDate + "'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
@ -1984,8 +1951,8 @@ public class DoctorSchemeService {
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   AND tp.doctor_code = '" + doctor + "' " +
                "   AND tp.team_code = " + teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
@ -1997,58 +1964,58 @@ public class DoctorSchemeService {
                "    i.del = '1' " +
                "   AND i.type = 2 " +
                "   AND i.value1 >139 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  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)){
        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+"%' ";
            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;
        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();
    public Map<String, Object> getDefaultScheme(String type) {
        Map<String, Object> rs = new HashedMap();
        //1. 血糖2.血压
        if("1".equals(type)){
        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{
            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);
            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){
    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){
        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){
        } else {
            List<PatientSchemeList> list = patientSchemeListDao.findByPatientcodeAndSchemecodeAndType(patient, "default", 2);
            if (list != null && list.size() > 0) {
                return "-1";
            }
            pl.setType(2);
@ -2065,6 +2032,7 @@ public class DoctorSchemeService {
    /**
     * 查看指定医生是否开启分派订单功能
     *
     * @param doctor
     * @return
     */
@ -2078,11 +2046,12 @@ public class DoctorSchemeService {
    /**
     * 修改指定医生的分派订单开关,不存在该医生的开关,则创建
     *
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusByDoctor(String doctor, String dispatchOrderStatus) {
        DoctorSwitch doctorSwitch =doctorSwitchDao.findByDoctor(doctor);
        DoctorSwitch doctorSwitch = doctorSwitchDao.findByDoctor(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setDispatchOrderSwitch(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
@ -2095,17 +2064,17 @@ public class DoctorSchemeService {
        doctorSwitchDao.save(doctorSwitch);
    }
    public JSONObject patientsByDoctorAndLabelCode(String labelCode, String doctorCode){//1,2改变。
    public JSONObject patientsByDoctorAndLabelCode(String labelCode, String doctorCode) {//1,2改变。
        StringBuilder sqlLabelStr = new StringBuilder();
        sqlLabelStr.append(" sp.label in ('").append(labelCode.replace(",","','")).append("') ");
        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+"'";
                "  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));
        patients = jdbcTemplate.query(patientsql, new BeanPropertyRowMapper(PatientVO.class));
        JSONObject result = new JSONObject();
        //绿标居民
        List<PatientVO> green_patients = new ArrayList<>();
@ -2113,11 +2082,11 @@ public class DoctorSchemeService {
        List<PatientVO> yellow_patients = new ArrayList<>();
        //红标居民
        List<PatientVO> red_patients = new ArrayList<>();
        if(!patients.isEmpty()){
        if (!patients.isEmpty()) {
            for (PatientVO patient : patients) {
                //获取居民颜色标签
                if(patient.getDiseaseCondition() != null){
                    switch (patient.getDiseaseCondition()){
                if (patient.getDiseaseCondition() != null) {
                    switch (patient.getDiseaseCondition()) {
                        case 0:
                            green_patients.add(patient);
                            break;
@ -2133,15 +2102,15 @@ public class DoctorSchemeService {
                }
            }
        }
        result.put("greencount",green_patients.size());
        result.put("yellowcount",yellow_patients.size());
        result.put("redcount",red_patients.size());
        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);
        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;
    }
@ -2149,4 +2118,108 @@ public class DoctorSchemeService {
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public static ExecutorService execute = Executors.newFixedThreadPool(20);
    /**
     * 获取红黄绿标高血压糖尿病的指标人数
     * disease 1高血压,2糖尿病,3高血压+糖尿病
     * 预警数量   a.standard_status='1'
     *
     * @return
     */
    public HashMap<String, Object> getLabelCount(String doctorId) throws ExecutionException, InterruptedException {
        // 高血压预警
        String sql01 = "SELECT count(DISTINCT  a.id)\n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.standard_status='1'\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('1','3') \n" +
                "AND b.doctor_id ='" + doctorId + "'";
        // 高血压
        String sql02 = "SELECT count(DISTINCT  a.id)\n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('1','3') \n" +
                "AND b.doctor_id ='" + doctorId + "'";
        // 糖尿病预警
        String sql03 = "SELECT count(DISTINCT  a.id)\n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.standard_status='1'\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('2','3') \n" +
                "AND b.doctor_id ='" + doctorId + "'";
        // 糖尿病
        String sql04 = "SELECT count(DISTINCT  a.id)\n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND a.disease IN ('2','3') \n" +
                "AND b.doctor_id ='" + doctorId + "'";
        CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            Integer count = jdbcTemplate.queryForObject(sql01, Integer.class);
            return count;
        }, execute);
        CompletableFuture<Integer> future02 = CompletableFuture.supplyAsync(() -> {
            Integer count = jdbcTemplate.queryForObject(sql02, Integer.class);
            return count;
        }, execute);
        CompletableFuture<Integer> future03 = CompletableFuture.supplyAsync(() -> {
            Integer count = jdbcTemplate.queryForObject(sql03, Integer.class);
            return count;
        }, execute);
        CompletableFuture<Integer> future04 = CompletableFuture.supplyAsync(() -> {
            Integer count = jdbcTemplate.queryForObject(sql04, Integer.class);
            return count;
        }, execute);
        CompletableFuture.allOf(future01, future02, future03, future04).get();
        Integer count1 = future01.get();// 高血压预警
        Integer count2 = future02.get();// 高血压
        Integer count3 = future03.get();// 糖尿病预警
        Integer count4 = future04.get();// 糖尿病
        HashMap<String, Object> map = new HashMap<>();
        map.put("gxy_yj", count1);// 高血压预警
        map.put("gxy", count2);// 高血压预警
        map.put("tnb_yj", count3);// 高血压预警
        map.put("tnb", count4);// 高血压预警
        return map;
    }
    /**
     * labelType 1高血压 2糖尿病
     */
    public List<Map<String, Object>> getLabelDetail(String doctorId, String labelType, String searchContent, int page, int pageSize) {
        String sql = "SELECTDISTINCT a.id,a.`name`,a.idcard,a.mobile,a.ssc, TIMESTAMPDIFF(YEAR, a.birthday, CURDATE()) AS age ,a.sex \n" +
                "FROM base_patient a \n" +
                "INNER JOIN base_patient_doctor_relation b ON a.id=b.patient_id\n" +
                "WHERE 1=1\n" +
                "AND a.disease_condition IN('1','2','3')\n" +
                "AND b.doctor_id ='" + doctorId + "'";
        if (StringUtils.isNotBlank(labelType)) {
            if ("1".equals(labelType)) {
                sql += "AND a.disease IN ('1','3') \n";
            }
            if ("2".equals(labelType)) {
                sql += "AND a.disease IN ('2','3') \n";
            }
        }
        if (StringUtils.isNotBlank(searchContent)) {
            sql += " AND a.`name` LIKE '%" + searchContent + "%' ";
        }
        sql += " LIMIT  " + (page - 1) * pageSize + "," + pageSize + "";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}

+ 59 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorFeldsherTemplateController.java

@ -0,0 +1,59 @@
package com.yihu.jw.hospital.module.template.controller;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.template.service.DoctorFeldsherTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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;
/**
 * 医生健康指导模板
 * <p>
 * Created by Reece on 2017/9/14.
 */
@RestController
@RequestMapping(value = "/doctor/feldsher")
@Api(description = "医生健康指导模板")
public class DoctorFeldsherTemplateController extends BaseController {
    @Autowired
    private DoctorFeldsherTemplateService feldsherTemplateService;
    /**
     * @param doctorCode   医生code
     * @param sessionId    会话Id
     * @param sessionType  会话类型
     * @param businessType 消息类型
     * @param from         发送者
     * @param content      消息内容
     * @return
     */
    @RequestMapping(value = "/sendDoctorTemplate", method = RequestMethod.GET)
    @ApiOperation(value = "医生助手给医生发送模板消息")
    public String sendDoctorTemplate(@RequestParam @ApiParam(value = "医生code") String doctorCode,
                                     @RequestParam @ApiParam(value = "会话Id", required = false) String sessionId,
                                     @RequestParam @ApiParam(value = "会话类型", required = false) String sessionType,
                                     @RequestParam @ApiParam(value = "消息类型") String businessType,
                                     @RequestParam @ApiParam(value = "发送者", required = false) String from,
                                     @RequestParam @ApiParam(value = "消息内容") String content) {
        try {
            Boolean flag = feldsherTemplateService.sendDoctorTemplate(doctorCode, sessionId, sessionType, businessType, from, content);
            if (flag){
                return write(200, "发送成功!");
            }else {
                return write( -1, "发送失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return invalidUserException(e, -1, "发送失败!");
        }
    }
}

+ 235 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorGuidanceTempController.java

@ -0,0 +1,235 @@
package com.yihu.jw.hospital.module.template.controller;
import com.yihu.jw.entity.template.DoctorGuidanceTemp;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempDao;
import com.yihu.jw.hospital.module.template.service.DoctorGuidanceTempService;
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.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;
import java.util.Map;
/**
 * 医生健康指导模板
 * <p>
 * Created by lyr on 2017/2/3.
 */
@RestController
@RequestMapping(value = "/doctor/guidance_temp")
@Api(description = "医生健康指导模板")
public class DoctorGuidanceTempController extends BaseController {
    @Autowired
    DoctorGuidanceTempService guidanceTempService;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    /**
     * 查询单个模板详情
     *
     * @return
     */
    @RequestMapping(value = "/listDetail", method = RequestMethod.GET)
    @ApiOperation(value = "查询单个模板详情")
    public String listDetail(@RequestParam @ApiParam(value = "指导模板编码") String modelCode) {
        JSONObject temp = null;
        try {
            temp = guidanceTempService.listDetail(modelCode);
        } catch (Exception e) {
            e.printStackTrace();
            return invalidUserException(e, -1, "查询失败!");
        }
        return write(200, "查询成功!", "data", temp);
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加指导模板")
   
    public String add(@RequestParam @ApiParam(value = "指导内容") String content,
                      @RequestParam @ApiParam(value = "模板名称") String modelName,
                      @RequestParam(required = false) @ApiParam(value = "图片内容") String imagesUrl) {
        try {
            if (StringUtils.isEmpty(content)) {
                return error(-1, "内容不能为空");
            }
            if (modelName.length() < 1 || modelName.length() > 10) {
                return error(-1, "模板名称不能为空且在10字之内");
            }
            //        验证模板名称唯一性
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(getUID(), modelName);
            if (templates != null && templates.size() != 0) {
                return error(-1, "模板名称与现有模板重复,请修改");
            }
            DoctorGuidanceTemp temp = guidanceTempService.add(getUID(), content, modelName, imagesUrl);
            if (temp != null) {
                return write(200, "添加成功","modelCode",temp.getCode());
            } else {
                return write(-1, "添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "添加失败");
        }
    }
    /**
     * 修改指导模板
     *
     * @param code
     * @param content
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ApiOperation(value = "修改指导模板")
   
    public String modify(@RequestParam @ApiParam(value = "指导编码") String code,
                         @RequestParam @ApiParam(value = "模板标题") String modelName,
                         @RequestParam @ApiParam(value = "指导内容") String content,
                         @RequestParam(required = false) @ApiParam(value = "图片地址") String imagesUrl
    ) {
        try {
            if (StringUtils.isEmpty(code)) {
                return error(-1, "请指定需修改的模板");
            }
            if (StringUtils.isEmpty(content)) {
                return error(-1, "内容不能为空");
            }
            if (StringUtils.isEmpty(modelName) || modelName.length() > 10) {
                return error(-1, "内容10个汉字之内且不能为空");
            }
//            验证模板名称唯一性 还要去除掉其本身  (判断查出来的和要修改的同名)
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(getUID(), modelName);
            for (DoctorGuidanceTemp teamplate : templates) {
                if (!code.equals(teamplate.getCode())) {
//                        不是修改同一个模板
                    return error(-1, "模板名称与现有模板重复,请修改");
                }
            }
            DoctorGuidanceTemp temp = guidanceTempService.modify(code, modelName, content, imagesUrl);
            if (temp != null) {
                return write(200, "修改成功");
            } else {
                return write(-1, "修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "修改失败");
        }
    }
    /**
     * 删除指导模板
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除指导模板")
   
    public String delete(@RequestParam @ApiParam(value = "指导编码") String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                return error(-1, "请指定需删除的模板");
            }
            int result = guidanceTempService.delete(code);
            if (result == 1) {
                return write(200, "删除成功");
            } else {
                return write(-1, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "删除失败");
        }
    }
    /**
     * 查询指导模板
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "查询指导模板")
    public String list(
                       @RequestParam(required = false, defaultValue = "")
                       @ApiParam(value = "搜索关键字") String filter,
                       @RequestParam(required = false, defaultValue = "")
                       @ApiParam(value = "模板类型 1:系统 2:自定义 为空:所有") String type,
                       @RequestParam(defaultValue = "10") String pageSize,
                       @RequestParam(defaultValue = "1") @ApiParam(value = "当前页码") String pageNo) {
        try {
            int pagesize = Integer.parseInt(pageSize);
            int pageno = Integer.parseInt(pageNo) - 1;
            List<Map<String, Object>> temps = guidanceTempService.list(getUID(),filter, type, pagesize, pageno);
            if (temps == null || temps.size() < 1) {
                return write(200, "查询成功", "data", new JSONArray());
            } else {
                return write(200, "查询成功", "data", new JSONArray(temps));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据模板类型、文章标题模糊搜索指导模板
     * (自定义即个人模板)
     * @param filter  搜索关键字
     * @param type  模板类型
     * @param type  teamId
     * @param pageSize 页展示数量
     * @param pageNo  当前页码
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ApiOperation(value = "模糊搜索指导模板")
    public String searchByTitle(
                        @RequestParam(required = true, defaultValue = "")
                        @ApiParam(value = "搜索关键字") String filter,
                        @RequestParam(required = true, defaultValue = "")
                        @ApiParam(value = "模板类型 1:系统 2:个人 3:团队摸版") String type,
                        @RequestParam(defaultValue = "10")
                        @ApiParam(value = "页展示数量") String pageSize,
                        @RequestParam(defaultValue = "1") @ApiParam(value = "当前页码") String pageNo) {
        try {
            int pagesize = Integer.parseInt(pageSize);
            int pageno = Integer.parseInt(pageNo) - 1;
            List<Map<String, Object>> temps = null;
            if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(filter)){
                temps = guidanceTempService.listByTitle(filter,type,pagesize, pageno);
            }else {
                return error(-1, "模板类型不能为空!");
            }
            if (temps == null || temps.size() < 1) {
                return write(200, "查询成功!", "data", new JSONArray());
            } else {
                return write(200, "查询成功!", "data", new JSONArray(temps));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
}

+ 131 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorGuidanceTempLabelController.java

@ -0,0 +1,131 @@
package com.yihu.jw.hospital.module.template.controller;
import com.yihu.jw.entity.template.DoctorGuidanceTempLabel;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempLabelDao;
import com.yihu.jw.hospital.module.template.service.DoctorGuidanceTempLableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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;
/**
 * Created by 刘文彬 on 2018/5/18.
 */
@RestController
@RequestMapping(value = "/doctor/guidance_temp/lable")
@Api(description = "医生健康指导模板标签")
public class DoctorGuidanceTempLabelController extends BaseController {
    @Autowired
    private DoctorGuidanceTempLableService doctorGuidanceTempLableService;
    @Autowired
    private DoctorGuidanceTempLabelDao doctorGuidanceTempLableDao;
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加指导模板标签")
    
    public String save(@ApiParam(name = "name", value = "标签名称", required = true)
                        @RequestParam(value = "name", required = true) String name,
                        @ApiParam(name = "teamId", value = "医生团队id", required = true)
                        @RequestParam(value = "teamId", required = true) Integer teamId){
        try{
            DoctorGuidanceTempLabel doctorGuidanceTempLabel = doctorGuidanceTempLableDao.findByNameWithDel(teamId,name);
            if(doctorGuidanceTempLabel!=null){
                return error(-1,"标签名称已存在!");
            }
            DoctorGuidanceTempLabel doctorGuidanceTempLable = doctorGuidanceTempLableService.save(getUID(),name,teamId);
            if(doctorGuidanceTempLable!=null){
                return write(200,"保存标签成功!","data",doctorGuidanceTempLable);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"保存标签失败!");
        }
        return error(-1,"保存标签失败!");
    }
    @RequestMapping(value = "/findAllList", method = RequestMethod.GET)
    @ApiOperation(value = "根据团队id获取标签")
    
    public String findAllList(@ApiParam(name = "teamId", value = "医生团队id", required = true)
                               @RequestParam(value = "teamId", required = true) Integer teamId){
        try{
            List<DoctorGuidanceTempLabel> list = doctorGuidanceTempLableService.findByDoctorCode(teamId);
            if (list == null || list.size() < 1) {
                return write(200, "查询成功!");
            } else {
                return write(200, "查询成功!", "data", list);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败!");
        }
    }
    @RequestMapping(value = "/findAllListByPage", method = RequestMethod.GET)
    @ApiOperation(value = "根据团队id获取标签(分页)")
    public String findAllListByPage(@ApiParam(name = "pageSize", value = "每页总数", required = true)
                              @RequestParam(value = "pageSize", required = true,defaultValue = "10") int pageSize,
                              @ApiParam(name = "pageNo", value = "当前页", required = true)
                              @RequestParam(value = "pageNo", required = true,defaultValue = "1") int pageNo,
                              @ApiParam(name = "teamId", value = "医生团队id", required = true)
                              @RequestParam(value = "teamId", required = true) Integer teamId){
        try{
            List<DoctorGuidanceTempLabel> list = doctorGuidanceTempLableService.findByDoctorCode(teamId, pageSize, pageNo);
            if (list == null || list.size() < 1) {
                return write(200, "查询成功!");
            } else {
                return write(200, "查询成功!", "data", list);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败!");
        }
    }
    @RequestMapping(value = "/deleteLabel", method = RequestMethod.POST)
    @ApiOperation(value = "删除健康指导模板标签")
    
    public String deleteLabel(@ApiParam(name = "code", value = "标签code", required = true)
                              @RequestParam(value = "code", required = true) String code){
        try {
            boolean b = doctorGuidanceTempLableService.delete(code);
            if(b){
                return success("删除成功!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"删除成功!");
        }
        return error(-1,"删除成功!");
    }
    @RequestMapping(value = "/updateLabel", method = RequestMethod.POST)
    @ApiOperation(value = "修改健康指导模板标签")
    
    public String updateLabel(@ApiParam(name = "code", value = "标签code", required = true)
                              @RequestParam(value = "code", required = true) String code,
                              @ApiParam(name = "name", value = "标签名称", required = true)
                              @RequestParam(value = "name", required = true) String name){
        try {
            boolean b = doctorGuidanceTempLableService.updateName(code,name);
            if(b){
                return success("修改成功!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"修改失败!");
        }
        return error(-1,"修改失败!");
    }
}

+ 202 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorRegistrationTempController.java

@ -0,0 +1,202 @@
package com.yihu.jw.hospital.module.template.controller;
import com.yihu.jw.entity.door.DoctorRegistration;
import com.yihu.jw.entity.door.DoctorRegistrationTemp;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.door.dao.DoctorRegistrationTempDao;
import com.yihu.jw.hospital.module.door.service.DoctorRegistrationTempService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.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.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 医生登记服务模板
 * Created by wangpeiqiang on 2019/3/12.
 */
@RestController
@RequestMapping(value = "/doctor/registration_temp")
@Api(description = "医生登记服务模板")
public class DoctorRegistrationTempController extends BaseController {
    @Autowired
    DoctorRegistrationTempDao doctorRegistrationTempDao;
    @Autowired
    DoctorRegistrationTempService doctorRegistrationTempService;
    @RequestMapping(value = "/getRegistrationTempData", method = RequestMethod.GET)
    @ApiOperation(value = "查询模板分类列表")
    public String getRegistrationTempData(@RequestParam(required = false, defaultValue = "")
                                          @ApiParam(value = "搜索关键字") String filter) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, Object>> registrationTemp = this.doctorRegistrationTempService.getRegistrationTempData(filter);
            map.put("registrationTemp", registrationTemp);
            if (map == null || map.size() < 1) {
                return write(200, "查询成功!");
            } else {
                return write(200, "查询成功!", "data", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/getListByDoctorCode", method = RequestMethod.GET)
    @ApiOperation(value = "根据医生code查询模板分类列表")
    public String getListByDoctorCode(@RequestParam(required = false, defaultValue = "")
                                      @ApiParam(value = "搜索关键字") String filter) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, Object>> allList = this.doctorRegistrationTempService.getListByDoctorCode(getUID(), filter);
            map.put("allList", allList);
            if (map == null || map.size() < 1) {
                return write(200, "查询成功!");
            } else {
                return write(200, "查询成功!", "data", map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 查询单个模板详情
     *
     * @return
     */
    @RequestMapping(value = "/listDetail", method = RequestMethod.GET)
    @ApiOperation(value = "查询单个模板详情")
    public String listDetail(@RequestParam @ApiParam(value = "登记服务模板编码") String modelCode) {
        JSONObject temp = null;
        try {
            temp = doctorRegistrationTempService.listDetail(modelCode);
        } catch (Exception e) {
            e.printStackTrace();
            return invalidUserException(e, -1, "查询失败!");
        }
        return write(200, "查询成功!", "data", temp);
    }
    @RequestMapping(value = "/findAllRegistrationList", method = RequestMethod.GET)
    @ApiOperation(value = "查询所有一级模板列表")
    public String findAllList() {
        try {
            List<DoctorRegistration> list = doctorRegistrationTempService.findAllRegistrationList();
            if (list == null || list.size() < 1) {
                return write(200, "查询成功!");
            } else {
                return write(200, "查询成功!", "data", list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加登记服务模板")
    public String add(
            @ApiParam(name = "content", value = "内容", required = true)
            @RequestParam(value = "content", required = true) String content,
            @ApiParam(name = "registration", value = "一级模板Code", required = true)
            @RequestParam(value = "registration", required = true) String registration) {
        try {
            if (StringUtils.isEmpty(content)) {
                return error(-1, "内容不能为空");
            }
            if (StringUtils.isEmpty(registration)) {
                return error(-1, "一级模板code不能为空");
            }
            DoctorRegistrationTemp temp = doctorRegistrationTempService.add(getUID(), content, registration);
            if (temp != null) {
                return write(200, "添加成功", "data", temp);
            } else {
                return write(-1, "添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "添加失败");
        }
    }
    /**
     * 修改登记服务模板
     *
     * @param code
     * @param content
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ApiOperation(value = "修改登记服务模板")
    public String modify(@RequestParam @ApiParam(value = "登记服务编码") String code,
                         @RequestParam @ApiParam(value = "内容") String content
    ) {
        try {
            if (StringUtils.isEmpty(code)) {
                return error(-1, "请指定需修改的模板");
            }
            if (StringUtils.isEmpty(content)) {
                return error(-1, "内容不能为空");
            }
            DoctorRegistrationTemp temp = doctorRegistrationTempService.modify(code, content);
            if (temp != null) {
                return write(200, "修改成功");
            } else {
                return write(-1, "修改失败");
            }
        }  catch (Exception e) {
            e.printStackTrace();
            return error(-1, "修改失败");
        }
    }
    /**
     * 删除登记服务模板
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除登记服务模板")
    public String delete(@RequestParam @ApiParam(value = "登记服务编码") String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                return error(-1, "请指定需删除的模板");
            }
            int result = doctorRegistrationTempService.delete(code);
            if (result == 1) {
                return write(200, "删除成功");
            } else {
                return write(-1, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "删除失败");
        }
    }
}

+ 323 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/controller/DoctorTeamGuidanceController.java

@ -0,0 +1,323 @@
package com.yihu.jw.hospital.module.template.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.template.DoctorGuidanceTemp;
import com.yihu.jw.entity.template.DoctorTeamGuidanceTemplate;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempDao;
import com.yihu.jw.hospital.module.template.service.DoctorTeamGuidanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 医生端、后端团队指导模板控制类
 */
@Controller
@RequestMapping(value = "/doctor/team/guidance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端&后端团队指导模板")
public class DoctorTeamGuidanceController extends BaseController {
    @Autowired
    private DoctorTeamGuidanceService doctorTeamGuidanceService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    /**
     * 获取医生所属的所有团队
     *
     * @return
     */
//    @RequestMapping(value = "/getDoctorTeams", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取医生所属的所有团队")
//    public String getHealthIndexHistory(@RequestParam(required = false, defaultValue = "") @ApiParam(value = "搜索关键字") String filter) {
//        try {
//            String doctorCode = getUID();
//            List teamList = doctorTeamGuidanceService.getDoctorTeams(doctorCode,filter);
//            return write(200, "获取医生所属团队成功!", "teamList", teamList);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, e.getMessage());
//        }
//    }
    /**
     * 获取医生所属的所有团队
     *
     * @return
     */
//    @RequestMapping(value = "/findDoctorLeaderTeam", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取团队长所属的团队长团队")
//    public String findDoctorLeaderTeam(@RequestParam(required = false, defaultValue = "") @ApiParam(value = "搜索关键字") String filter) {
//        try {
//            String doctorCode = getUID();
//            List teamList = doctorTeamGuidanceService.findDoctorLeaderTeam(doctorCode,filter);
//            return write(200, "获取医生所属团队成功!", "teamList", teamList);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, e.getMessage());
//        }
//    }
    /**
     * 根据医生所属的单个团队获取团队模板列表
     *
     * @param teamId
     * @return
     */
    @RequestMapping(value = "/getTeamGuidanceList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取单个团队模板列表")
    public String getTeamGuidanceList(
                                      @RequestParam(required = false, defaultValue = "")
                                      @ApiParam(value = "搜索关键字") String filter,
                                      @RequestParam(required = false, defaultValue = "")
                                      @ApiParam(value = "团队ID") Integer teamId,
                                      @RequestParam int pageNo,
                                      @RequestParam int pageSize) {
        try {
            List list = doctorTeamGuidanceService.getTeamGuidanceList(getUID(),filter,teamId, pageNo - 1, pageSize);
            return write(200, "获取团队模板列表成功!", "templateList", list);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 根据团队模板编码获取单个模板详情
     *
     * @return
     */
    @RequestMapping(value = "/getTeamGuidanceDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取单个模板详情")
    public String getTeamGuidanceDetail(
            @ApiParam(value = "团队编码")
            @RequestParam int teamId,
            @ApiParam(value = "团队模板编码")
            @RequestParam String teamTemplateCode) {
        try {
            JSONObject guidanceDetail = doctorTeamGuidanceService.getTeamGuidanceDetail(teamId, teamTemplateCode);
            return write(200, "获取模板详情成功!", "guidanceDetail", guidanceDetail);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 新增团队模板
     *
     * @param title    模板标题要排重,团队内不可重复
     * @param teamInfo 该模板所属的团队ID及名称 可能会有多个
     * @param content  模板内容,前端限10000,后端无限制
     * @param images   多图以,分隔,取值1-9图,
     * @return
     */
    @RequestMapping(value = "/saveTeamGuidance", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增团队模板")
    
    public String saveTeamGuidance(
            @ApiParam(value = "团队模板标题")
            @RequestParam String title,
            @ApiParam(value = "所属团队ID及名称json串", defaultValue = "[{\"teamName\":\"一农\",\"teamId\":212},{\"teamName\":\"一\",\"teamId\":21}]")
            @RequestParam String teamInfo,
            @ApiParam(value = "模板内容")
            @RequestParam String content,
            @ApiParam(value = "图片路径")
            @RequestParam(required = false) String images,
            @ApiParam(value = "指导标签")
            @RequestParam(required = false,defaultValue = "") String labelCode
    ) {
        try {
//            前端参数校验
            String doctor = getUID();
            JSONArray teams = new JSONArray(teamInfo);
            String guidanceCode = doctorTeamGuidanceService.saveTeamGuidance(doctor, title, teams, content, images,labelCode);
            return write(200, "保存团队模板成功!","guidanceCode",guidanceCode);
        }catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 修改团队模板
     *
     * @param saveAsGuidance 团队模板是否保存为个人模板 0否 1是
     * @param title          模板标题要排重,团队内不可重复
     * @param teamInfo       该模板所属的团队ID及名称 可能会有多个
     * @param content        模板内容,前端限10000,后端无限制
     * @param images         多图以,分隔,取值0-9图,
     * @return
     */
    @RequestMapping(value = "/modifyTeamGuidance", method = RequestMethod.POST)
    @ResponseBody
    
    @ApiOperation("修改团队模板")
    public String modifyTeamGuidance(
            @ApiParam(value = "团队模板团队模板是否保存为个人模板", defaultValue = "0")
            @RequestParam int saveAsGuidance,
            @ApiParam(value = "要修改的团队模板编号")
            @RequestParam String guidanceCode,
            @ApiParam(value = "团队模板标题")
            @RequestParam String title,
            @ApiParam(value = "所属团队ID及名称json串", defaultValue = "[{\"teamName\":\"一农\",\"teamId\":212},{\"teamName\":\"一\",\"teamId\":21}]")
            @RequestParam String teamInfo,
            @ApiParam(value = "模板内容")
            @RequestParam String content,
            @ApiParam(value = "是否团队长")
            @RequestParam String isLeader,
            @ApiParam(value = "图片路径")
            @RequestParam(required = false) String images,
            @ApiParam(value = "指导标签")
            @RequestParam(required = false,defaultValue = "") String labelCode) {
        try {
//            新增修改权限,只有创建者和团队长才能修改
            String result = "";
            Boolean isRepeat = false;
            String doctor = getUID();
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(doctor, title);
            if (templates != null && templates.size() != 0) {
                isRepeat = true;
                result = "个人模板标题重复";
            }
            JSONArray teams = new JSONArray(teamInfo);
            doctorTeamGuidanceService.modifyTeamGuidance(doctor, isLeader, saveAsGuidance, isRepeat, guidanceCode, title, teams, content, images,labelCode);
            String str = "";
            return write(200, "修改团队模板成功!", "result", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 删除团队所属的团队模板
     *
     * @param deleteAll    0否 1是
     * @param teamId
     * @param guidanceCode
     * @return
     */
    @RequestMapping(value = "/deleteTeamGuidance", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("删除团队所属的团队模板")
    
    public String deleteTeamGuidance(
            @ApiParam(value = "是否删除存在该模板的所有团队") @RequestParam int deleteAll,
            @ApiParam(value = "团队ID") @RequestParam(required = false) Integer teamId,
            @ApiParam(value = "团队模板编码") @RequestParam String guidanceCode
    ) {
        try {
            String doctor = getUID();
            doctorTeamGuidanceService.deleteTeamGuidance(doctor, deleteAll, teamId, guidanceCode);
            return write(200, "删除模板成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 发送团队模板给居民
     *
     * @param patient
     * @param content
     * @param guidanceCode
     * @param images
     * @return
     */
//    @RequestMapping(value = "/sendTeamGuidance", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("发送团队模板给居民")
//    public String sendTeamGuidance(
//            @ApiParam(value = "要发送的居民code") @RequestParam String patient,
//            @ApiParam(value = "团队模板内容") @RequestParam String content,
//            @ApiParam(value = "团队id") @RequestParam String teamId,
//            @ApiParam(value = "团队模板code") @RequestParam String guidanceCode,
//            @ApiParam(value = "团队模板图片") @RequestParam(required = false) String images,
//            @ApiParam(value = "异常指标数据的ids,多条用逗号分割") @RequestParam(required = false) String tzCode
//    ) {
//        try {
//            String accessToken = getAccessToken();
//            String doctor = getUID();
//            JSONArray teams = new JSONArray(teamId);
//            List<PatientHealthGuidance> list = new ArrayList<>();
//            for (Object team : teams) {
//                JSONObject teamJson = new JSONObject(team.toString());
//                int teamCode = teamJson.getInt("teamId");
//                list.add(doctorTeamGuidanceService.sendTeamGuidance(accessToken, doctor, patient, content, guidanceCode, images,teamCode,tzCode));
//            }
//            PatientHealthGuidance p = null;
//            for(PatientHealthGuidance one:list){
//                if(one!=null){
//                    p=one;
//                    break;
//                }
//            }
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("id",p.getId());
//            return write(200, "发送成功!","data",jsonObject);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, e.getMessage());
//        }
//    }
    /**
     * 根据医生所属的单个团队获取团队模板标签列表
     *
     * @param teamId
     * @return
     */
    @RequestMapping(value = "/getTeamGuidanceLabelList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("根据单个团队标签获取团队模板列表")
    public String getTeamGuidanceListByLabel(
            @RequestParam(required = true)
            @ApiParam(value = "团队ID") Integer teamId,
            @RequestParam(required = false)
            @ApiParam(value = "团队模板标签code") String labelCode,
            @RequestParam(value = "pageNo", required = true,defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", required = true,defaultValue = "10") int pageSize) {
        try {
            List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceService.getGuidanceByTeamIdAndLabelCode(teamId,labelCode, pageNo , pageSize);
            return write(200, "获取团队模板列表成功!", "data", list);
        } catch (Exception e) {
            return error(-1,"查询失败!");
        }
    }
    @RequestMapping(value = "/getTeamGuidanceListByLabelWithFilter", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("根据单个团队标签过滤条件获取团队模板列表")
    public String getTeamGuidanceListByLabelWithFilter(@RequestParam(value = "teamId",required = true)
                                                        @ApiParam(value = "团队ID") Integer teamId,
                                                       @RequestParam(value = "filter",required = true)
                                                       @ApiParam(value = "过滤条件") String filter){
        try{
            Map<String,List<DoctorTeamGuidanceTemplate>> map = doctorTeamGuidanceService.getTeamGuidanceListByLabelWithFilter(teamId ,filter);
            return write(200, "查询成功!","data",map);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败!");
        }
    }
}

+ 47 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorGuidanceTempDao.java

@ -0,0 +1,47 @@
package com.yihu.jw.hospital.module.template.dao;
import com.yihu.jw.entity.template.DoctorGuidanceTemp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr-pc on 2017/2/3.
 */
public interface DoctorGuidanceTempDao extends PagingAndSortingRepository<DoctorGuidanceTemp, Long> {
    DoctorGuidanceTemp findByCode(String code);
    int deleteByCode(String code);
    @Query("select t from DoctorGuidanceTemp t where t.owner = ?1 order by t.sendTimes desc ,t.createTime desc")
    Page<DoctorGuidanceTemp> findByOwner(String owner, Pageable pageRequest);
//    Page<List<DoctorGuidanceTemp>> findByOwner(String owner, Pageable pageRequest);
    @Query("select t from DoctorGuidanceTemp t where t.owner = ?1 or t.owner = 'system' order by t.sendTimes desc ,t.createTime desc")
    Page<DoctorGuidanceTemp> findByOwnerAndSystem(String owner, Pageable pageRequest);
    //    Page<List<DoctorGuidanceTemp>> findByOwnerAndSystem(String owner, Pageable pageRequest);
    //验证医生健康指导模板标题是否重复
    @Query("select t from DoctorGuidanceTemp t where t.owner = ?1 and t.modelName = ?2 ")
    List<DoctorGuidanceTemp> findByTitle(String owner, String title);
    //根据模板文章标题模糊搜索系统指导模板
    @Query(value = "select t from DoctorGuidanceTemp t where t.owner = 'system' and t.modelName like ?1 order by t.sendTimes desc ,t.createTime desc ")
    Page<DoctorGuidanceTemp> listByTileSystem(String filter, Pageable pageRequest);
    //根据模板文章标题模糊搜索个人指导模板
    @Query(value = "select t from DoctorGuidanceTemp t where t.owner != 'system' and t.modelName like ?1 order by t.sendTimes desc ,t.createTime desc ")
    Page<DoctorGuidanceTemp> listByTile(String filter, Pageable pageRequest);
    //根据模板文章标题模糊搜索个人指导模板
    @Query(value = "select t from DoctorGuidanceTemp t where t.owner = ?1 and t.modelName like ?2 order by t.sendTimes desc ,t.createTime desc ")
    Page<DoctorGuidanceTemp> listOwnerByTile(String owner, String filter, Pageable pageRequest);
    @Query("select t from DoctorGuidanceTemp t where (t.owner = 'system' or t.owner = ?1) and t.modelName like ?2 order by t.sendTimes desc ,t.createTime desc ")
    Page<DoctorGuidanceTemp> listByTileAll(String owner, String filter, Pageable pageRequest);
}

+ 38 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorGuidanceTempLabelDao.java

@ -0,0 +1,38 @@
package com.yihu.jw.hospital.module.template.dao;
import com.yihu.jw.entity.template.DoctorGuidanceTempLabel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by 刘文彬 on 2018/5/18.
 */
public interface DoctorGuidanceTempLabelDao extends PagingAndSortingRepository<DoctorGuidanceTempLabel, Long> {
    @Query("select t from DoctorGuidanceTempLabel t where t.teamId = ?1 and t.del=1")
    Page<DoctorGuidanceTempLabel> findByTeamId(Integer teamId, Pageable pageRequest);
    @Query("select t from DoctorGuidanceTempLabel t where t.teamId = ?1 and t.del=1 order by t.createTime desc ")
    List<DoctorGuidanceTempLabel> findByTeamId(Integer teamId);
    @Query("select t from DoctorGuidanceTempLabel t where t.teamId=?1 and  t.name = ?2 and t.del=1 ")
    DoctorGuidanceTempLabel findByNameWithDel(Integer teamId, String name);
    @Query("select t from DoctorGuidanceTempLabel t where t.code = ?1 ")
    DoctorGuidanceTempLabel findByCode(String code);
    @Modifying
    @Query(value = "update DoctorGuidanceTempLabel p set p.del=?1 where p.code=?2 ")
    int updateDel(int del, String code);
    @Modifying
    @Query(value = "update DoctorGuidanceTempLabel p set p.name=?1 where p.code=?2 ")
    int updateName(String name, String code);
}

+ 22 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorTeamGuidanceDetailDao.java

@ -0,0 +1,22 @@
package com.yihu.jw.hospital.module.template.dao;
import com.yihu.jw.entity.template.DoctorTeamGuidanceDetail;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/6/8.
 */
public interface DoctorTeamGuidanceDetailDao extends PagingAndSortingRepository<DoctorTeamGuidanceDetail, Long>, JpaSpecificationExecutor<DoctorTeamGuidanceDetail> {
    //根据模板编码获取有效的模板详情
    @Query("select distinct t from DoctorTeamGuidanceDetail t,DoctorTeamGuidanceTemplate a where t.code = a.teamTemplateCode and a.del = 1 and t.code = ?1 ")
    DoctorTeamGuidanceDetail findGuidanceDetail(String guidanceCode);
    //根据模板编码更改模板详情
    @Modifying
    @Query("update DoctorTeamGuidanceDetail t set t.title = ?1,t.content = ?2,t.imagesUrl = ?3 where t.code = ?4 ")
    int modifyTeamGuidanceDetail(String title, String content, String image, String guidance);
}

+ 83 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/dao/DoctorTeamGuidanceTemplateDao.java

@ -0,0 +1,83 @@
package com.yihu.jw.hospital.module.template.dao;
import com.yihu.jw.entity.template.DoctorTeamGuidanceTemplate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Reece on 2017/6/8.
 */
public interface DoctorTeamGuidanceTemplateDao extends PagingAndSortingRepository<DoctorTeamGuidanceTemplate, Long>, JpaSpecificationExecutor<DoctorTeamGuidanceTemplate> {
    //    新增团队模板时团队内标题排重
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.title = ?1 and t.teamId = ?2 ")
    List<DoctorTeamGuidanceTemplate> distinctByTeamTitle(String title, int teamId);
    //    根据团队ID获取团队内的模板列表(带分页和创建时间倒序)
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamId = ?1 ")
    List<DoctorTeamGuidanceTemplate> findGuidanceByTeamId(int teamId, Pageable request);
    //    根据团队ID获取团队内的模板列表(带分页和创建时间倒序)
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamId = ?1 ")
    List<DoctorTeamGuidanceTemplate> countGuidanceByTeamId(int teamId);
    //    由模板编码获取拥有该模板的团队信息
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamTemplateCode = ?1 ")
    List<DoctorTeamGuidanceTemplate> getTeamsByGuidance(String guidanceCode);
    //    根据团队ID及模板编码删除团队所属的团队模板
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.del = 0 where t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int deleteTeamGuidance(int teamId, String guidanceCode);
    //  根据模板编码更改团队模板对应表
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.title = ?3,t.labelCode=?4,t.labelName=?5 where t.del = 1 and t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int modifyTeamGuidance(int teamId, String guidanceCode, String title, String labelCode, String labelName);
    //  每给居民发送一次团队指导,使用数量加1
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.useTimes = t.useTimes+1 where t.del = 1 and t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int countSend(int teamId, String guidanceCode);
    //  批量删除(失效)该模板所在的所有团队关系
    @Modifying
    @Query("update DoctorTeamGuidanceTemplate t set t.useTimes =  0 ,t.del = 0 where t.teamId = ?1 and t.teamTemplateCode =?2 ")
    int deleteByTeam(int teamId, String guidanceCode);
    // 根据模板文章标题模糊搜索团队指导模板
    @Query("SELECT b FROM DoctorTeamGuidanceDetail a, DoctorTeamGuidanceTemplate b WHERE a.code = b.teamTemplateCode  " +
            " AND b.del = 1 AND b.title LIKE ?1 order by b.useTimes desc ,b.createTime desc ")
    Page<DoctorTeamGuidanceTemplate> listByTile(String title, Pageable pageRequest);
    // 根据模板文章标题模糊搜索团队指导模板
    @Query("SELECT b FROM DoctorTeamGuidanceDetail a, DoctorTeamGuidanceTemplate b WHERE a.code = b.teamTemplateCode  " +
            " AND b.del = 1 AND b.teamId = ?1 AND b.title LIKE ?2 order by b.useTimes desc ,b.createTime desc ")
    List<DoctorTeamGuidanceTemplate> countTeamListByTile(int teamId, String title);
    // 根据模板文章标题模糊搜索团队指导模板
    @Query("SELECT b FROM DoctorTeamGuidanceDetail a, DoctorTeamGuidanceTemplate b WHERE a.code = b.teamTemplateCode  " +
            " AND b.del = 1  AND b.creater = ?1  AND b.title LIKE ?2 GROUP BY b.teamId order by b.useTimes desc ,b.createTime desc ")
    List<DoctorTeamGuidanceTemplate> countTeamListByTile(String doctor, String title);
    // 根据模板文章标题模糊搜索团队指导模板
    @Query("SELECT b FROM DoctorTeamGuidanceTemplate b ,DoctorTeamGuidanceDetail a WHERE a.code = b.teamTemplateCode  " +
            " AND b.del = 1 AND b.teamId = ?1 AND b.title LIKE ?2 ")
    List<DoctorTeamGuidanceTemplate> getListByTile(int teamId, String title, Pageable pageRequest);
    // 根据模板文章标题模糊搜索团队指导模板(不分页)
    @Query("SELECT b FROM DoctorTeamGuidanceTemplate b WHERE   " +
            " b.del = 1 AND b.teamId = ?1 AND b.title LIKE ?2 ")
    List<DoctorTeamGuidanceTemplate> getListByTile(int teamId, String title);
    //    根据团队ID获取团队内的模板列表(带分页和创建时间倒序)
    @Query("select t from DoctorTeamGuidanceTemplate t where t.del = 1 and t.teamId = ?1 and t.labelCode= ?2")
    List<DoctorTeamGuidanceTemplate> findGuidanceByTeamIdAndLabelCode(int teamId, String labelCode, Pageable request);
}

+ 140 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorFeldsherTemplateService.java

@ -0,0 +1,140 @@
package com.yihu.jw.hospital.module.template.service;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 医生助手相关模板消息
 * <p>
 * Created by Reece on 2017/9/7/007.
 */
@Service
@Transactional
public class DoctorFeldsherTemplateService {
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    private static final Logger logger = LoggerFactory.getLogger(DoctorFeldsherTemplateService.class);
    /**
     * 医生为居民设置监测方案后实时为居民推送信息变更通知消息提醒
     *
     * @param patient 居民code
     * @param url     带参数的跳转URL
     * @throws Exception
     */
    public void sendChangeTemplate(String patient, String url) throws Exception {
        BasePatientDO people = patientDao.findById(patient).orElse(null);
        String openId = people.getOpenid();
        String name = people.getName();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonArray = null;
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change", "jcfa");
        String first = templateConfig.getFirst();
        first = first.replace("key1", (name == null ? "" : name));
        String remark = templateConfig.getRemark();
        String keyword3 = templateConfig.getKeyword3();
        JSONObject sendJson = new JSONObject();
        /*String first = name + "您好,您的家庭医生已为您设置了血糖(血压)监测方案,请按照方案及时测量及上传您的体征数据。";
        String remark = "您可使用详情查看方案内容";*/
        sendJson.put("keyword1", name);
        sendJson.put("keyword2", dateFormat.format(new Date()));
//        sendJson.put("keyword3", "血糖(血压)监测方案");
        sendJson.put("keyword3", keyword3);
        sendJson.put("first", first);
        sendJson.put("remark", remark);
        sendJson.put("url", url);//带参数的模板跳转链接
        pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 10, openId, name, sendJson);
        //发送代理人
        jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openId);
        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject j = jsonArray.getJSONObject(i);
                BasePatientDO member = (BasePatientDO) j.get("member");
                int start = url.indexOf("&toUser=");
                int end = url.indexOf("&", start + 1);
                String touser = url.substring(start, end);
                url = url.replace(touser, "&toUser=" + member.getId());
                //name患者姓名
                sendJson.put("first", weiXinOpenIdUtils.getTitleMes(people, (int) j.get("relation"), name) + first);
                sendJson.put("url", url);
                pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 10, member.getOpenid(), name, sendJson);
            }
        }
        logger.info("sendJson: " + sendJson);
    }
    /**
     * 拼装医生助手 医生类模板消息并发送
     *
     * @param doctorCode   医生code
     * @param sessionId    会话Id
     * @param sessionType  会话类型
     * @param businessType 消息类型
     * @param from         发送者
     * @param content      消息内容
     * @return
     */
    public Boolean sendDoctorTemplate(String doctorCode, String sessionId, String sessionType, String businessType, String from, String content) {
        try {
            String remark = "请进入手机APP查看,如尚未安装APP请点击详情下载安装";
            String url = "www.baidu.com";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            JSONObject sendJson = new JSONObject();
            BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
            String doctorName = doctor.getName();
            String doctorOpenId = doctor.getOpenid();
            String first = businessType;
            sendJson.put("keyword1", content);
            sendJson.put("keyword2", dateFormat.format(new Date()));
            sendJson.put("first", first);
            sendJson.put("remark", remark);
            sendJson.put("url", url);//带参数的模板跳转链接
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 11, doctorOpenId, doctorName, sendJson);
            logger.info("sendJson: " + sendJson);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

+ 87 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorGuidanceTempLableService.java

@ -0,0 +1,87 @@
package com.yihu.jw.hospital.module.template.service;
import com.yihu.jw.entity.template.DoctorGuidanceTempLabel;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempLabelDao;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by 刘文彬 on 2018/5/18.
 */
@Service
public class DoctorGuidanceTempLableService  {
    @Autowired
    private DoctorGuidanceTempLabelDao doctorGuidanceTempLableDao;
    /**
     * 保存
     * @param doctorCode
     * @param name
     */
    @Transactional
    public DoctorGuidanceTempLabel save(String doctorCode, String name, Integer teamId)throws Exception{
        DoctorGuidanceTempLabel one = new DoctorGuidanceTempLabel();
        one.setCode(getCode());
        one.setCreateTime(new Date());
        one.setDoctorCode(doctorCode);
        one.setName(name);
        one.setTeamId(teamId);
        one.setDel(1);
        return doctorGuidanceTempLableDao.save(one);
    }
    public List<DoctorGuidanceTempLabel> findByDoctorCode(Integer teamId, int pageSize, int pageNo) throws Exception{
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        pageNo=pageNo-1;
        PageRequest pageRequest =  PageRequest.of(pageNo, pageSize,sort);
        Page<DoctorGuidanceTempLabel> page =  doctorGuidanceTempLableDao.findByTeamId(teamId,pageRequest);
        List<DoctorGuidanceTempLabel> newList = new ArrayList<>();
        if(pageNo==0){
            newList.add(0,new DoctorGuidanceTempLabel("","未分组"));
        }
        newList.addAll(page.getContent());
        return newList;
    }
    public List<DoctorGuidanceTempLabel> findByDoctorCode(Integer teamId) throws Exception{
        List<DoctorGuidanceTempLabel> list =  doctorGuidanceTempLableDao.findByTeamId(teamId);
        List<DoctorGuidanceTempLabel> newList = new ArrayList<>();
        newList.add(0,new DoctorGuidanceTempLabel("","未分组"));
        newList.addAll(list);
        return newList;
    }
    @Transactional
    public boolean delete(String code) throws Exception{
        int temp = doctorGuidanceTempLableDao.updateDel(0,code);
        if(temp>0){
            return true;
        }
        return false;
    }
    @Transactional
    public boolean updateName(String code,String name) throws Exception{
        int temp = doctorGuidanceTempLableDao.updateName(name,code);
        if(temp>0){
            return true;
        }
        return false;
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

+ 304 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorGuidanceTempService.java

@ -0,0 +1,304 @@
package com.yihu.jw.hospital.module.template.service;
import com.yihu.jw.entity.template.DoctorGuidanceTemp;
import com.yihu.jw.entity.template.DoctorTeamGuidanceTemplate;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempDao;
import com.yihu.jw.hospital.module.template.dao.DoctorTeamGuidanceTemplateDao;
import com.yihu.jw.util.common.CommonUtil;
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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生健康指导模板
 * <p>
 * Created by lyr-pc on 2017/2/3.
 */
@Service
@Transactional
public class DoctorGuidanceTempService  {
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorTeamGuidanceTemplateDao doctorTeamGuidanceTemplateDao;
    @Autowired
    private CommonUtil CommonUtil;
    /**
     * 记录医生健康指导模板使用次数
     *
     * @param modelCode 健康指导模板编码
     */
    public void countSend(String modelCode) {
        synchronized (this) {
            String sql = "UPDATE wlyy_doctor_guidance_temp  " +
                    "SET send_times=send_times+1 " +
                    "WHERE CODE=?";
            jdbcTemplate.update(sql, modelCode);
        }
    }
    /**
     * 查询单个指导模板详情
     *
     * @param modelCode
     * @return
     * @throws Exception
     */
    public JSONObject listDetail(String modelCode) throws Exception {
        String sql = "SELECT wdgt.`model_name`,wdgt.`content`,wdgt.`images_url`,wdgt.`create_time`,wdgt.`send_times` " +
                "FROM wlyy_doctor_guidance_temp wdgt " +
                "WHERE wdgt.`code`=?";
        Map temp = (Map) jdbcTemplate.queryForMap(sql, modelCode);
        String modelName = (String) temp.get("model_name");
        String content = (String) temp.get("content");
        String imagesUrl = (String) temp.get("images_url");
//        多图按逗号分割保存成数组
        String[] imagesArray = null;
        if (imagesUrl != null) {
            imagesArray = imagesUrl.split(",");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = (Date) temp.get("create_time");
        String dateTime = sdf.format(createTime);
        String sendTimes = (String) temp.get("send_times").toString();
        JSONObject json = new JSONObject();
        json.put("modelName", modelName);
        json.put("content", content);
        json.put("imagesUrls", imagesArray);
        json.put("createTime", dateTime);
        json.put("sendTimes", sendTimes);
        return json;
    }
    /**
     * 添加指导模板
     *
     * @param doctor  医生
     * @param content 指导内容
     * @return
     */
    public DoctorGuidanceTemp add(String doctor, String content, String modelName, String imagesUrl) throws Exception{
        DoctorGuidanceTemp guidanceTemp = new DoctorGuidanceTemp();
        String imageUrls = "";
        String imageRow = "";
        guidanceTemp.setCode(getCode());
        guidanceTemp.setOwner(doctor);
        guidanceTemp.setContent(content);
        guidanceTemp.setSendTimes(0);
        guidanceTemp.setCreateTime(new Date());
        guidanceTemp.setModelName(modelName);
        if (StringUtils.isNotEmpty(imagesUrl)) {
            imagesUrl = CommonUtil.validateImages(imagesUrl);
        }
        guidanceTemp.setImagesUrl(imagesUrl);
        return guidanceTempDao.save(guidanceTemp);
    }
    /**
     * 修改指导模板
     *
     * @param code    模板编码
     * @param content 指导内容
     * @return
     */
    public DoctorGuidanceTemp modify(String code, String modelName, String content, String imagesUrl) throws Exception {
        DoctorGuidanceTemp guidanceTemp = guidanceTempDao.findByCode(code);
        String imageUrls = "";
        String imageRow = "";
        if (guidanceTemp == null) {
            throw new RuntimeException("模板不存在");
        }
        guidanceTemp.setModelName(modelName);
        guidanceTemp.setContent(content);
        if (imagesUrl == null || "".equals(imagesUrl)) {
            imagesUrl = null;
        } else {
            String[] images = imagesUrl.split(",");
            for (String image : images) {
                if (image.contains("group1")) {
                    imageUrls += image + ",";
                } else {
                    try {
                        imageRow += CommonUtil.copyTempImage(image) + ",";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            imagesUrl = imageUrls + imageRow;
            imagesUrl = imagesUrl.substring(0, imagesUrl.length() - 1);
        }
        guidanceTemp.setImagesUrl(imagesUrl);
        return guidanceTempDao.save(guidanceTemp);
    }
    /**
     * 删除指导模板
     *
     * @param code 模板编码
     * @return
     */
    public int delete(String code) throws Exception {
        String[] codes = code.split(",");
        if (codes != null && codes.length > 0) {
            for (String temp : codes) {
                String sql = "SELECT t.owner FROM wlyy_doctor_guidance_temp t WHERE t.code=?";
                String owner = jdbcTemplate.queryForObject(sql, String.class, temp);
                if (!"system".equals(owner)) {
                    guidanceTempDao.deleteByCode(temp);
                }
            }
        }
        return 1;
    }
    /**
     * 查询指导模板
     *
     * @param doctor 医生
     * @param type   模板类型
     * @return
     */
    public List<Map<String, Object>> list(String doctor,String filter, String type, int pageSize, int pageNo) throws Exception {
        Page<DoctorGuidanceTemp> temps = null;
        PageRequest pageRequest =  PageRequest.of(pageNo, pageSize);
        List<Map<String, Object>> listMap = new ArrayList<>();
        if (StringUtils.isEmpty(filter)){
            if (type.equals("1")) {
                temps = guidanceTempDao.findByOwner("system", pageRequest);
            } else if (type.equals("2")) {
                temps = guidanceTempDao.findByOwner(doctor, pageRequest);
            } else {
                temps = guidanceTempDao.findByOwnerAndSystem(doctor, pageRequest);
            }
        }else {
            if (type.equals("1")) {
                temps = guidanceTempDao.listByTileSystem("%"+filter+"%", pageRequest);
            } else if (type.equals("2")) {
                temps = guidanceTempDao.listOwnerByTile(doctor,"%"+filter+"%", pageRequest);
            } else {
                temps = guidanceTempDao.listByTileAll(doctor,"%"+filter+"%", pageRequest);
            }
        }
        List<DoctorGuidanceTemp> list = temps.getContent();
        for (int i = 0; i < list.size(); i++) {
            DoctorGuidanceTemp dgt = list.get(i);
            Map<String, Object> tem = new HashMap<>();
            tem.put("code", dgt.getCode());
            tem.put("owner", dgt.getOwner());
            tem.put("sendTimes", dgt.getSendTimes());
            tem.put("lastTime", dgt.getLastTime());
            tem.put("modelName", dgt.getModelName());
            if(i == 0) {
                tem.put("total", temps.getTotalElements());
                tem.put("pages", temps.getTotalPages());
            }
            listMap.add(tem);
        }
        return listMap;
    }
    /**
     * 根据模板类型、文章标题模糊搜索指导模板
     *
     * @param filter 搜索关键字
     * @param type 1:系统 2:个人 3:团队摸版
     * @param pageSize
     * @param pageNo
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> listByTitle(String filter,String type, int pageSize, int pageNo) throws Exception {
        PageRequest pageRequest = PageRequest.of(pageNo, pageSize);
        List<Map<String, Object>> listMap = new ArrayList<>();
        if ("1".equals(type)) {
            Page<DoctorGuidanceTemp> temps = guidanceTempDao.listByTileSystem("%"+filter+"%", pageRequest);
            List<DoctorGuidanceTemp> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorGuidanceTemp dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("code", dgt.getCode());
                tem.put("owner", dgt.getOwner());
                tem.put("sendTimes", dgt.getSendTimes());
                tem.put("lastTime", dgt.getLastTime());
                tem.put("modelName", dgt.getModelName());
                listMap.add(tem);
            }
        } else if ("2".equals(type)) {
            Page<DoctorGuidanceTemp> temps = guidanceTempDao.listByTile("%"+filter+"%", pageRequest);
            List<DoctorGuidanceTemp> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorGuidanceTemp dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("code", dgt.getCode());
                tem.put("owner", dgt.getOwner());
                tem.put("sendTimes", dgt.getSendTimes());
                tem.put("lastTime", dgt.getLastTime());
                tem.put("modelName", dgt.getModelName());
                listMap.add(tem);
            }
        } else if("3".equals(type)){
            Page<DoctorTeamGuidanceTemplate> temps = doctorTeamGuidanceTemplateDao.listByTile("%"+filter+"%", pageRequest);
            List<DoctorTeamGuidanceTemplate> list = temps.getContent();
            for (int i = 0; i < list.size(); i++) {
                DoctorTeamGuidanceTemplate dgt = list.get(i);
                Map<String, Object> tem = new HashMap<>();
                tem.put("teamId", dgt.getTeamId());
                tem.put("teamName", dgt.getTeamName());
                tem.put("code", dgt.getTeamTemplateCode());
                tem.put("owner", dgt.getCreater());
                tem.put("sendTimes", dgt.getUseTimes());
                tem.put("lastTime", dgt.getCzrq());
                tem.put("modelName", dgt.getTitle());
                listMap.add(tem);
            }
        }
        return listMap;
    }
    /**
     * 根据code获取详情
     * @param code
     * @return
     */
    public DoctorGuidanceTemp findByCode(String code) {
        return guidanceTempDao.findByCode(code);
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

+ 560 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/template/service/DoctorTeamGuidanceService.java

@ -0,0 +1,560 @@
package com.yihu.jw.hospital.module.template.service;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.patient.PatientHealthGuidance;
import com.yihu.jw.entity.template.DoctorGuidanceTemp;
import com.yihu.jw.entity.template.DoctorGuidanceTempLabel;
import com.yihu.jw.entity.template.DoctorTeamGuidanceDetail;
import com.yihu.jw.entity.template.DoctorTeamGuidanceTemplate;
import com.yihu.jw.hospital.module.consult.service.ConsultService;
import com.yihu.jw.hospital.module.health.service.PatientHealthGuidanceService;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempDao;
import com.yihu.jw.hospital.module.template.dao.DoctorGuidanceTempLabelDao;
import com.yihu.jw.hospital.module.template.dao.DoctorTeamGuidanceDetailDao;
import com.yihu.jw.hospital.module.template.dao.DoctorTeamGuidanceTemplateDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.CommonUtil;
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.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Reece on 2017/6/8.
 */
@Service
@Transactional
public class DoctorTeamGuidanceService  {
    @Autowired
    private DoctorTeamGuidanceTemplateDao doctorTeamGuidanceTemplateDao;
    @Autowired
    private DoctorTeamGuidanceDetailDao doctorTeamGuidanceDetailDao;
    @Autowired
    private DoctorGuidanceTempDao doctorGuidanceTempDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    
    @Autowired
    private ConsultService consultService;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private DoctorGuidanceTempLabelDao doctorGuidanceTempLableDao;
    
    @Autowired
    private PatientHealthGuidanceService patientHealthGuidanceService;
    /**
     * 新增团队指导模板
     *
     * @param title
     * @param teams
     * @param content
     * @param images
     */
    public String saveTeamGuidance(String doctor, String title, JSONArray teams, String content, String images, String labelCode) throws Exception {
        String templateCode = getCode();
        Date nowDate = new Date();
        //指导标签
        DoctorGuidanceTempLabel doctorGuidanceTempLable =  doctorGuidanceTempLableDao.findByCode(labelCode);
        String labelName = "未分组";
        if(doctorGuidanceTempLable!=null){
            labelName = doctorGuidanceTempLable.getName();
        }
        for (Object team : teams) {
            JSONObject teamJson = new JSONObject(team.toString());
            int teamId = teamJson.getInt("teamId");
            String teamName = teamJson.getString("teamName");
            //             团队内标题排重
            List<DoctorTeamGuidanceTemplate> teamGuidanceTemplates = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
            if (teamGuidanceTemplates.size() == 0) {
                DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                doctorTeamGuidanceTemplate.setCreater(doctor);
                doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                doctorTeamGuidanceTemplate.setCzrq(nowDate);
                doctorTeamGuidanceTemplate.setDel(1);
                doctorTeamGuidanceTemplate.setTeamId(teamId);
                doctorTeamGuidanceTemplate.setTeamName(teamName);
                doctorTeamGuidanceTemplate.setTitle(title);
                doctorTeamGuidanceTemplate.setTeamTemplateCode(templateCode);
                doctorTeamGuidanceTemplate.setUseTimes(0);
                doctorTeamGuidanceTemplate.setLabelCode(labelCode);
                doctorTeamGuidanceTemplate.setLabelName(labelName);
                doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
            } else {
                throw new RuntimeException(teamName + ":团队标题重复!");
            }
        }
//            团队内标题不重复保存到团队模板详情表团队模板表
        DoctorTeamGuidanceDetail doctorTeamGuidanceDetail = new DoctorTeamGuidanceDetail();
        doctorTeamGuidanceDetail.setCode(templateCode);
        doctorTeamGuidanceDetail.setTitle(title);
        doctorTeamGuidanceDetail.setCreater(doctor);
        doctorTeamGuidanceDetail.setContent(content);
        doctorTeamGuidanceDetail.setCreateTime(nowDate);
        doctorTeamGuidanceDetail.setCzrq(nowDate);
        doctorTeamGuidanceDetail.setImagesUrl(images);
        doctorTeamGuidanceDetailDao.save(doctorTeamGuidanceDetail);
        return templateCode;
    }
    /**
     * 修改团队模板
     *
     * @param guidanceCode
     * @param title
     * @param teams
     * @param content
     * @param images
     * @throws Exception
     */
    public void modifyTeamGuidance(String doctor, String isLeader, int saveAsGuidance, Boolean isRepeat , String guidanceCode, String title,
                                   JSONArray teams, String content, String images, String labelCode) throws Exception {
//        首先身份验证
        DoctorTeamGuidanceDetail guidanceDetail = doctorTeamGuidanceDetailDao.findGuidanceDetail(guidanceCode);
        String creater = guidanceDetail.getCreater();
        Date nowDate = new Date();
        DoctorGuidanceTempLabel doctorGuidanceTempLable =  doctorGuidanceTempLableDao.findByCode(labelCode);
        String labelName = "未分组";
        if(doctorGuidanceTempLable!=null){
            labelName = doctorGuidanceTempLable.getName();
        }
//        图片地址需要处理
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
            image = validateImages(images);
        }
        if (saveAsGuidance == 1) {
            //      保存为个人模板 去除个人模板标题重复 个人模板重复和修改是分开的互不影响
            //        验证模板名称唯一性
            List<DoctorGuidanceTemp> templates = guidanceTempDao.findByTitle(doctor, title);
            DoctorGuidanceTemp doctorGuidanceTemp = new DoctorGuidanceTemp();
            if (!isRepeat) {
                doctorGuidanceTemp.setCode(getCode());
                doctorGuidanceTemp.setImagesUrl(image);
                doctorGuidanceTemp.setCreateTime(nowDate);
                doctorGuidanceTemp.setContent(content);
                doctorGuidanceTemp.setModelName(title);
                doctorGuidanceTemp.setOwner(doctor);
                doctorGuidanceTemp.setLastTime(nowDate);
                doctorGuidanceTemp.setSendTimes(1);
                doctorGuidanceTempDao.save(doctorGuidanceTemp);
            }
            if ((!doctor.equals(creater)) && (!"1".equals(isLeader))) {
                throw new RuntimeException("没有修改权限");
            }
            //                        数据库中拥有该模板的所有团队
            List<DoctorTeamGuidanceTemplate> teamIds = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
            List teamList = new ArrayList();
            List tempTeams = new ArrayList();
            for (DoctorTeamGuidanceTemplate team : teamIds) {
                teamList.add(team.getTeamId());
            }
            for (Object team : teams) {
                JSONObject teamJson = new JSONObject(team.toString());
                int teamId = teamJson.getInt("teamId");
                tempTeams.add(teamId);
                String teamName = teamJson.getString("teamName");
//                    团队内模板标题要去重复(去掉自身)
                List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
                if (list.size() <= 1) {
//                        直接失效原有团队模板对应关系  在重新新增以前没有的团队关系 发送次数要归0
                    if (teamList.contains(teamId)) {
//                            数据库有
                        doctorTeamGuidanceTemplateDao.modifyTeamGuidance(teamId, guidanceCode, title,labelCode,labelName);
                    } else if (!teamList.contains(teamId)) {
                        //                        现在有,而数据库没有 要新增
                        DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                        doctorTeamGuidanceTemplate.setCreater(doctor);
                        doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                        doctorTeamGuidanceTemplate.setCzrq(nowDate);
                        doctorTeamGuidanceTemplate.setDel(1);
                        doctorTeamGuidanceTemplate.setTeamId(teamId);
                        doctorTeamGuidanceTemplate.setTeamName(teamName);
                        doctorTeamGuidanceTemplate.setTitle(title);
                        doctorTeamGuidanceTemplate.setTeamTemplateCode(guidanceCode);
                        doctorTeamGuidanceTemplate.setUseTimes(0);
                        doctorTeamGuidanceTemplate.setLabelCode(labelCode);
                        doctorTeamGuidanceTemplate.setLabelName(labelName);
                        doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
                    }
                } else {
                    
                    throw new RuntimeException(teamName + ":团队标题重复!");
                }
                //                直接修改团队模板后修改模板团队对应表
                doctorTeamGuidanceDetailDao.modifyTeamGuidanceDetail(title, content, image, guidanceCode);
            }
//                            数据库有,而现在没有
            teamList.removeAll(tempTeams);
            for (Object team : teamList) {
                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(Integer.parseInt(team.toString()), guidanceCode);
            }
        } else if (saveAsGuidance == 0) {
            if ((!doctor.equals(creater)) && (!"1".equals(isLeader))) {
                throw new RuntimeException("没有修改权限");
            }
            //                        数据库中拥有该模板的所有团队
            List<DoctorTeamGuidanceTemplate> teamIds = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
            List teamList = new ArrayList();
            List tempTeams = new ArrayList();
            for (DoctorTeamGuidanceTemplate team : teamIds) {
                teamList.add(team.getTeamId());
            }
            for (Object team : teams) {
                JSONObject teamJson = new JSONObject(team.toString());
                int teamId = teamJson.getInt("teamId");
                tempTeams.add(teamId);
                String teamName = teamJson.getString("teamName");
//                    团队内模板标题要去重复(去掉自身)
                List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.distinctByTeamTitle(title, teamId);
                if (list.size() <= 1) {
//                        直接失效原有团队模板对应关系  在重新新增以前没有的团队关系 发送次数要归0
                    if (teamList.contains(teamId)) {
//                            数据库有
                        doctorTeamGuidanceTemplateDao.modifyTeamGuidance(teamId, guidanceCode, title,labelCode,labelName);
                    } else if (!teamList.contains(teamId)) {
                        //                        现在有,而数据库没有 要新增
                        DoctorTeamGuidanceTemplate doctorTeamGuidanceTemplate = new DoctorTeamGuidanceTemplate();
                        doctorTeamGuidanceTemplate.setCreater(doctor);
                        doctorTeamGuidanceTemplate.setCreateTime(nowDate);
                        doctorTeamGuidanceTemplate.setCzrq(nowDate);
                        doctorTeamGuidanceTemplate.setDel(1);
                        doctorTeamGuidanceTemplate.setTeamId(teamId);
                        doctorTeamGuidanceTemplate.setTeamName(teamName);
                        doctorTeamGuidanceTemplate.setTitle(title);
                        doctorTeamGuidanceTemplate.setTeamTemplateCode(guidanceCode);
                        doctorTeamGuidanceTemplate.setUseTimes(0);
                        doctorTeamGuidanceTemplate.setLabelCode(labelCode);
                        doctorTeamGuidanceTemplate.setLabelName(labelName);
                        doctorTeamGuidanceTemplateDao.save(doctorTeamGuidanceTemplate);
                    }
                } else {
                    throw new RuntimeException(teamName + ":团队标题重复!");
                }
                //                直接修改团队模板后修改模板团队对应表
                doctorTeamGuidanceDetailDao.modifyTeamGuidanceDetail(title, content, image, guidanceCode);
            }
//                            数据库有,而现在没有
            teamList.removeAll(tempTeams);
            for (Object team : teamList) {
                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(Integer.parseInt(team.toString()), guidanceCode);
            }
        }
    }
    /**
     * 根据医生所属的单个团队获取团队模板列表
     *
     * @param doctor
     * @param filter
     * @param teamId
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public List getTeamGuidanceList(String doctor, String filter, Integer teamId, int pageNo, int pageSize) throws Exception {
        Sort sort =  Sort.by(Sort.Direction.DESC, "useTimes","createTime");
        PageRequest request =  PageRequest.of(pageNo, pageSize, sort);
        List list = new ArrayList();
        List<DoctorTeamGuidanceTemplate> listGuidances = null;
        if (StringUtils.isEmpty(filter)){
            listGuidances = doctorTeamGuidanceTemplateDao.findGuidanceByTeamId(teamId, request);
        }else {
            listGuidances = doctorTeamGuidanceTemplateDao.getListByTile(teamId,"%"+filter+"%", request);
        }
        for (DoctorTeamGuidanceTemplate guidance : listGuidances) {
            Map map = new HashMap();
            String title = guidance.getTitle();
            int useTimes = guidance.getUseTimes();
            String teamTemplateCode = guidance.getTeamTemplateCode();
            map.put("teamTemplateCode", teamTemplateCode);
            map.put("title", title);
            map.put("useTimes", useTimes);
            map.put("createTime", guidance.getCreateTime());
            list.add(map);
        }
        return list;
    }
//    /**
//     * 获取此医生所在的团队列表。
//     *
//     * @param doctorCode
//     * @param filter 搜索关键字
//     * @return
//     */
//    public List getDoctorTeams(String doctorCode,String filter) throws Exception{
//        List teamList = null;
//        try {
//            List<AdminTeam> doctorTeams = memberDao.findDoctorTeams(doctorCode);
//            teamList = new ArrayList();
//
//            for (AdminTeam AdminTeam : doctorTeams){
//                Map map = new HashMap();
//                String teamName = AdminTeam.getName();
//                Long teamId = AdminTeam.getId();
//                map.put("teamName", teamName);
//                map.put("teamId", teamId);
//
//                if (StringUtils.isNotEmpty(filter)){
//                    List<DoctorTeamGuidanceTemplate> guidances = doctorTeamGuidanceTemplateDao.countTeamListByTile(Integer.valueOf(teamId.toString()),"%"+filter+"%");
//                    map.put("amount", guidances.size());
//                }else {
//                    List<DoctorTeamGuidanceTemplate> listGuidances = doctorTeamGuidanceTemplateDao.countGuidanceByTeamId(Integer.valueOf(teamId.toString()));
//                    map.put("amount", listGuidances.size());
//                }
//                teamList.add(map);
//            }
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
//
//        return teamList;
//    }
//    /**
//     * 获取此医生所在的团队列表。
//     *
//     * @param doctorCode
//     * @param filter 搜索关键字
//     * @return
//     */
//    public List findDoctorLeaderTeam(String doctorCode,String filter) throws Exception{
//        List teamList = null;
//        try {
//            List<AdminTeam> doctorTeams = memberDao.findDoctorLeaderTeam(doctorCode);
//            teamList = new ArrayList();
//
//            for (AdminTeam AdminTeam : doctorTeams){
//                Map map = new HashMap();
//                String teamName = AdminTeam.getName();
//                Long teamId = AdminTeam.getId();
//                map.put("teamName", teamName);
//                map.put("teamId", teamId);
//
//                if (StringUtils.isNotEmpty(filter)){
//                    List<DoctorTeamGuidanceTemplate> guidances = doctorTeamGuidanceTemplateDao.countTeamListByTile(Integer.valueOf(teamId.toString()),"%"+filter+"%");
//                    map.put("amount", guidances.size());
//                }else {
//                    List<DoctorTeamGuidanceTemplate> listGuidances = doctorTeamGuidanceTemplateDao.countGuidanceByTeamId(Integer.valueOf(teamId.toString()));
//                    map.put("amount", listGuidances.size());
//                }
//                teamList.add(map);
//            }
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
//
//        return teamList;
//    }
    /**
     * 根据团队模板编码获取单个 有效的 模板详情
     *
     * @param guidanceCode
     * @return
     * @throws Exception
     */
    public JSONObject getTeamGuidanceDetail(int teamId, String guidanceCode) throws Exception {
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = "";
        String czrq = "";
        DoctorTeamGuidanceDetail guidanceDetail = doctorTeamGuidanceDetailDao.findGuidanceDetail(guidanceCode);
        List<DoctorTeamGuidanceTemplate> doctorTeamGuidanceTemplate = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
        List teamList = new ArrayList();
        for (DoctorTeamGuidanceTemplate teamGuidanceTemplate : doctorTeamGuidanceTemplate) {
            Map map = new HashMap();
            map.put("teamId", teamGuidanceTemplate.getTeamId());
            map.put("teamName", teamGuidanceTemplate.getTeamName());
            if (teamGuidanceTemplate.getTeamId() == teamId) {
                jsonObject.put("useTimes", teamGuidanceTemplate.getUseTimes());
            }
            teamList.add(map);
        }
        Date create = guidanceDetail.getCreateTime();
        Date cztime = guidanceDetail.getCzrq();
        if (create != null) {
            createTime = sdf.format(create);
        }
        if (cztime != null) {
            czrq = sdf.format(cztime);
        }
        jsonObject.put("id", guidanceDetail.getId() != null ? guidanceDetail.getId() : "");
        jsonObject.put("code", guidanceDetail.getCode() != null ? guidanceDetail.getCode() : "");
        jsonObject.put("creater", guidanceDetail.getCreater() != null ? guidanceDetail.getCreater() : "");
        jsonObject.put("title", guidanceDetail.getTitle() != null ? guidanceDetail.getTitle() : "");
        jsonObject.put("content", guidanceDetail.getContent() != null ? guidanceDetail.getContent() : "");
        jsonObject.put("imagesUrl", guidanceDetail.getImagesUrl() != null ? guidanceDetail.getImagesUrl() : "");
        jsonObject.put("createTime", createTime);
        jsonObject.put("czrq", czrq);
        jsonObject.put("teamList", teamList);
        String labelCode = doctorTeamGuidanceTemplate.get(0).getLabelCode();
        String labelName = doctorTeamGuidanceTemplate.get(0).getLabelName();
        jsonObject.put("labelCode", labelCode);
        jsonObject.put("labelName", labelName);
        return jsonObject;
    }
    /**
     * 删除团队所属的团队模板
     *
     * @param teamId
     * @param guidanceCode
     * @throws Exception
     */
    public void deleteTeamGuidance(String doctor, int deteleAll, Integer teamId, String guidanceCode) throws Exception {
        String str = "";
        if (deteleAll == 0) {
            doctorTeamGuidanceTemplateDao.deleteTeamGuidance(teamId, guidanceCode);
        } else {
//            删除该医生所有团队内该模板
//            List<AdminTeam> teams = memberDao.findDoctorTeams(doctor);
//            for (AdminTeam team : teams) {
//                int teamCode = team.getId().intValue();
//                doctorTeamGuidanceTemplateDao.deleteTeamGuidance(teamCode, guidanceCode);
//            }
            doctorTeamGuidanceTemplateDao.deleteTeamGuidance(123, guidanceCode);
        }
    }
    /**
     * 给居民发送团队模板
     *
     * @param accessToken
     * @param patient
     * @param content
     * @param guidanceCode
     * @param images
     * @throws Exception
     */
    public PatientHealthGuidance sendTeamGuidance(String accessToken, String dc, String patient, String content, String guidanceCode, String images, int teamId, String tzCode) throws Exception {
        String image = "";
        if (StringUtils.isNotEmpty(images)) {
            image = validateImages(images);
        }
        List<DoctorTeamGuidanceTemplate> guidanceTemplate = doctorTeamGuidanceTemplateDao.getTeamsByGuidance(guidanceCode);
        PatientHealthGuidance guidance = new PatientHealthGuidance();
        guidance.setContent(content);
        guidance.setDoctor(dc);
        guidance.setPatient(patient);
        BaseDoctorDO doctor = doctorDao.findById(dc).orElse(null);
        guidance.setImages(image);
        // 保存
        PatientHealthGuidance guidance1 = patientHealthGuidanceService.add(guidance, accessToken, tzCode, guidanceTemplate.get(0).getTitle());
        if (guidance1 != null) {
            String sendImgs = "";
            if (StringUtils.isNotBlank(image)) {
                sendImgs = image;
            }
            BasePatientDO p = patientDao.findById(patient).orElse(null);
            String imcotent = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" +
                    guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\"" +
                    CommonUtil.getSubString(guidance.getContent(), 0, 30) + "\"}";
            // todo 这个选注释掉了 -- 还没改完 20240306
//            consultService.sendMucMessageBySingnType(dc, doctor.getName(), patient, imcotent, "4", p.getName());
//            BusinessLogs.info(BusinessLogs.BusinessType.guidance, dc, patient, new JSONObject(guidance));
            //发送成功记录模板发送次数
            doctorTeamGuidanceTemplateDao.countSend(teamId, guidanceCode);
            return guidance1;
        }
        return null;
    }
    /**
     * 校验图片本地路径掺杂网络路径,统一返回网路路径
     *
     * @param images
     * @throws Exception
     */
    public  String validateImages(String images) throws Exception {
        String imagePath = "";
        String imageUrls = "";
        String imageRow = "";
        String[] imgs = images.split(",");
        for (String image : imgs) {
            if (image.contains("group1")) {
                imageUrls += image + ",";
            } else {
                try {
                    imageRow += CommonUtil.copyTempImage(image) + ",";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        imagePath += imageUrls + imageRow;
        imagePath = imagePath.substring(0, imagePath.length() - 1);
        return imagePath;
    }
    public List<DoctorTeamGuidanceTemplate> getGuidanceByTeamIdAndLabelCode( Integer teamId,String labelCode, int pageNo, int pageSize) throws Exception {
        Sort sort = Sort.by(Sort.Direction.DESC, "useTimes","createTime");
        pageNo = pageNo -1;
        PageRequest request =  PageRequest.of(pageNo, pageSize, sort);
        List<DoctorTeamGuidanceTemplate> list = doctorTeamGuidanceTemplateDao.findGuidanceByTeamIdAndLabelCode(teamId,labelCode,request);
        return list;
    }
    public Map<String,List<DoctorTeamGuidanceTemplate>> getTeamGuidanceListByLabelWithFilter(Integer teamId , String filter) throws Exception {
        List<DoctorTeamGuidanceTemplate>  listGuidances = doctorTeamGuidanceTemplateDao.getListByTile(teamId,"%"+filter+"%");
        Map<String,List<DoctorTeamGuidanceTemplate>> map= new HashMap<>();
        for(DoctorTeamGuidanceTemplate one:listGuidances){
            if(map.containsKey(one.getLabelName()!=null?one.getLabelName():"未分组")){
                List<DoctorTeamGuidanceTemplate> temp = map.get(one.getLabelName()!=null?one.getLabelName():"未分组");
                temp.add(one);
            }else{
                map.put(one.getLabelName()!=null?one.getLabelName():"未分组",new ArrayList<>(Arrays.asList(one)));
            }
        }
        return map;
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}