Browse Source

健康记录查询接口

YE-YI 8 năm trước cách đây
mục cha
commit
66297dd98e
86 tập tin đã thay đổi với 5859 bổ sung1131 xóa
  1. 0 1
      .gitignore
  2. 6 6
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java
  3. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/MessageDao.java
  4. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java
  5. 178 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/AgentAppointmentFilter.java
  6. 129 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AgentAppointmentJob.java
  7. 26 4
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentDayAllQuotaJob.java
  8. 0 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/cache/CacheCleanJob.java
  9. 322 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientReservation.java
  10. 8 0
      patient-co-wlyy/pom.xml
  11. 24 0
      patient-co-wlyy/readme.MD
  12. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/Consult.java
  13. 21 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/ConsultTeam.java
  14. 77 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/Evaluate.java
  15. 57 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/EvaluateLabel.java
  16. 226 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/device/PatientBloodSugger.java
  17. 248 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/device/PatientHealthTime.java
  18. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/doctor/profile/Doctor.java
  19. 31 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticlePatient.java
  20. 144 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/feedback/Appeal.java
  21. 149 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/feedback/Feedback.java
  22. 11 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/followup/Followup.java
  23. 2 2
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/message/Message.java
  24. 36 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/message/SMS.java
  25. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/PatientHealthGuidance.java
  26. 479 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/SignFamilyRenew.java
  27. 8 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java
  28. 37 34
      patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java
  29. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/interceptors/DoctorInterceptor.java
  30. 12 11
      patient-co-wlyy/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java
  31. 4 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/job/SignEndJob.java
  32. 107 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/job/consult/EvaluateScoreJob.java
  33. 4 4
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultDao.java
  34. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamDoctorDao.java
  35. 36 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/EvaluateDao.java
  36. 28 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/EvaluateLabelDao.java
  37. 14 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/deviece/PatientBloodSuggerDao.java
  38. 15 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/deviece/PatientHealthTimeDao.java
  39. 12 6
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticlePatientDao.java
  40. 11 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/feedback/AppealDao.java
  41. 11 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/feedback/FeedbackDao.java
  42. 33 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyRenewDao.java
  43. 2 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  44. 5 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultService.java
  45. 17 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java
  46. 54 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/EvaluateLabelService.java
  47. 130 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/EvaluateService.java
  48. 489 386
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java
  49. 54 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/feedback/AppealService.java
  50. 53 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/feedback/FeedbackService.java
  51. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/followup/FollowUpService.java
  52. 8 4
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleDoctorService.java
  53. 88 3
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticlePatientService.java
  54. 23 9
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleService.java
  55. 5 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java
  56. 101 14
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  57. 99 8
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  58. 299 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java
  59. 17 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsAllService.java
  60. 43 2
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/SMSService.java
  61. 72 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java
  62. 15 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/task/PushMsgTask.java
  63. 78 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ClazzReflect.java
  64. 23 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ImUtill.java
  65. 26 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java
  66. 1 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java
  67. 82 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorEvaluateController.java
  68. 92 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/feedback/DoctorFeedbackController.java
  69. 5 3
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java
  70. 76 30
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java
  71. 165 14
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/sign/DoctorSignController.java
  72. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java
  73. 84 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/EvaluateController.java
  74. 154 107
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java
  75. 2 2
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/family/FamilyMemberController.java
  76. 158 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/feedback/PatientFeedbackController.java
  77. 165 145
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/HealthEduArticleController.java
  78. 453 250
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java
  79. 48 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/sign/FamilyContractController.java
  80. 1 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/sign/PatientSignController.java
  81. 60 41
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java
  82. 33 33
      patient-co-wlyy/src/main/resources/application.properties
  83. 2 2
      patient-co-wlyy/src/main/resources/config/fdfs_client.conf
  84. 4 2
      patient-co-wlyy/src/main/resources/system.properties
  85. 5 5
      patient-co-wlyy/src/main/resources/weixin_menu.txt
  86. 11 0
      readme.MD

+ 0 - 1
.gitignore

@ -12,7 +12,6 @@
build/*.jar
.settings
.cache
cache
.generated-mima*
work/
out/

+ 6 - 6
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java

@ -7,9 +7,9 @@ import org.springframework.boot.context.web.SpringBootServletInitializer;
/**
 * Created by Administrator on 2016.10.14.
 */
public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}
//public class ServletInitializer extends SpringBootServletInitializer {
//    @Override
//    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//        return application.sources(Application.class);
//    }
//}

+ 1 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/MessageDao.java

@ -17,7 +17,7 @@ public interface MessageDao extends PagingAndSortingRepository<Message, Long>, J
    @Query("select count(a) from Message a where a.type =1 and a.read= 1 and a.receiver=?1 ")
    int amountUnreadByReceiver(String doctor);
    @Query("select count(a) from Message a where a.read = 0 and over ='0'  and a.receiver=?1 and a.type=3 ")
    @Query("select count(a) from Message a where a.read = 1  and a.receiver=?1 and a.type=3 ")
    int amountUnreadSystemByReceiver(String doctor);

+ 1 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java

@ -18,7 +18,7 @@ public interface QuartzJobConfigDao extends PagingAndSortingRepository<QuartzJob
    @Query(" FROM QuartzJobConfig a WHERE a.status=?1 and a.del='1'")
    List<QuartzJobConfig> findByAll(String s);
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,20,21,22,23,24,25,26)  and a.del='1' ")
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,20,21,22,23,24,25,26,27)  and a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")

+ 178 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/AgentAppointmentFilter.java

@ -0,0 +1,178 @@
package com.yihu.wlyy.statistics.etl.dataFilter;
import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.patient.PatientReservation;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by Trick on 2017/5/9.
 */
@Component
@Scope("prototype")
public class AgentAppointmentFilter {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();//错误信息
    public FilterModel filter(List<PatientReservation> patientReservations, String sql, String filterDate){
        //查找出系统全部的全科医生
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospital2();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        //数据过滤清洗出脏数据  -----------start
        for(PatientReservation patientReservation:patientReservations){
            ETLModel etlModel=new ETLModel();
            String patient=patientReservation.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_sign_noExist));
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamCode()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_adminTeam_null));
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            //统计机构 -----------------start---------------------
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //统计社区
                orgCodeTemp=orgCode;
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_hospital_noExist));
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(patientReservation.getId().toString(),ErrorModel.healthGuidance_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(patientReservations.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(patientHealthGuidances.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }
    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}

+ 129 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AgentAppointmentJob.java

@ -0,0 +1,129 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.etl.dataFilter.AgentAppointmentFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.HealthGuideDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.patient.PatientReservation;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 预约统计指标执行类
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class AgentAppointmentJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private HealthGuideDataFilter healthGuideDataFilter;
    @Autowired
    private AgentAppointmentFilter agentAppointmentFilter;
    String yesterday;
    String daybefore;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
            daybefore= StringUtils.isEmpty(map.get("daybefore"))?SignJob.getDayString(-2):map.get("daybefore").toString();
            yesterday= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
        }catch (Exception e){
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }
    @Transactional
    private void computequota() {
        try {
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 27 + "'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //找出今天的健康指导信息
            String sql="select w.id,w.patient from  wlyy_patient_reservation w,wlyy_doctor d where w.doctor = d.code and  w.doctor is not null and w.dname is not null and w.czrq>='"+daybefore+ Constant.quota_date_last+"' and w.czrq< '"+yesterday+ Constant.quota_date_last+"'";
            //抽取數據
            List<PatientReservation> patientReservations = dbExtract.extract(PatientReservation.class,sql);
            //過濾數據
            FilterModel etlModels= agentAppointmentFilter.filter(patientReservations,sql,yesterday);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private String saveContent(List<PatientHealthGuidance> patientHealthGuidances, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount,String sql) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的健康指导数据完成 ,数据库查询到健康指导数目:"+patientHealthGuidances.size());
        string.append(",sql语句:"+sql);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append(",是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
    public String getYesterday() {
        return yesterday;
    }
}

+ 26 - 4
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentDayAllQuotaJob.java

@ -1,10 +1,7 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.ConsultDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.FollowUpDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.HealthGuideDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.*;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
@ -18,6 +15,7 @@ import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.patient.PatientReservation;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
@ -70,6 +68,8 @@ public class CurrentDayAllQuotaJob implements Job {
    @Autowired
    private HealthGuideDataFilter healthGuideDataFilter;
    @Autowired
    private AgentAppointmentFilter agentAppointmentFilter;
    @Autowired
    private FollowUpDataFilter followUpDataFilter;
    @Autowired
    private JdbcTemplate jdbcTemplate;
@ -181,6 +181,7 @@ public class CurrentDayAllQuotaJob implements Job {
        computequota_24();//及时回复的咨询量时间分布
        computequota_25();//统计质询量总数
        computequota_26();//统计未缴费签约总数
        computequota_27();//统计代预约量
        quartzJobLog.setJobContent(allContent.toString());
        quartzJobLog.setJobName("实时统计");
@ -943,6 +944,27 @@ public class CurrentDayAllQuotaJob implements Job {
        allContent.append("-----------26----------");
    }
    private void computequota_27() {
        String quotaId="27";
        String sql="select w.id,w.patient from  wlyy_patient_reservation w,wlyy_doctor d where w.doctor = d.code and  w.doctor is not null and w.dname is not null and w.czrq< '"+tomorrow+"' and w.czrq>= '"+now+"'";
        try{
            //抽取數據
            List<PatientReservation> patientReservations = SpringUtil.getBean(DBExtract.class).extract(PatientReservation.class,sql);
            //過濾數據
            FilterModel etlModels= agentAppointmentFilter.filter(patientReservations,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------27----------");
    }
    public static String getDayString(Integer size) {
        Date date = new Date();//取时间

CacheCleanJob.java → patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/cache/CacheCleanJob.java


+ 322 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/patient/PatientReservation.java

@ -0,0 +1,322 @@
package com.yihu.wlyy.statistics.model.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 预约挂号记录表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_reservation")
public class PatientReservation extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8452660447546825044L;
	// 预约号/预约流水号
	private String code;
	// 医生标识(医生帮患者预约时才会有值)
	private String doctor;
	// 医生姓名(医生帮患者预约时才会有值)
	private String dname;
	// 患者标识
	private String patient;
	// 患者身份证
	private String idcard;
	// 患者姓名
	private String name;
	// 患者手机号
	private String phone;
	// 患者社保卡号
	private String ssc;
	// 预约时间段:AM (上午)或者PM (下午)
	private String sectionType;
	// 一次预约段的开始时间
	private Date startTime;
	// 一次预约段的结束时间
	private Date endTime;
	// 医生所在医疗机构编码
	private String orgCode;
	// 医疗机构名称
	private String orgName;
	// 科室编码
	private String deptCode;
	// 科室名称
	private String deptName;
	// 专家ID/编码
	private String doctorCode;
	// 专家姓名
	private String doctorName;
	// 专家头像
	private String doctorPhoto;
	// 专家职称
	private String doctorJob;
	// 状态:1预约成功,0预约取消
	private Integer status;
	//取消预约者(状态为预约取消时才有值)
	private String canceler;
	//取消预约者姓名(状态为预约取消时才有值)
	private String cancelerName;
	//取消预约者角色(状态为预约取消时才有值)1专科医生,2全科医生,3健康管理师,4临时专科 5.患者 (与医生服务团队角色一直)
	private Integer cancelerType;
	//取消时间(状态为预约取消时才有值)
	private String cancelerTime;
	// 预约时间
	private Date czrq;
	// 0 健康之路 1智业
	private String type;
	// 签约类型 1三师 2家庭
	private Integer signType;
	// 行政团队
	private Long adminTeamCode;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	@Column(name = "section_type")
	public String getSectionType() {
		return sectionType;
	}
	public void setSectionType(String sectionType) {
		this.sectionType = sectionType;
	}
	@Column(name = "start_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getStartTime() {
		return startTime;
	}
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}
	@Column(name = "end_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEndTime() {
		return endTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	@Column(name = "org_code")
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	@Column(name = "org_name")
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}
	@Column(name = "dept_code")
	public String getDeptCode() {
		return deptCode;
	}
	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}
	@Column(name = "dept_name")
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	@Column(name = "doctor_code")
	public String getDoctorCode() {
		return doctorCode;
	}
	public void setDoctorCode(String doctorCode) {
		this.doctorCode = doctorCode;
	}
	@Column(name = "doctor_name")
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	@Column(name = "doctor_photo")
	public String getDoctorPhoto() {
		return doctorPhoto;
	}
	public void setDoctorPhoto(String doctorPhoto) {
		this.doctorPhoto = doctorPhoto;
	}
	@Column(name = "doctor_job")
	public String getDoctorJob() {
		return doctorJob;
	}
	public void setDoctorJob(String doctorJob) {
		this.doctorJob = doctorJob;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getCanceler() {
		return canceler;
	}
	public void setCanceler(String canceler) {
		this.canceler = canceler;
	}
	@Column(name = "canceler_name")
	public String getCancelerName() {
		return cancelerName;
	}
	public void setCancelerName(String cancelerName) {
		this.cancelerName = cancelerName;
	}
	@Column(name = "canceler_type")
	public Integer getCancelerType() {
		return cancelerType;
	}
	public void setCancelerType(Integer cancelerType) {
		this.cancelerType = cancelerType;
	}
	@Column(name = "canceler_time")
	public String getCancelerTime() {
		return cancelerTime;
	}
	public void setCancelerTime(String cancelerTime) {
		this.cancelerTime = cancelerTime;
	}
	@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 getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	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;
	}
}

+ 8 - 0
patient-co-wlyy/pom.xml

@ -266,6 +266,14 @@
            <version>20160212</version>
        </dependency>
        <!-- JSON end -->
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.htmlparser</groupId>
            <artifactId>htmlparser</artifactId>

+ 24 - 0
patient-co-wlyy/readme.MD

@ -0,0 +1,24 @@
doc 项目相关文档
src 代码
    main
        java
            com.yihu.wlyy
                aop 切面相关代码
                config 配置相关代码
                entity jpa 实体类相关代码
                event 事件相关代码
                exception 异常相关代码
                health 体征设备相关代码
                interceptors 拦截器相关代码
                job 任务相关代码
                logs 日志相关代码
                repository dao相关代码
                rest 
                service 服务类相关代码
                task 线程相关代码
                util 工具类相关代码
                web controller相关代码
                wechat 微信相关代码
        resource 资源和配置文件
        webapp  web相关代码

+ 10 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/Consult.java

@ -43,6 +43,8 @@ public class Consult extends IdEntity {
	private String del;
	// 结束时间
	private Date endTime;
	//签约表Code
	private String  signCode;
	public String getCode() {
		return code;
@ -124,4 +126,12 @@ public class Consult extends IdEntity {
	public void setGuidance(Long guidance) {
		this.guidance = guidance;
	}
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
}

+ 21 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/ConsultTeam.java

@ -9,6 +9,7 @@ import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import io.swagger.models.auth.In;
/**
 * 三师咨询
@ -53,6 +54,26 @@ public class ConsultTeam extends IdEntity {
	private Integer endType;
	// 结束时间
	private Date endTime;
	//是否评价 1、已评价 0、未评价'
	private Integer evaluate;
	//评价时间
	private Date evaluateTime;
	public Integer getEvaluate() {
		return evaluate;
	}
	public void setEvaluate(Integer evaluate) {
		this.evaluate = evaluate;
	}
	public Date getEvaluateTime() {
		return evaluateTime;
	}
	public void setEvaluateTime(Date evaluateTime) {
		this.evaluateTime = evaluateTime;
	}
	@Column(name = "admin_team_code")
	public Long getAdminTeamId() {

+ 77 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/Evaluate.java

@ -0,0 +1,77 @@
package com.yihu.wlyy.entity.consult;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by 卓 on 2017/5/10.
 */
@Entity
@Table(name = "wlyy_evaluate")
public class Evaluate extends IdEntity {
    private static final long serialVersionUID = -161924234234189L;
    private String doctor;//被评价的医生
    private String patient;//评价人
    private String consult;//咨询
    private Integer score;//分数
    private Integer type;//1、实名,2、匿名
    private Integer evaluateType;//评价种类0、实名评价, 1、专业能力,2、服务态度,3、回复速度
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getConsult() {
        return consult;
    }
    public void setConsult(String consult) {
        this.consult = consult;
    }
    public Integer getScore() {
        return score;
    }
    public void setScore(Integer score) {
        this.score = score;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Integer getEvaluateType() {
        return evaluateType;
    }
    public void setEvaluateType(Integer evaluateType) {
        this.evaluateType = evaluateType;
    }
}

+ 57 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/EvaluateLabel.java

@ -0,0 +1,57 @@
package com.yihu.wlyy.entity.consult;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by 卓 on 2017/5/10.
 */
@Entity
@Table(name = "wlyy_evaluate_label")
public class EvaluateLabel extends IdEntity {
    private static final long serialVersionUID = -161943424234234189L;
    private String doctor; //被评价的医生
    private String patient; //被评价的患者
    private String consult; //咨询code
    private String content;//标签内容
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getConsult() {
        return consult;
    }
    public void setConsult(String consult) {
        this.consult = consult;
    }
}

+ 226 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/device/PatientBloodSugger.java

@ -0,0 +1,226 @@
package com.yihu.wlyy.entity.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import javax.persistence.*;
import java.util.Date;
/**
 * Created by Reece on 2017/5/11.
 */
@Entity
@Table(name = "wlyy_patient_blood_sugger")
public class PatientBloodSugger extends IdEntity {
    //    早餐前开始时间
    private String fastingStart;
    //    '早餐前截止时间'
    private String fastingEnd;
    //    '早餐后开始时间'
    private String afterBreakfastStart;
    //    '早餐后截止时间'
    private String afterBreakfastEnd;
    //    '午餐前开始时间'
    private String beforeLunchStart;
    //    '午餐前截止时间'
    private String beforeLunchEnd;
    //    '午餐后开始时间'
    private String afterLunchStart;
    //    '午餐后截止时间'
    private String afterLunchEnd;
    //    '晚餐前开始时间'
    private String beforeDinnerStart;
    //    '晚餐前截止时间'
    private String beforeDinnerEnd;
    //    '晚餐后开始时间'
    private String afterDinnerStart;
    //    '晚餐后截止时间'
    private String afterDinnerEnd;
    //    '睡前开始时间'
    private String beforeSleepStart;
    //    '睡前截止时间'
    private String beforeSleepEnd;
    //    '添加时间'
    private Date czrq;
    //    是否作废,1正常,0作废
    private int del;
    public PatientBloodSugger() {
    }
    @Column(name = "fasting_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getFastingStart() {
        return fastingStart;
    }
    public void setFastingStart(String fastingStart) {
        this.fastingStart = fastingStart;
    }
    @Column(name = "fasting_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getFastingEnd() {
        return fastingEnd;
    }
    public void setFastingEnd(String fastingEnd) {
        this.fastingEnd = fastingEnd;
    }
    @Column(name = "after_breakfast_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterBreakfastStart() {
        return afterBreakfastStart;
    }
    public void setAfterBreakfastStart(String afterBreakfastStart) {
        this.afterBreakfastStart = afterBreakfastStart;
    }
    @Column(name = "after_breakfast_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterBreakfastEnd() {
        return afterBreakfastEnd;
    }
    public void setAfterBreakfastEnd(String afterBreakfastEnd) {
        this.afterBreakfastEnd = afterBreakfastEnd;
    }
    @Column(name = "before_lunch_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeLunchStart() {
        return beforeLunchStart;
    }
    public void setBeforeLunchStart(String beforeLunchStart) {
        this.beforeLunchStart = beforeLunchStart;
    }
    @Column(name = "before_lunch_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeLunchEnd() {
        return beforeLunchEnd;
    }
    public void setBeforeLunchEnd(String beforeLunchEnd) {
        this.beforeLunchEnd = beforeLunchEnd;
    }
    @Column(name = "after_lunch_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterLunchStart() {
        return afterLunchStart;
    }
    public void setAfterLunchStart(String afterLunchStart) {
        this.afterLunchStart = afterLunchStart;
    }
    @Column(name = "after_lunch_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterLunchEnd() {
        return afterLunchEnd;
    }
    public void setAfterLunchEnd(String afterLunchEnd) {
        this.afterLunchEnd = afterLunchEnd;
    }
    @Column(name = "before_dinner_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeDinnerStart() {
        return beforeDinnerStart;
    }
    public void setBeforeDinnerStart(String beforeDinnerStart) {
        this.beforeDinnerStart = beforeDinnerStart;
    }
    @Column(name = "before_dinner_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeDinnerEnd() {
        return beforeDinnerEnd;
    }
    public void setBeforeDinnerEnd(String beforeDinnerEnd) {
        this.beforeDinnerEnd = beforeDinnerEnd;
    }
    @Column(name = "after_dinner_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterDinnerStart() {
        return afterDinnerStart;
    }
    public void setAfterDinnerStart(String afterDinnerStart) {
        this.afterDinnerStart = afterDinnerStart;
    }
    @Column(name = "after_dinner_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterDinnerEnd() {
        return afterDinnerEnd;
    }
    public void setAfterDinnerEnd(String afterDinnerEnd) {
        this.afterDinnerEnd = afterDinnerEnd;
    }
    @Column(name = "before_sleep_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeSleepStart() {
        return beforeSleepStart;
    }
    public void setBeforeSleepStart(String beforeSleepStart) {
        this.beforeSleepStart = beforeSleepStart;
    }
    @Column(name = "before_sleep_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeSleepEnd() {
        return beforeSleepEnd;
    }
    public void setBeforeSleepEnd(String beforeSleepEnd) {
        this.beforeSleepEnd = beforeSleepEnd;
    }
    @Column(name = "czrq")
    @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;
    }
}

+ 248 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/device/PatientHealthTime.java

@ -0,0 +1,248 @@
package com.yihu.wlyy.entity.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import javax.persistence.*;
import java.util.Date;
/**
 * Created by Reece on 2017/5/11.
 */
@Entity
@Table(name = "wlyy_patient_health_time")
public class PatientHealthTime extends IdEntity {
    //    居民
    private String user;
    //    设备sn码
    private String deviceSN;
    //    早餐前开始时间
    private String fastingStart;
    //    '早餐前截止时间'
    private String fastingEnd;
    //    '早餐后开始时间'
    private String afterBreakfastStart;
    //    '早餐后截止时间'
    private String afterBreakfastEnd;
    //    '午餐前开始时间'
    private String beforeLunchStart;
    //    '午餐前截止时间'
    private String beforeLunchEnd;
    //    '午餐后开始时间'
    private String afterLunchStart;
    //    '午餐后截止时间'
    private String afterLunchEnd;
    //    '晚餐前开始时间'
    private String beforeDinnerStart;
    //    '晚餐前截止时间'
    private String beforeDinnerEnd;
    //    '晚餐后开始时间'
    private String afterDinnerStart;
    //    '晚餐后截止时间'
    private String afterDinnerEnd;
    //    '睡前开始时间'
    private String beforeSleepStart;
    //    '睡前截止时间'
    private String beforeSleepEnd;
    //    '添加时间'
    private Date czrq;
    //    是否作废,1正常,0作废
    private int del;
    public PatientHealthTime() {
    }
    @Column(name = "user")
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    @Column(name = "device_sn")
    public String getDeviceSN() {
        return deviceSN;
    }
    public void setDeviceSN(String deviceSN) {
        this.deviceSN = deviceSN;
    }
    @Column(name = "fasting_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getFastingStart() {
        return fastingStart;
    }
    public void setFastingStart(String fastingStart) {
        this.fastingStart = fastingStart;
    }
    @Column(name = "fasting_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getFastingEnd() {
        return fastingEnd;
    }
    public void setFastingEnd(String fastingEnd) {
        this.fastingEnd = fastingEnd;
    }
    @Column(name = "after_breakfast_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterBreakfastStart() {
        return afterBreakfastStart;
    }
    public void setAfterBreakfastStart(String afterBreakfastStart) {
        this.afterBreakfastStart = afterBreakfastStart;
    }
    @Column(name = "after_breakfast_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterBreakfastEnd() {
        return afterBreakfastEnd;
    }
    public void setAfterBreakfastEnd(String afterBreakfastEnd) {
        this.afterBreakfastEnd = afterBreakfastEnd;
    }
    @Column(name = "before_lunch_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeLunchStart() {
        return beforeLunchStart;
    }
    public void setBeforeLunchStart(String beforeLunchStart) {
        this.beforeLunchStart = beforeLunchStart;
    }
    @Column(name = "before_lunch_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeLunchEnd() {
        return beforeLunchEnd;
    }
    public void setBeforeLunchEnd(String beforeLunchEnd) {
        this.beforeLunchEnd = beforeLunchEnd;
    }
    @Column(name = "after_lunch_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterLunchStart() {
        return afterLunchStart;
    }
    public void setAfterLunchStart(String afterLunchStart) {
        this.afterLunchStart = afterLunchStart;
    }
    @Column(name = "after_lunch_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterLunchEnd() {
        return afterLunchEnd;
    }
    public void setAfterLunchEnd(String afterLunchEnd) {
        this.afterLunchEnd = afterLunchEnd;
    }
    @Column(name = "before_dinner_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeDinnerStart() {
        return beforeDinnerStart;
    }
    public void setBeforeDinnerStart(String beforeDinnerStart) {
        this.beforeDinnerStart = beforeDinnerStart;
    }
    @Column(name = "before_dinner_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeDinnerEnd() {
        return beforeDinnerEnd;
    }
    public void setBeforeDinnerEnd(String beforeDinnerEnd) {
        this.beforeDinnerEnd = beforeDinnerEnd;
    }
    @Column(name = "after_dinner_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterDinnerStart() {
        return afterDinnerStart;
    }
    public void setAfterDinnerStart(String afterDinnerStart) {
        this.afterDinnerStart = afterDinnerStart;
    }
    @Column(name = "after_dinner_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getAfterDinnerEnd() {
        return afterDinnerEnd;
    }
    public void setAfterDinnerEnd(String afterDinnerEnd) {
        this.afterDinnerEnd = afterDinnerEnd;
    }
    @Column(name = "before_sleep_start")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeSleepStart() {
        return beforeSleepStart;
    }
    public void setBeforeSleepStart(String beforeSleepStart) {
        this.beforeSleepStart = beforeSleepStart;
    }
    @Column(name = "before_sleep_end")
    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+08:00")
    public String getBeforeSleepEnd() {
        return beforeSleepEnd;
    }
    public void setBeforeSleepEnd(String beforeSleepEnd) {
        this.beforeSleepEnd = beforeSleepEnd;
    }
    @Column(name = "czrq")
    @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;
    }
}

+ 10 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/doctor/profile/Doctor.java

@ -64,6 +64,16 @@ public class Doctor extends IdEntity {
    private String isPasswordPrompt;// 是否提示密码信息 1是 0或者空是否
    private String isHelp;//是否求助  1已经求助 0未求助
    private Double evaluateScore;//评分
    public Double getEvaluateScore() {
        return evaluateScore;
    }
    public void setEvaluateScore(Double evaluateScore) {
        this.evaluateScore = evaluateScore;
    }
    public Doctor() {
    }

+ 31 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticlePatient.java

@ -48,6 +48,29 @@ public class HealthEduArticlePatient extends IdEntity {
	private Long adminTeamCode;
	// 简介
	private String summary;
	//附加内容
	private String attachedContent;
	//批次号记录发送所属批次
	private String batchNo;
	//签约表code
	private String signCode;
	public String getBatchNo() {
		return batchNo;
	}
	public void setBatchNo(String batchNo) {
		this.batchNo = batchNo;
	}
	public String getAttachedContent() {
		return attachedContent;
	}
	public void setAttachedContent(String attachedContent) {
		this.attachedContent = attachedContent;
	}
	public String getPatient() {
		return patient;
@ -147,4 +170,12 @@ public class HealthEduArticlePatient extends IdEntity {
	public void setSummary(String summary) {
		this.summary = summary;
	}
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
}

+ 144 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/feedback/Appeal.java

@ -0,0 +1,144 @@
package com.yihu.wlyy.entity.feedback;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Reece on 2017/5/6.
 */
@Entity
@Table(name = "wlyy_appeal")
public class Appeal extends IdEntity {
    //   '账号申诉编码'
    private String code;
    //    申诉人编码
    private String creater;
    //    '问题描述'
    private String description;
    //    申诉类别:1、手机号变更、2、重置密码、3、其他
    private int type;
    //    图片路径,逗号分隔
    private String images;
    //    联系手机号
    private String phone;
    //    状态 0、未读 1、待处理  2、已处理
    private int status;
    //    '处理结果'
    private String result;
    //    申诉人身份:1、患者  2、医生
    private int identity;
    //是否删除   0 删除    1.未删除
    private Integer del ;
    @Column(name="creater_name")
    private String createrName;
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public String getCreaterName() {
        return createrName;
    }
    public void setCreaterName(String createrName) {
        this.createrName = createrName;
    }
    public Appeal() {
    }
    public Appeal(String code, String creater, String description, int type, String images, String phone, int status, String result, int identity, Integer del, String createrName) {
        this.code = code;
        this.creater = creater;
        this.description = description;
        this.type = type;
        this.images = images;
        this.phone = phone;
        this.status = status;
        this.result = result;
        this.identity = identity;
        this.del = del;
        this.createrName = createrName;
    }
    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;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public int getIdentity() {
        return identity;
    }
    public void setIdentity(int identity) {
        this.identity = identity;
    }
}

+ 149 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/feedback/Feedback.java

@ -0,0 +1,149 @@
package com.yihu.wlyy.entity.feedback;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.*;
/**
 * Created by Reece on 2017/5/6.
 */
@Entity
@Table(name = "wlyy_feedback")
public class Feedback extends IdEntity{
//    意见反馈编码
    @Column(name="code")
    private String code;
//    反馈人编码
    @Column(name="creater")
    private String creater;
//    反馈人身份 1、患者  2、医生
    @Column(name="identity")
    private  int identity;
//    问题描述
    @Column(name="description")
    private String description;
//    反馈类别:1、优化建议、2、提交bug、3、新功能建议、4、其他
    @Column(name="type")
    private int type;
//    图片路径,逗号分隔
    @Column(name="images")
    private String images;
//    联系方式: qq号或者邮箱
    @Column(name="contact")
    private String contact;
//    状态 0、未读 1、已读
    @Column(name="status")
    private int status;
    //逻辑删除 0.删除   1.正常
    @Column(name="del")
    private Integer del;
    //创建人名字
    @Column(name="creater_name")
    private String createrName;
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public String getCreaterName() {
        return createrName;
    }
    public void setCreaterName(String createrName) {
        this.createrName = createrName;
    }
    public Feedback(String code, String creater, int identity, String description, int type, String images, String contact, int status, Integer del, String createrName) {
        this.code = code;
        this.creater = creater;
        this.identity = identity;
        this.description = description;
        this.type = type;
        this.images = images;
        this.contact = contact;
        this.status = status;
        this.del = del;
        this.createrName = createrName;
    }
    public Feedback() {
    }
    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;
    }
    public int getIdentity() {
        return identity;
    }
    public void setIdentity(int identity) {
        this.identity = identity;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
}

+ 11 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/followup/Followup.java

@ -62,6 +62,9 @@ public class Followup extends IdEntity {
	// 行政团队
	private Long adminTeamCode;
	//签约表Code
	private String signCode;
	public Date getFollowupPlanDate() {
		return followupPlanDate;
	}
@ -241,4 +244,12 @@ public class Followup extends IdEntity {
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
}

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 2 - 2
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/message/Message.java


+ 36 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/message/SMS.java

@ -24,6 +24,42 @@ public class SMS extends IdEntity {
    private Date deadline;// 过期时间
    private Integer status;// 状态,0未发送,1已发送
    private Date czrq;
    private String userCode;//用户标示
    private Integer userType;//用户类型
    private String town; //所属区
    private String hospital;//所属机构,未签约用居民地址
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public Integer getUserType() {
        return userType;
    }
    public void setUserType(Integer userType) {
        this.userType = userType;
    }
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getMobile() {
        return mobile;

+ 10 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/PatientHealthGuidance.java

@ -44,6 +44,8 @@ public class PatientHealthGuidance extends IdEntity {
	private int readStatus;
//	指导创建时间
	private Date createTime;
	//签约表Code
	private String signCode;
	public Date getCreateTime() {
		return createTime;
@ -133,4 +135,12 @@ public class PatientHealthGuidance extends IdEntity {
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
}

+ 479 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/patient/SignFamilyRenew.java

@ -0,0 +1,479 @@
package com.yihu.wlyy.entity.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 家庭签约
 *
 * @author George
 */
@Entity
@Table(name = "wlyy_sign_family_renew")
public class SignFamilyRenew extends IdEntity {
    private static final long serialVersionUID = 364799142991631092L;
    private String code;        // 签约标识
    private String lwCode;      // 两网标识
    private Integer type;       // 签约类型:1三师签约,2网络签约
    private String patient;     // 患者标识
    private String openid;      // 微信OPENID
    private String name;        // 患者姓名
    private String idcard;      // 身份证号
    private String ssc;         // 社保卡号
    private String mobile;      // 手机号
    private String emerMobile;  // 紧急联系人手机号
    private String hospital;    // 签约医院标识
    private String hospitalName;    // 签约医院名称
    private String doctor;      // 全科医生
    private String doctorName;  // 全科医生姓名
    private String doctorHealth;    // 健康管理师
    private String doctorHealthName;    // 健康管理师姓名
    private Date begin;         // 签约开始日期
    private Date end;           // 签约结束日期
    private Integer status;     // 签约状态(-1患者已取消,-2已拒绝,-3已解约,-4已到期,0待签约,1已签约,2患者申请取消签约
    private String images;      // 签约图片附件URL,多图以逗号分隔
    private String reason;      // 解约原因
    private Date czrq;          // 操作时间
    private String teamCode;
    private Date applyDate;     //签约时间
    private Date applyUnsignDate;//解约时间
    private Date patientApplyDate;//患者发起签约时间
    private Date patientApplyUnsignDate;//患者发起解约时间
    private String signType;//1 用户自己申请  2医生手工带签  3.医生发起邀请
    private String familyCode;//签约code
    private Double expenses;//签约费用
    private String expensesStatus;//扣费状态【0未扣费 1已扣费 2已退费】
    private String signSource;// 签约来源【1 社区签约 2 移动签约】
    private String signDoctorCode;//簽約人code
    private String signDoctorName;//簽約人銘
    private String signDoctorLevel;//簽約人等级
    private String expensesType;//补贴类型(4种类型:01无补贴,02全部贴,03补个人承担部分(20),04补统筹基金(70))
    private String signYear;//签约年度
    private String medicalInsuranceNum;//医保流水号
    private String agentDoctorCode;//代理簽約人code
    private String agentDoctorName;//代理簽約人銘
    private String agentDoctorLevel;//代理簽約人等级
    private Long adminTeamId;//行政团队ID
    private Date expensesTime;//缴费时间
    private Integer isValid;//是否生效
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getLwCode() {
        return lwCode;
    }
    public void setLwCode(String lwCode) {
        this.lwCode = lwCode;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    @Column(name = "emer_mobile")
    public String getEmerMobile() {
        return emerMobile;
    }
    public void setEmerMobile(String emerMobile) {
        this.emerMobile = emerMobile;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "hospital_name")
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "doctor_health")
    public String getDoctorHealth() {
        return doctorHealth;
    }
    public void setDoctorHealth(String doctorHealth) {
        this.doctorHealth = doctorHealth;
    }
    @Column(name = "doctor_health_name")
    public String getDoctorHealthName() {
        return doctorHealthName;
    }
    public void setDoctorHealthName(String doctorHealthName) {
        this.doctorHealthName = doctorHealthName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getBegin() {
        return begin;
    }
    public void setBegin(Date begin) {
        this.begin = begin;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getEnd() {
        return end;
    }
    public void setEnd(Date end) {
        this.end = end;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getReason() {
        return reason;
    }
    public void setReason(String reason) {
        this.reason = reason;
    }
    @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;
    }
    @Column(name = "team_code")
    public String getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(String teamCode) {
        this.teamCode = teamCode;
    }
    @Column(name = "sign_type")
    public String getSignType() {
        return signType;
    }
    public void setSignType(String signType) {
        this.signType = signType;
    }
    @Column(name = "apply_date")
    public Date getApplyDate() {
        return applyDate;
    }
    public void setApplyDate(Date applyDate) {
        this.applyDate = applyDate;
    }
    @Column(name = "patient_apply_date")
    public Date getPatientApplyDate() {
        return patientApplyDate;
    }
    public void setPatientApplyDate(Date patientApplyDate) {
        this.patientApplyDate = patientApplyDate;
    }
    @Column(name = "patient_apply_unsgin_date")
    public Date getPatientApplyUnsignDate() {
        return patientApplyUnsignDate;
    }
    public void setPatientApplyUnsignDate(Date patientApplyUnsignDate) {
        this.patientApplyUnsignDate = patientApplyUnsignDate;
    }
    @Column(name = "family_code")
    public String getFamilyCode() {
        return familyCode;
    }
    public void setFamilyCode(String familyCode) {
        this.familyCode = familyCode;
    }
    @Column(name = "expenses")
    public Double getExpenses() {
        return expenses;
    }
    public void setExpenses(Double expenses) {
        this.expenses = expenses;
    }
    @Column(name = "sign_doctor_code")
    public String getSignDoctorCode() {
        return signDoctorCode;
    }
    public void setSignDoctorCode(String signDoctorCode) {
        this.signDoctorCode = signDoctorCode;
    }
    @Column(name = "sign_doctor_name")
    public String getSignDoctorName() {
        return signDoctorName;
    }
    public void setSignDoctorName(String signDoctorName) {
        this.signDoctorName = signDoctorName;
    }
    @Column(name = "sign_doctor_level")
    public String getSignDoctorLevel() {
        return signDoctorLevel;
    }
    public void setSignDoctorLevel(String signDoctorLevel) {
        this.signDoctorLevel = signDoctorLevel;
    }
    @Column(name = "apply_unsign_date")
    public Date getApplyUnsignDate() {
        return applyUnsignDate;
    }
    public void setApplyUnsignDate(Date applyUnsignDate) {
        this.applyUnsignDate = applyUnsignDate;
    }
    @Column(name = "expenses_type")
    public String getExpensesType() {
        return expensesType;
    }
    public void setExpensesType(String expensesType) {
        this.expensesType = expensesType;
    }
    @Column(name = "sign_year")
    public String getSignYear() {
        return signYear;
    }
    public void setSignYear(String signYear) {
        this.signYear = signYear;
    }
    @Column(name = "medical_insurance_num")
    public String getMedicalInsuranceNum() {
        return medicalInsuranceNum;
    }
    public void setMedicalInsuranceNum(String medicalInsuranceNum) {
        this.medicalInsuranceNum = medicalInsuranceNum;
    }
    @Column(name = "agent_doctor_code")
    public String getAgentDoctorCode() {
        return agentDoctorCode;
    }
    public void setAgentDoctorCode(String agentDoctorCode) {
        this.agentDoctorCode = agentDoctorCode;
    }
    @Column(name = "agent_doctor_name")
    public String getAgentDoctorName() {
        return agentDoctorName;
    }
    public void setAgentDoctorName(String agentDoctorName) {
        this.agentDoctorName = agentDoctorName;
    }
    @Column(name = "agent_doctor_level")
    public String getAgentDoctorLevel() {
        return agentDoctorLevel;
    }
    public void setAgentDoctorLevel(String agentDoctorLevel) {
        this.agentDoctorLevel = agentDoctorLevel;
    }
    @Column(name = "expenses_status")
    public String getExpensesStatus() {
        return expensesStatus;
    }
    public void setExpensesStatus(String expensesStatus) {
        this.expensesStatus = expensesStatus;
    }
    @Column(name = "sign_source")
    public String getSignSource() {
        return signSource;
    }
    public void setSignSource(String signSource) {
        this.signSource = signSource;
    }
    @Column(name = "admin_team_code")
    public Long getAdminTeamId() {
        return adminTeamId;
    }
    public void setAdminTeamId(Long adminTeamId) {
        this.adminTeamId = adminTeamId;
    }
    @Override
    public String toString() {
        return "SignFamily{" +
                "code='" + code + '\'' +
                ", lwCode='" + lwCode + '\'' +
                ", type=" + type +
                ", patient='" + patient + '\'' +
                ", openid='" + openid + '\'' +
                ", name='" + name + '\'' +
                ", idcard='" + idcard + '\'' +
                ", ssc='" + ssc + '\'' +
                ", mobile='" + mobile + '\'' +
                ", emerMobile='" + emerMobile + '\'' +
                ", hospital='" + hospital + '\'' +
                ", hospitalName='" + hospitalName + '\'' +
                ", doctor='" + doctor + '\'' +
                ", doctorName='" + doctorName + '\'' +
                ", doctorHealth='" + doctorHealth + '\'' +
                ", doctorHealthName='" + doctorHealthName + '\'' +
                ", begin=" + begin +
                ", end=" + end +
                ", status=" + status +
                ", images='" + images + '\'' +
                ", reason='" + reason + '\'' +
                ", czrq=" + czrq +
                ", teamCode='" + teamCode + '\'' +
                ", applyDate=" + applyDate +
                ", signType='" + signType + '\'' +
                ", familyCode='" + familyCode + '\'' +
                '}';
    }
    public Date getExpensesTime() {
        return expensesTime;
    }
    public void setExpensesTime(Date expensesTime) {
        this.expensesTime = expensesTime;
    }
    @Column(name="is_valid")
    public Integer getIsValid() {
        return isValid;
    }
    public void setIsValid(Integer isValid) {
        this.isValid = isValid;
    }
}

+ 8 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java

@ -2,6 +2,7 @@ package com.yihu.wlyy.event;
import com.yihu.wlyy.job.QuartzHelper;
import com.yihu.wlyy.job.SignEndJob;
import com.yihu.wlyy.job.consult.EvaluateScoreJob;
import com.yihu.wlyy.util.SystemConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
@ -30,6 +31,13 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
            } else {
                System.out.println("sign end job exist");
            }
            if (!quartzHelper.isExistJob("evaluate_score_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("evaluate_score_job");
                quartzHelper.addJob(EvaluateScoreJob.class, trigger, "evaluate_score_job", new HashMap<String, Object>());
                System.out.println("evaluate_score_job start success");
            } else {
                System.out.println("evaluate_score_job exist");
            }
        } catch (Exception e) {
            System.out.println("sign end job start failed");
        }

+ 37 - 34
patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java

@ -5,6 +5,7 @@ import io.swagger.models.auth.In;
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 org.springframework.jca.cci.core.InteractionCallback;
@ -13,42 +14,43 @@ import java.util.Date;
import java.util.List;
public interface DevicePatientHealthIndexDao
		extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
        extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
	 List<DevicePatientHealthIndex> findByIdcardAndType(String idcard,Integer type);
    List<DevicePatientHealthIndex> findByIdcardAndType(String idcard, Integer type);
	/**
	 * 按录入时间和患者标识查询健康记录
	 * @param patientCode
	 * @param date
	 * @return
	 */
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
	Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
	
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by recordDate order by recordDate asc")
	Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
	
	@Query("select a.value1 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value1 > 0 order by recordDate desc")
	Page<String> findValue1ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value2 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value2 > 0 order by recordDate desc")
	Page<String> findValue2ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value3 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value3 > 0 order by recordDate desc")
	Page<String> findValue3ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value4 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value4 > 0 order by recordDate desc")
	Page<String> findValue4ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value5 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value5 > 0 order by recordDate desc")
	Page<String> findValue5ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value6 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value6 > 0 order by recordDate desc")
	Page<String> findValue6ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	
	@Query("select a.value7 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value7 > 0 order by recordDate desc")
	Page<String> findValue7ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @param patientCode
     * @param date
     * @return
     */
    @Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
    Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
    @Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by recordDate order by recordDate asc")
    Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
    @Query("select a.value1 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value1 > 0 order by recordDate desc")
    Page<String> findValue1ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value2 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value2 > 0 order by recordDate desc")
    Page<String> findValue2ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value3 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value3 > 0 order by recordDate desc")
    Page<String> findValue3ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value4 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value4 > 0 order by recordDate desc")
    Page<String> findValue4ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value5 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value5 > 0 order by recordDate desc")
    Page<String> findValue5ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value6 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value6 > 0 order by recordDate desc")
    Page<String> findValue6ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
    @Query("select a.value7 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value7 > 0 order by recordDate desc")
    Page<String> findValue7ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate >= ?3 and a.recordDate <= ?4 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Date start, Date end, Pageable pageRequest);
@ -56,6 +58,7 @@ public interface DevicePatientHealthIndexDao
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.value2 =?3 and a.recordDate >= ?4 and a.recordDate <= ?5 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type,String gi_type, Date start, Date end, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.del = '1'")
	List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Pageable pageRequest);

+ 3 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/interceptors/DoctorInterceptor.java

@ -138,6 +138,9 @@ public class DoctorInterceptor extends BaseInterceptor {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(null==request.getAttribute("log-start")){
            return;
        }
        long start = (long) request.getAttribute("log-start");
        long end = new Date().getTime();
        Class cls = ((HandlerMethod) handler).getBeanType();

+ 12 - 11
patient-co-wlyy/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java

@ -1,22 +1,20 @@
package com.yihu.wlyy.interceptors;
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
/**
 * 患者权限校验
@ -31,7 +29,7 @@ public class PatientInterceptor extends BaseInterceptor {
		try {
			request.setCharacterEncoding("UTF-8");
			request.setAttribute("log-start", new Date().getTime());
			if(request.getRequestURI().contains("/patient/hosptail/getHositalByTownCode")){
			if(request.getRequestURI().contains("/patient/hosptail/getHositalByTownCode")||request.getRequestURI().contains("/patient/feedback/saveAppeal")){
				return true;
			}
			response.setCharacterEncoding("UTF-8");
@ -98,6 +96,9 @@ public class PatientInterceptor extends BaseInterceptor {
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if(null==request.getAttribute("log-start")){
			return;
		}
		long start = (long) request.getAttribute("log-start");
		long end = new Date().getTime();
		Class cls = ((HandlerMethod) handler).getBeanType();

+ 4 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/job/SignEndJob.java

@ -35,6 +35,7 @@ public class SignEndJob implements Job {
            int sucessT = jdbcTemplate.update(sqlT, start, end);
            int sucessTm = jdbcTemplate.update(sqlTm, start, end);
            int sucess = jdbcTemplate.update(sql, start, end);
            renewToSign();
            System.out.println("sign end job end");
        } catch (Exception e) {
            e.printStackTrace();
@ -42,4 +43,7 @@ public class SignEndJob implements Job {
        }
    }
    public void renewToSign(){
    }
}

+ 107 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/job/consult/EvaluateScoreJob.java

@ -0,0 +1,107 @@
package com.yihu.wlyy.job.consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamDoctor;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.job.QuartzHelper;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.service.quota.JobService;
import com.yihu.wlyy.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
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 org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.math.BigDecimal;
import java.util.*;
import static com.yihu.wlyy.job.consult.ConsultCleanerJob.ConsultTerminatorJobKey;
/**
 * @author Sand
 * @since 2016/9/26
 */
@Service
public class EvaluateScoreJob implements Job{
    @Autowired
    ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DoctorDao doctorDao;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            System.out.println("calculate evaluate job start");
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //获取有被评价过的医生列表
            String doctorsSql = "select w.doctor from wlyy_evaluate w group by w.doctor";
            String sql = "select w.evaluate_type,sum(w.score) as score from wlyy_evaluate w where w.doctor =? GROUP BY w.evaluate_type,w.doctor";
            String evaluateTimesSql = "select count(1) as count from wlyy_evaluate w where w.doctor =? GROUP BY w.consult,w.doctor";
            List<Map<String, Object>> doctorList = jdbcTemplate.queryForList(doctorsSql);
            for (Map<String, Object> doctorMap : doctorList) {
                //获取医生的所有评价信息
                String doctor =  doctorMap.get("doctor").toString();
                List<Map<String, Object>> evaluateList = jdbcTemplate.queryForList(sql, new Object[]{doctor});
                BigDecimal score = BigDecimal.ZERO;//总分
                BigDecimal anonymousScore = BigDecimal.ZERO;//匿名评价分
                BigDecimal realScore = BigDecimal.ZERO;//实名评价分
                BigDecimal jiaquan = BigDecimal.ZERO;//加权平均分
                for (Map<String, Object> evaluate : evaluateList) {
                    BigDecimal scoreTemp = new BigDecimal(evaluate.get("score").toString());
                    switch (evaluate.get("evaluate_type").toString()) {
                        case "0":
                            realScore = realScore.add(scoreTemp.multiply(new BigDecimal("0.3")));
                            break;
                        case "1":
                            anonymousScore=  anonymousScore.add(scoreTemp.multiply(new BigDecimal("0.2")));
                            break;
                        case "2":
                            anonymousScore=  anonymousScore.add(scoreTemp.multiply(new BigDecimal("0.25")));
                            break;
                        case "3":
                            anonymousScore=  anonymousScore.add(scoreTemp.multiply(new BigDecimal("0.25")));
                            break;
                    }
                }
                //获取有效评价次数
                List<Map<String, Object>> evaluateTimesList = jdbcTemplate.queryForList(evaluateTimesSql, new Object[]{doctor});
                int evaTimes = Integer.parseInt(evaluateTimesList.get(0).get("count").toString());
                if(evaTimes>0){
                    evaTimes = evaluateTimesList.size();
                }
                int consultTimes = consultTeamDoctorDao.countByDoctorAndType(2, doctor);
                jiaquan = (anonymousScore.add(realScore)).divide(BigDecimal.valueOf(evaTimes),2,BigDecimal.ROUND_HALF_UP);
                if (consultTimes <= 100) {  //咨询系数 咨询次数≤100次,对应系数为3;
                    //100次<咨询次数≤1000次,对应系数为2;
                    //咨询次数>1000次,对应系数为1。
                    jiaquan = (jiaquan.subtract(BigDecimal.valueOf(80L))).divide(BigDecimal.valueOf(3L),2,BigDecimal.ROUND_HALF_UP);
                } else if (consultTimes > 100 && consultTimes <= 1000) {
                    jiaquan = (jiaquan.subtract(BigDecimal.valueOf(80L))).divide(BigDecimal.valueOf(2L),2,BigDecimal.ROUND_HALF_UP);
                } else {
                    jiaquan = (jiaquan.subtract(BigDecimal.valueOf(80L))).divide(BigDecimal.valueOf(1L),2,BigDecimal.ROUND_HALF_UP);
                }
                score = jiaquan.add(BigDecimal.valueOf(80L)).setScale(1, BigDecimal.ROUND_HALF_UP);
                //计算完毕
                Doctor d  =  doctorDao.findByCode(doctor);
                d.setEvaluateScore(score.doubleValue());
                doctorDao.save(d);
            }
            System.out.println("calculate evaluate job end");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("calculate evaluate job failed");
        }
    }
}

+ 4 - 4
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultDao.java

@ -13,19 +13,19 @@ public interface ConsultDao extends PagingAndSortingRepository<Consult, Long>, J
    Consult findByCode(String code);
    // 查询患者咨询记录
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.del = '1' and a.symptoms like ?2 order by a.czrq desc")
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.del = '1' and a.symptoms like ?2 order by a.czrq desc")
    Page<Object> findByPatient(String patient, String title, Pageable pageRequest);
    // 查询患者咨询记录
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.id < ?3 and a.del = '1'and a.symptoms like ?2 order by a.czrq desc")
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.id < ?3 and a.del = '1'and a.symptoms like ?2 order by a.czrq desc")
    Page<Object> findByPatient(String patient, String title, long id, Pageable pageRequest);
    // 查询患者咨询记录
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.del = '1' order by a.czrq desc")
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.del = '1' order by a.czrq desc")
    Page<Object> findByPatient(String patient, Pageable pageRequest);
    // 查询患者咨询记录
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.id < ?2 and a.del = '1'order by a.czrq desc")
    @Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate from Consult a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.id < ?2 and a.del = '1'order by a.czrq desc")
    Page<Object> findByPatient(String patient, long id, Pageable pageRequest);
    @Query("select count(a) from Consult a,ConsultTeamDoctor b  where a.code = b.consult and a.patient=?1 and b.to=?2 and b.from is null")

+ 3 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamDoctorDao.java

@ -12,6 +12,9 @@ public interface ConsultTeamDoctorDao extends PagingAndSortingRepository<Consult
	@Query("select count(1) from ConsultTeamDoctor a where a.consult = ?1 and a.to = ?2")
	int isExist(String consult, String doctor);
	@Query("select count(1) from ConsultTeamDoctor a,ConsultTeam t where t.consult = a.consult and t.type = ?1 and a.to = ?2")
	int countByDoctorAndType(int type,String doctor);
	// 更新为有回复
	@Modifying
	@Query("update ConsultTeamDoctor a set a.reply = 1 where a.consult = ?1 and a.to = ?2")

+ 36 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/EvaluateDao.java

@ -0,0 +1,36 @@
package com.yihu.wlyy.repository.consult;
import com.yihu.wlyy.entity.consult.Evaluate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by 卓 on 2017/5/10.
 */
public interface EvaluateDao extends PagingAndSortingRepository<Evaluate, Long>, JpaSpecificationExecutor<Evaluate> {
    /**
     * 获取某个咨询的评分
     * @param consult
     * @return
     */
    List<Evaluate> findByConsult(String consult);
    /**
     * 根据咨询获取实名或者匿名评分
     * @param consult
     * @return
     */
    List<Evaluate> findByConsultAndType(String consult,int type);
    /**
     * 根据医生获取实名或者匿名评分
     * @param doctor
     * @return
     */
    List<Evaluate> findByDoctorAndType(String doctor,int type);
}

+ 28 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/EvaluateLabelDao.java

@ -0,0 +1,28 @@
package com.yihu.wlyy.repository.consult;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by 卓 on 2017/5/10.
 */
public interface EvaluateLabelDao extends PagingAndSortingRepository<EvaluateLabel, Long>, JpaSpecificationExecutor<EvaluateLabel> {
    /**
     * 获取某个咨询的标签
     * @param consult
     * @return
     */
    List<EvaluateLabel> findByConsult(String consult);
    /**
     * 获取某个医生的标签
     * @param doctor
     * @return
     */
    List<EvaluateLabel> findByDoctor(String doctor);
}

+ 14 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/deviece/PatientBloodSuggerDao.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.repository.deviece;
import com.yihu.wlyy.entity.device.PatientBloodSugger;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/11.
 */
public interface PatientBloodSuggerDao extends PagingAndSortingRepository<PatientBloodSugger,Long> {
//    按ID倒序查最近的有效默认时间段
    @Query(value = "select t.* from device.wlyy_patient_blood_sugger t where t.del = 1 order by t.id desc limit 0,1 ",nativeQuery = true)
    PatientBloodSugger findRecent();
}

+ 15 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/deviece/PatientHealthTimeDao.java

@ -0,0 +1,15 @@
package com.yihu.wlyy.repository.deviece;
import com.yihu.wlyy.entity.device.PatientHealthTime;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/11.
 */
public interface PatientHealthTimeDao extends PagingAndSortingRepository<PatientHealthTime, Long> {
    //    根据居民和设备sn码查询自定义的血糖时间段
    @Query(value = "select t.* from wlyy_patient_health_time t where t.del = 1 and t.user = ?1 and t.device_sn = ?2 ", nativeQuery = true)
    PatientHealthTime findByUserAndSN(String user, String deviceSN);
}

+ 12 - 6
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticlePatientDao.java

@ -11,12 +11,18 @@ import java.util.List;
public interface HealthEduArticlePatientDao extends PagingAndSortingRepository<HealthEduArticlePatient, Long>, JpaSpecificationExecutor<HealthEduArticlePatient> {
	// 更新为已读
	@Modifying
	@Query("update HealthEduArticlePatient a set a.read = 0 where a.patient = ?1 and a.article = ?2 ")
	int updateRead(String patient, String article);
	HealthEduArticlePatient findByArticle(String article);
    // 更新为已读
    @Modifying
    @Query("update HealthEduArticlePatient a set a.read = 0 where a.patient = ?1 and a.article = ?2 ")
    int updateRead(String patient, String article);
	List<HealthEduArticlePatient> findByArticleAndPatient(String article,String patient);
    HealthEduArticlePatient findByArticle(String article);
    List<HealthEduArticlePatient> findByArticleAndPatient(String article, String patient);
    // 当前用户的所有未读文章设置为已读
    @Modifying
    @Query("update HealthEduArticlePatient a set a.read = 0 where a.read = 1 and a.patient = ?1 ")
    int readAllArticle(String patient);
}

+ 11 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/feedback/AppealDao.java

@ -0,0 +1,11 @@
package com.yihu.wlyy.repository.feedback;
import com.yihu.wlyy.entity.feedback.Appeal;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/6.
 */
public interface AppealDao extends PagingAndSortingRepository<Appeal, Long>,JpaSpecificationExecutor<Appeal> {
}

+ 11 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/feedback/FeedbackDao.java

@ -0,0 +1,11 @@
package com.yihu.wlyy.repository.feedback;
import com.yihu.wlyy.entity.feedback.Feedback;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/6.
 */
public interface FeedbackDao extends PagingAndSortingRepository<Feedback, Long>,JpaSpecificationExecutor<Feedback> {
}

+ 33 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyRenewDao.java

@ -0,0 +1,33 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SignFamilyRenew;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface SignFamilyRenewDao extends PagingAndSortingRepository<SignFamilyRenew, Long>, JpaSpecificationExecutor<SignFamilyRenew> {
    @Query("select a from SignFamilyRenew a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
    SignFamilyRenew findByIdcard(String idcard);
    /**
     * 获取所有有效的签约信息(不包含-1 -2)
     *
     * @param patient
     * @return
     */
    @Query(value = "select a from SignFamilyRenew a where a.patient = ?1 and a.status <> -1 and a.status <> -2")
    List<SignFamilyRenew> findAllActiveSignByPatient(String patient);
    List<SignFamilyRenew> findByDoctorAndPatient(String doctor,String patient);
    List<SignFamilyRenew> findByDoctorHealthAndPatient(String doctorHealth,String patient);
}

+ 2 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java

@ -33,6 +33,7 @@ import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImUtill;
@ -111,6 +112,7 @@ public class DoctorInfoService extends BaseService {
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    /**
     * 获取医生的签约病人
     *

+ 5 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultService.java

@ -7,6 +7,7 @@ import java.util.List;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.SendPatientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
@ -55,6 +56,9 @@ public class ConsultService extends BaseService {
	@Autowired
	private SignFamilyDao signFamilyDao;
	@Autowired
	private PatientService patientService;
	/**
	 * 添加一条咨询记录
	 * @param patient 患者信息
@ -72,6 +76,7 @@ public class ConsultService extends BaseService {
		consult.setSymptoms(symptoms);
		consult.setImages(images);
		consult.setType(type);
		consult.setSignCode(patientService.getSignCodeByPatient(patient));
		return consultDao.save(consult);
	}

+ 17 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java

@ -26,6 +26,7 @@ import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
@ -46,6 +47,7 @@ import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import org.springside.modules.utils.Clock;
import java.text.SimpleDateFormat;
import java.util.*;
/**
@ -84,6 +86,9 @@ public class ConsultTeamService extends ConsultService {
    @Autowired
    private com.yihu.wlyy.service.common.account.DoctorService doctorService;
    @Autowired
    WeiXinAccessTokenUtils accessTokenUtils;
    /**
     * 查询患者是否还有未结束的三师咨询
     *
@ -758,6 +763,7 @@ public class ConsultTeamService extends ConsultService {
            if (patient.equals(key)) {
                continue;
            }
            //记录咨询的医生详情误删
            ConsultTeamDoctor cd = new ConsultTeamDoctor();
            cd.setConsult(consult.getCode());
            cd.setDel("1");
@ -1623,6 +1629,17 @@ public class ConsultTeamService extends ConsultService {
                endId = d.getCode();
                endName = d.getName();
            }
            if(consultTeam.getType()==2){
                Patient p = patientDao.findByCode(consultTeam.getPatient());
                String name = p.getName();
                String openId = p.getOpenid();
                JSONObject json = new JSONObject();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                json.put("keyword1", sdf.format(new Date()));
                json.put("toUser", p.getCode());
                json.put("first", name +",您好!您有1条咨询已结束,请及时对咨询医生进行满意度评价。待办事项:满意度评价");
                PushMsgTask.getInstance().putWxMsg(accessTokenUtils.getAccessToken(), 10, openId, p.getName(), json);
            }
        }
        JSONObject obj = ImUtill.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
        if (obj == null) {

+ 54 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/EvaluateLabelService.java

@ -0,0 +1,54 @@
package com.yihu.wlyy.service.app.consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.Evaluate;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import com.yihu.wlyy.repository.consult.EvaluateLabelDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.ClazzReflect;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
@Transactional
public class EvaluateLabelService extends BaseService {
	@Autowired
	EvaluateLabelDao evaluateLabelDao;
	@Autowired
	JdbcTemplate jdbcTemplate;
	public void save(List<EvaluateLabel> evaluateLabels){
		evaluateLabelDao.save(evaluateLabels);
	}
	public List<EvaluateLabel> findByDoctor(String doctor){
		return	this.evaluateLabelDao.findByDoctor(doctor);
	}
	public List<EvaluateLabel> findByConsult(String consult){
		return this.evaluateLabelDao.findByConsult(consult);
	}
	public 	List<Map<String, Object>> findDistinctLabelByLaDoctor(String doctor){
		String sql ="select content,count(content) as amount from wlyy_evaluate_label where doctor =? group by content";
		List<Object> params = new ArrayList<Object>();
		params.add(doctor);
		List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql,params.toArray());
		return  result;
	}
}

+ 130 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/EvaluateService.java

@ -0,0 +1,130 @@
package com.yihu.wlyy.service.app.consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.Evaluate;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import com.yihu.wlyy.repository.consult.EvaluateDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.ClazzReflect;
import com.yihu.wlyy.util.ImUtill;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Component
@Transactional
public class EvaluateService extends BaseService {
	@Autowired
	EvaluateDao evaluateDao;
	@Autowired
	ConsultTeamService consultTeamService;
	@Autowired
	EvaluateLabelService evaluateLabelService;
	public void save(List<Evaluate> evaluates){
		evaluateDao.save(evaluates);
	}
	public void saveByJson(String jsonData,String patient){
		JSONObject jsonObject = new JSONObject(jsonData);
		String consult = jsonObject.getString("consult");
		ConsultTeam consultTeam  = consultTeamService.findByCode(consult);
		if(consultTeam.getEvaluate()==1){
			throw new RuntimeException("已经评价不允许重复评价!");
		}
		JSONArray evaluateArray = jsonObject.getJSONArray("evaluate");
		JSONArray labelArray = jsonObject.getJSONArray("label");
		List<Evaluate> evaluateList = new ArrayList<>();
		List<EvaluateLabel> evaluateLabelList = new ArrayList<>();
		for(Object evaluateObj: evaluateArray){
			Evaluate evaluate = new Evaluate();
			JSONObject obj =(JSONObject) evaluateObj;
			ClazzReflect clazzReflect = new ClazzReflect();
			evaluate = (Evaluate)clazzReflect.formatToClazz(evaluate,obj);
			evaluate.setConsult(consult);
			evaluate.setPatient(patient);
			evaluateList.add(evaluate);
		}
		for(Object labelObj: labelArray){
			EvaluateLabel evaluateLabel = new EvaluateLabel();
			JSONObject obj =(JSONObject) labelObj;
			ClazzReflect clazzReflect = new ClazzReflect();
			evaluateLabel = (EvaluateLabel)clazzReflect.formatToClazz(evaluateLabel,obj);
			evaluateLabel.setConsult(consult);
			evaluateLabel.setPatient(patient);
			evaluateLabelList.add(evaluateLabel);
		}
		this.save(evaluateList);
		evaluateLabelService.save(evaluateLabelList);
		consultTeam.setEvaluate(1);
		consultTeam.setEvaluateTime(new Date());
		JSONObject topicObject = new JSONObject();
		topicObject.put("evaluate",1);
		topicObject.put("evaluate_time",new Date());
		ImUtill.updateTopics(consult,topicObject.toString());
		this.consultTeamService.save(consultTeam);
	}
	/**
	 * 查询某个咨询某种类型的评价
	 * @param consult
	 * @param type
	 * @return
	 */
	public List<Evaluate> getEvaluateByConsultAndType(String consult,int type){
		List<Evaluate> evaluates = evaluateDao.findByConsultAndType(consult,type);
		return 	evaluates;
	}
	/**
	 * 查询某个咨询的评价
	 * @param consult
	 * @return
	 */
	public List<Evaluate> getEvaluateByConsult(String consult){
		List<Evaluate> evaluates = evaluateDao.findByConsult(consult);
		return 	evaluates;
	}
	/**
	 * 获取某个医生的某种类型的评价
	 * @param doctor
	 * @param type
	 * @return
	 */
	public List<Evaluate> getEvaluateByDoctorAndType(String doctor,int type){
		List<Evaluate> evaluates = evaluateDao.findByDoctorAndType(doctor,type);
		return 	evaluates;
	}
	//public static void main(String args[]){
	//	JSONObject object = new JSONObject();
	//	JSONArray evaluateArray = new JSONArray();
	//	JSONArray labelArray = new JSONArray();
	//	JSONObject evaluateObject = new JSONObject();
	//	evaluateObject.put("doctor","要评价的医生code");
	//	evaluateObject.put("evaluateType","评价种类0、实名评价, 1、专业能力,2、服务态度,3、回复速度");
	//	evaluateObject.put("type","1、实名,2、匿名");
	//	evaluateObject.put("score","得分多少");
	//	evaluateArray.put(evaluateObject);
	//	JSONObject labelObject = new JSONObject();
	//	labelObject.put("doctor","要贴标签的医生code");
	//	labelObject.put("content","标签内容");
	//	labelArray.put(labelObject);
	//	object.put("consult","咨询的code");
	//	object.put("evaluate",evaluateArray);
	//	object.put("label",labelArray);
	//	System.out.print(object.toString());
	//}
}

+ 489 - 386
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java

@ -1,11 +1,15 @@
package com.yihu.wlyy.service.app.device;
import com.yihu.wlyy.entity.device.Device;
import com.yihu.wlyy.entity.device.PatientBloodSugger;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.device.PatientHealthTime;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.deviece.DeviceDao;
import com.yihu.wlyy.repository.deviece.PatientBloodSuggerDao;
import com.yihu.wlyy.repository.deviece.PatientHealthTimeDao;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamMemberDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
@ -37,393 +41,492 @@ import java.util.*;
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceService extends BaseService {
	private Clock clock = Clock.DEFAULT;
	@Autowired
	private DoctorDao doctorDao;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private DeviceDao deviceDao;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;
	@Autowired
	private AdminTeamService adminTeamService;
	private String url = SystemConf.getInstance().getYihuOpenPlatformUrl();
	private String appid = SystemConf.getInstance().getYihuOpenPlatformAppId();
	private String secret = SystemConf.getInstance().getYihuOpenPlatformSecret();
	private String registerDevice = "DeviceGateway/DeviceApi/registerDevice";//注册设备
	/**
	 * 保存患者设备
	 */
	public boolean saveDevice(PatientDevice patientDevice) throws Exception {
		synchronized (patientDevice.getDeviceSn()){
			//判断sn码是否被使用
			String sn = patientDevice.getDeviceSn();
			String type =  patientDevice.getCategoryCode();
			Long deviceId =  patientDevice.getDeviceId();
			String userType = patientDevice.getUserType();
			if(userType == null)
			{
				userType = "-1";
				patientDevice.setUserType("-1");
			}
			boolean needVerify = true;
			//修改操作
			if(patientDevice.getId()!=null)
			{
				PatientDevice deviceOld =  patientDeviceDao.findOne(patientDevice.getId());
				if(deviceOld!=null)
				{
					if(deviceOld.getDeviceSn().equals(sn))
					{
						needVerify = false;
					}
				}
				else{
					throw new Exception("不存在该条记录!");
				}
			}
			//校验sn码是否被使用
			if(needVerify) {
    private Clock clock = Clock.DEFAULT;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;
    @Autowired
    private AdminTeamService adminTeamService;
    @Autowired
    private PatientBloodSuggerDao patientBloodSuggerDao;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    private String url = SystemConf.getInstance().getYihuOpenPlatformUrl();
    private String appid = SystemConf.getInstance().getYihuOpenPlatformAppId();
    private String secret = SystemConf.getInstance().getYihuOpenPlatformSecret();
    private String registerDevice = "DeviceGateway/DeviceApi/registerDevice";//注册设备
    /**
     * 保存患者设备
     */
    public boolean saveDevice(PatientDevice patientDevice) throws Exception {
        synchronized (patientDevice.getDeviceSn()) {
            //判断sn码是否被使用
            String sn = patientDevice.getDeviceSn();
            String type = patientDevice.getCategoryCode();
            Long deviceId = patientDevice.getDeviceId();
            String userType = patientDevice.getUserType();
            if (userType == null) {
                userType = "-1";
                patientDevice.setUserType("-1");
            }
            boolean needVerify = true;
            //修改操作
            if (patientDevice.getId() != null) {
                PatientDevice deviceOld = patientDeviceDao.findOne(patientDevice.getId());
                if (deviceOld != null) {
                    if (deviceOld.getDeviceSn().equals(sn)) {
                        needVerify = false;
                    }
                } else {
                    throw new Exception("不存在该条记录!");
                }
            }
            //校验sn码是否被使用
            if (needVerify) {
//				PatientDevice device = patientDeviceDao.findByDeviceIdAndDeviceSnAndUserType(deviceId, sn, userType);
				PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
				if (device != null && !device.getId().equals(patientDevice.getId())) {
					throw new Exception("sn码" + sn + "已被使用!");
				}
			}
			patientDevice.setCzrq(clock.getCurrentDate());
			//当前用户的身份证
			Patient patient = patientDao.findByCode(patientDevice.getUser());
			patientDevice.setUserIdcard(patient.getIdcard());
			//注册设备
			Map<String, String> params = new HashMap<>();
			params.put("deviceSn", sn);
			//调用服务
			String response = HttpClientUtil.httpPost(url + registerDevice,HttpClientUtil.getSecretParams(params,appid,secret));
			System.out.println("注册设备="+response);
			JSONObject json = new JSONObject(response);
			String code = json.get("Code").toString();
			//10000注册成功 10001已注册 -10000参数不通过(没传参数) -10001设备不存在 -10002设备未出库
			if("10000".equals(code)||"10001".equals(code))
			{
				patientDeviceDao.save(patientDevice);
			}else{
				String message = json.get("Message").toString();
				throw new Exception(message);
			}
			return true;
		}
	}
	/**
	 * 注册设备
	 * @return
	 * @throws Exception
                PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
                if (device != null && !device.getId().equals(patientDevice.getId())) {
                    throw new Exception("sn码" + sn + "已被使用!");
                }
            }
            patientDevice.setCzrq(clock.getCurrentDate());
            //当前用户的身份证
            Patient patient = patientDao.findByCode(patientDevice.getUser());
            patientDevice.setUserIdcard(patient.getIdcard());
            //注册设备
            Map<String, String> params = new HashMap<>();
            params.put("deviceSn", sn);
            //调用服务
            String response = HttpClientUtil.httpPost(url + registerDevice, HttpClientUtil.getSecretParams(params, appid, secret));
            System.out.println("注册设备=" + response);
            JSONObject json = new JSONObject(response);
            String code = json.get("Code").toString();
            //10000注册成功 10001已注册 -10000参数不通过(没传参数) -10001设备不存在 -10002设备未出库
            if ("10000".equals(code) || "10001".equals(code)) {
                patientDeviceDao.save(patientDevice);
            } else {
                String message = json.get("Message").toString();
                throw new Exception(message);
            }
            return true;
        }
    }
    /**
     * 注册设备
     *
     * @return
     * @throws Exception
     */
	public String registerSnInit() throws Exception{
		String re = "";
		Iterable<PatientDevice> iterable = patientDeviceDao.findAll();
		if(iterable!=null){
			for (PatientDevice patientDevice:iterable){
				String deviceSn = patientDevice.getDeviceSn();
				Map<String, String> params = new HashMap<>();
				params.put("deviceSn", deviceSn);
				String response = HttpClientUtil.httpPost(url + registerDevice,HttpClientUtil.getSecretParams(params,appid,secret));
				System.out.println("注册设备="+response);
				JSONObject json = new JSONObject(response);
				String code = json.get("Code").toString();
				//10000注册成功 10001已注册 -10000参数不通过(没传参数) -10001设备不存在 -10002设备未出库
				if("10000".equals(code)||"10001".equals(code))
				{
				}else{
					String message = json.get("Message").toString();
					re+= deviceSn + message +";";
				}
			}
		}
		return re;
	}
	/**
	 * 单个注册
	 * @param deviceSn
	 * @return
	 * @throws Exception
    public String registerSnInit() throws Exception {
        String re = "";
        Iterable<PatientDevice> iterable = patientDeviceDao.findAll();
        if (iterable != null) {
            for (PatientDevice patientDevice : iterable) {
                String deviceSn = patientDevice.getDeviceSn();
                Map<String, String> params = new HashMap<>();
                params.put("deviceSn", deviceSn);
                String response = HttpClientUtil.httpPost(url + registerDevice, HttpClientUtil.getSecretParams(params, appid, secret));
                System.out.println("注册设备=" + response);
                JSONObject json = new JSONObject(response);
                String code = json.get("Code").toString();
                //10000注册成功 10001已注册 -10000参数不通过(没传参数) -10001设备不存在 -10002设备未出库
                if ("10000".equals(code) || "10001".equals(code)) {
                } else {
                    String message = json.get("Message").toString();
                    re += deviceSn + message + ";";
                }
            }
        }
        return re;
    }
    /**
     * 单个注册
     *
     * @param deviceSn
     * @return
     * @throws Exception
     */
	public String registerSn(String deviceSn) throws Exception{
		Map<String, String> params = new HashMap<>();
		params.put("deviceSn", deviceSn);
		String response = HttpClientUtil.httpPost(url + registerDevice,HttpClientUtil.getSecretParams(params,appid,secret));
		return response;
	}
	public void deleteDevices(String deviceSn,String type,String uuid){
		List<PatientDevice> patientDevices = 	patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn,type);
		if(patientDevices==null||patientDevices.size()==0){
			throw  new RuntimeException("设备未被绑定!");
		}
		for(PatientDevice patientDevice: patientDevices){
			patientDeviceDao.delete(patientDevice);
		}
	}
	/**
	 * 删除患者设备
	 */
	public List<JSONObject> deleteDevice(String id,String uuid) {
		PatientDevice device = patientDeviceDao.findOne(Long.valueOf(id));
		patientDeviceDao.delete(device);
		List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(),device.getCategoryCode());
		List<JSONObject> objects = new ArrayList<>();
		for(PatientDevice patientDevice:patientDevices){
			JSONObject object = new JSONObject(patientDevice);
			Patient patient = patientDao.findByCode(patientDevice.getUser());
			if(patient!=null){
				object.put("userName",patient.getName());
			}
			objects.add(object);
		}
		return objects;
	}
	/**
	 * 患者设备列表接口(分页)
	 */
	public Page<PatientDevice> findByPatient(String patientCode, long id, int pageSize) {
		if (id < 0) {
			id = 0;
		}
		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		filters.put("patient", new SearchFilter("user", Operator.EQ, patientCode));
		//filters.put("del", new SearchFilter("del", Operator.EQ, 0));
		if(id > 0){
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		Specification<PatientDevice> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientDevice.class);
		return patientDeviceDao.findAll(spec, pageRequest);
	}
	/**
	 * 患者设备列表接口--医生端
	 */
	public List<Map<String,Object>> findByDoctor(String patientCode,String doctorCode, int page, int pagesize) {
		List<Map<String,Object>> re = new ArrayList<>();
		if (page <= 0) {
			page = 1;
		}
		if (pagesize <= 0) {
			pagesize = 10;
		}
		//boolean bo = false;
		////判断该医生是否属于患者的签约行政团队
		//List<AdminTeamMember> adminTeamMembers = doctorAdminTeamMemberDao.findByAdminTeam(patientCode,doctorCode);
		//if(adminTeamMembers!=null && adminTeamMembers.size()>0)
		//{
		//	bo = true;
		//}
		PageRequest pageRequest = new PageRequest(page-1, pagesize);
		List<PatientDevice> list = new ArrayList<>();
		//if(bo) //签约医生查看所有设备
		//{
		//	list = patientDeviceDao.findByUser(patientCode,pageRequest);
		//}
		//else{
		//	list = patientDeviceDao.findByUserAndDoctor(patientCode, doctorCode,pageRequest);
		//}
		list = patientDeviceDao.findByUser(patientCode,pageRequest);
		if(list!=null)
		{
			//获取设备路径,医生姓名
			List<Device> deviceList = deviceDao.findAll();
			Doctor self = doctorDao.findByCode(doctorCode);
			for(PatientDevice item :list)
			{
				Map<String,Object>  map = new HashMap<>();
				if(StringUtils.isNotBlank(item.getDoctor())){
					if(StringUtils.equals(item.getDoctor(),doctorCode)){
						map.put("role",1);//可解绑自己绑定的
					}else{
						List<AdminTeam> adminTeams = adminTeamService.findDoctorsTeams(item.getDoctor(),doctorCode);
						if(adminTeams!=null&&adminTeams.size()>0){
							map.put("role",1);//同行政团队可解绑
						}else{
							map.put("role",0);//不同行政团队不可解绑
						}
					}
				}else{
					map.put("role",0);//患者自己绑定无法解绑
				}
				map.put("id",item.getId()) ;
				map.put("deviceId",item.getDeviceId());
				map.put("deviceSn",item.getDeviceSn());
				map.put("user",item.getUser());
				map.put("categoryCode",item.getCategoryCode());
				map.put("userType",item.getUserType());
				map.put("userIdcard",item.getUserIdcard());
				map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
				String deviceDoctor = item.getDoctor();
				if(deviceDoctor == null)
				{
					map.put("doctor","");
					map.put("doctorName","");
				}
				else{
					map.put("doctor",deviceDoctor);
					if(deviceDoctor.equals(doctorCode))
					{
						map.put("doctorName",self.getName());
					}
					else{
						Doctor doctor = doctorDao.findByCode(deviceDoctor);
						if(doctor!=null)
						{
							map.put("doctorName",doctor.getName());
						}
						else{
							map.put("doctorName","");
						}
					}
				}
				//获取设备路径
				for(Device de : deviceList)
				{
					if(de.getId().equals(item.getDeviceId()))
					{
						map.put("deviceName",de.getName());
						map.put("devicePhoto",de.getPhoto());
						map.put("deviceBrands",de.getBrands());
						break;
					}
				}
				re.add(map);
			}
		}
		re.sort(new Comparator<Map<String, Object>>() {
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0){
					return -1;
				}
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0){
					return 1;
				}
				return 0;
			}
		});
		return re;
	}
	/**
	 * 查询患者已拥有的设备
	 * @param patient
	 * @return
	 */
	public Iterator<PatientDevice> findPatientHave(String patient) {
		return patientDeviceDao.findByUser(patient).iterator();
	}
	/**
	 * 获取患者设备信息
	 **/
	public PatientDevice findById(String id) {
		return patientDeviceDao.findOne(Long.valueOf(id));
	}
	/**
	 * 通过sn码获取设备绑定情况
	 **/
	public List<Map<String,String>> getDeviceUser(String user,String deviceSn,String type) throws Exception {
		List<Map<String,String>> re = new ArrayList<>();
		List<PatientDevice> list =patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn,type);
		if(list!=null)
		{
			for(PatientDevice item:list)
			{
				Map<String,String> map = new HashMap<> ();
				map.put("type",item.getUserType());
				String code = item.getUser();
				if(code.equals(user))
				{
					map.put("others","0");
				}
				else{
					map.put("others","1");
				}
				//获取姓名
				Patient patient = patientDao.findByCode(code);
				if(patient!=null)
				{
					map.put("name",patient.getName());
				}
				else{
					map.put("name",code);
				}
				re.add(map);
			}
		}
		return re;
	}
	public JSONArray getDeviceByDeviceSn(String deviceSn,String type){
		List<PatientDevice> list =patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn,type);
		JSONArray objects = new JSONArray();
		for(PatientDevice patientDevice:list){
			JSONObject object = new JSONObject(patientDevice);
			Patient patient = patientDao.findByCode(patientDevice.getUser());
			if(patient!=null){
				object.put("userName",patient.getName());
			}
			objects.put(object);
		}
		return objects;
	}
    public String registerSn(String deviceSn) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("deviceSn", deviceSn);
        String response = HttpClientUtil.httpPost(url + registerDevice, HttpClientUtil.getSecretParams(params, appid, secret));
        return response;
    }
    public void deleteDevices(String deviceSn, String type, String uuid) {
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (patientDevices == null || patientDevices.size() == 0) {
            throw new RuntimeException("设备未被绑定!");
        }
        for (PatientDevice patientDevice : patientDevices) {
            patientDeviceDao.delete(patientDevice);
        }
    }
    /**
     * 删除患者设备
     */
    public List<JSONObject> deleteDevice(String id, String uuid) {
        PatientDevice device = patientDeviceDao.findOne(Long.valueOf(id));
        patientDeviceDao.delete(device);
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(), device.getCategoryCode());
        List<JSONObject> objects = new ArrayList<>();
        for (PatientDevice patientDevice : patientDevices) {
            JSONObject object = new JSONObject(patientDevice);
            Patient patient = patientDao.findByCode(patientDevice.getUser());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.add(object);
        }
        return objects;
    }
    /**
     * 患者设备列表接口(分页)
     */
    public Page<PatientDevice> findByPatient(String patientCode, long id, int pageSize) {
        if (id < 0) {
            id = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("patient", new SearchFilter("user", Operator.EQ, patientCode));
        //filters.put("del", new SearchFilter("del", Operator.EQ, 0));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<PatientDevice> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientDevice.class);
        return patientDeviceDao.findAll(spec, pageRequest);
    }
    /**
     * 患者设备列表接口--医生端
     */
    public List<Map<String, Object>> findByDoctor(String patientCode, String doctorCode, int page, int pagesize) {
        List<Map<String, Object>> re = new ArrayList<>();
        if (page <= 0) {
            page = 1;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        //boolean bo = false;
        ////判断该医生是否属于患者的签约行政团队
        //List<AdminTeamMember> adminTeamMembers = doctorAdminTeamMemberDao.findByAdminTeam(patientCode,doctorCode);
        //if(adminTeamMembers!=null && adminTeamMembers.size()>0)
        //{
        //	bo = true;
        //}
        PageRequest pageRequest = new PageRequest(page - 1, pagesize);
        List<PatientDevice> list = new ArrayList<>();
        //if(bo) //签约医生查看所有设备
        //{
        //	list = patientDeviceDao.findByUser(patientCode,pageRequest);
        //}
        //else{
        //	list = patientDeviceDao.findByUserAndDoctor(patientCode, doctorCode,pageRequest);
        //}
        list = patientDeviceDao.findByUser(patientCode, pageRequest);
        if (list != null) {
            //获取设备路径,医生姓名
            List<Device> deviceList = deviceDao.findAll();
            Doctor self = doctorDao.findByCode(doctorCode);
            for (PatientDevice item : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(item.getDoctor())) {
                    if (StringUtils.equals(item.getDoctor(), doctorCode)) {
                        map.put("role", 1);//可解绑自己绑定的
                    } else {
                        List<AdminTeam> adminTeams = adminTeamService.findDoctorsTeams(item.getDoctor(), doctorCode);
                        if (adminTeams != null && adminTeams.size() > 0) {
                            map.put("role", 1);//同行政团队可解绑
                        } else {
                            map.put("role", 0);//不同行政团队不可解绑
                        }
                    }
                } else {
                    map.put("role", 0);//患者自己绑定无法解绑
                }
                map.put("id", item.getId());
                map.put("deviceId", item.getDeviceId());
                map.put("deviceSn", item.getDeviceSn());
                map.put("user", item.getUser());
                map.put("categoryCode", item.getCategoryCode());
                map.put("userType", item.getUserType());
                map.put("userIdcard", item.getUserIdcard());
                map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
                String deviceDoctor = item.getDoctor();
                if (deviceDoctor == null) {
                    map.put("doctor", "");
                    map.put("doctorName", "");
                } else {
                    map.put("doctor", deviceDoctor);
                    if (deviceDoctor.equals(doctorCode)) {
                        map.put("doctorName", self.getName());
                    } else {
                        Doctor doctor = doctorDao.findByCode(deviceDoctor);
                        if (doctor != null) {
                            map.put("doctorName", doctor.getName());
                        } else {
                            map.put("doctorName", "");
                        }
                    }
                }
                //获取设备路径
                for (Device de : deviceList) {
                    if (de.getId().equals(item.getDeviceId())) {
                        map.put("deviceName", de.getName());
                        map.put("devicePhoto", de.getPhoto());
                        map.put("deviceBrands", de.getBrands());
                        break;
                    }
                }
                re.add(map);
            }
        }
        re.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0) {
                    return -1;
                }
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0) {
                    return 1;
                }
                return 0;
            }
        });
        return re;
    }
    /**
     * 查询患者已拥有的设备
     *
     * @param patient
     * @return
     */
    public Iterator<PatientDevice> findPatientHave(String patient) {
        return patientDeviceDao.findByUser(patient).iterator();
    }
    /**
     * 获取患者设备信息
     **/
    public PatientDevice findById(String id) {
        return patientDeviceDao.findOne(Long.valueOf(id));
    }
    /**
     * 通过sn码获取设备绑定情况
     **/
    public List<Map<String, String>> getDeviceUser(String user, String deviceSn, String type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        List<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (list != null) {
            for (PatientDevice item : list) {
                Map<String, String> map = new HashMap<>();
                map.put("type", item.getUserType());
                String code = item.getUser();
                if (code.equals(user)) {
                    map.put("others", "0");
                } else {
                    map.put("others", "1");
                }
                //获取姓名
                Patient patient = patientDao.findByCode(code);
                if (patient != null) {
                    map.put("name", patient.getName());
                } else {
                    map.put("name", code);
                }
                re.add(map);
            }
        }
        return re;
    }
    public JSONArray getDeviceByDeviceSn(String deviceSn, String type) {
        List<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        JSONArray objects = new JSONArray();
        for (PatientDevice patientDevice : list) {
            JSONObject object = new JSONObject(patientDevice);
            Patient patient = patientDao.findByCode(patientDevice.getUser());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.put(object);
        }
        return objects;
    }
    /**
     * 获取血糖仪各个时间段(无参为默认时间段)
     *
     * @param user
     * @param deviceSN
     * @return
     */
    public Map getBloodSuggerTime(String user, String deviceSN) {
        Map map = new HashMap();
        PatientBloodSugger bloodSugger = null;
        PatientHealthTime patientHealthTime = null;
        if (StringUtils.isEmpty(user) && StringUtils.isEmpty(deviceSN)) {
            bloodSugger = patientBloodSuggerDao.findRecent();
        } else {
            patientHealthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
        }
        String fastingStart = null;
        String fastingEnd = null;
        String afterBreakFastStart = null;
        String afterBreakFastEnd = null;
        String beforeLunchStart = null;
        String beforeLunchEnd = null;
        String afterLunchStart = null;
        String afterLunchEnd = null;
        String beforeDinnerStart = null;
        String beforeDinnerEnd = null;
        String afterDinnerStart = null;
        String afterDinnerEnd = null;
        String beforeSleepStart = null;
        String beforeSleepEnd = null;
        if (patientHealthTime == null) {
            fastingStart = bloodSugger.getFastingStart();
            fastingEnd = bloodSugger.getFastingEnd();
            afterBreakFastStart = bloodSugger.getAfterBreakfastStart();
            afterBreakFastEnd = bloodSugger.getAfterBreakfastEnd();
            beforeLunchStart = bloodSugger.getBeforeLunchStart();
            beforeLunchEnd = bloodSugger.getBeforeLunchEnd();
            afterLunchStart = bloodSugger.getAfterLunchStart();
            afterLunchEnd = bloodSugger.getAfterLunchEnd();
            beforeDinnerStart = bloodSugger.getBeforeDinnerStart();
            beforeDinnerEnd = bloodSugger.getBeforeDinnerEnd();
            afterDinnerStart = bloodSugger.getAfterDinnerStart();
            afterDinnerEnd = bloodSugger.getAfterDinnerEnd();
            beforeSleepStart = bloodSugger.getBeforeSleepStart();
            beforeSleepEnd = bloodSugger.getBeforeSleepEnd();
        } else {
            fastingStart = patientHealthTime.getFastingStart();
            fastingEnd = patientHealthTime.getFastingEnd();
            afterBreakFastStart = patientHealthTime.getAfterBreakfastStart();
            afterBreakFastEnd = patientHealthTime.getAfterBreakfastEnd();
            beforeLunchStart = patientHealthTime.getBeforeLunchStart();
            beforeLunchEnd = patientHealthTime.getBeforeLunchEnd();
            afterLunchStart = patientHealthTime.getAfterLunchStart();
            afterLunchEnd = patientHealthTime.getAfterLunchEnd();
            beforeDinnerStart = patientHealthTime.getBeforeDinnerStart();
            beforeDinnerEnd = patientHealthTime.getBeforeDinnerEnd();
            afterDinnerStart = patientHealthTime.getAfterDinnerStart();
            afterDinnerEnd = patientHealthTime.getAfterDinnerEnd();
            beforeSleepStart = patientHealthTime.getBeforeSleepStart();
            beforeSleepEnd = patientHealthTime.getBeforeSleepEnd();
        }
        map.put("fasting", fastingStart + " - " + fastingEnd);
        map.put("afterBreakFast", afterBreakFastStart + " - " + afterBreakFastEnd);
        map.put("beforeLunch", beforeLunchStart + " - " + beforeLunchEnd);
        map.put("afterLunch", afterLunchStart + " - " + afterLunchEnd);
        map.put("beforeDinner", beforeDinnerStart + " - " + beforeDinnerEnd);
        map.put("afterDinner", afterDinnerStart + " - " + afterDinnerEnd);
        map.put("beforeSleep", beforeSleepStart + " - " + beforeSleepEnd);
        return map;
    }
    /**
     * 用户自定义血糖仪各个时间段
     *
     * @param fastingStart
     * @param fastingEnd
     * @param afterBreakfastStart
     * @param afterBreakfastEnd
     * @param beforeLunchStart
     * @param beforeLunchEnd
     * @param afterLunchStart
     * @param afterLunchEnd
     * @param beforeDinnerStart
     * @param beforeDinnerEnd
     * @param afterDinnerStart
     * @param afterDinnerEnd
     * @param beforeSleepStart
     * @param beforeSleepEnd
     */
    public void setBloodTime(String user, String deviceSN, String fastingStart, String fastingEnd, String afterBreakfastStart, String afterBreakfastEnd, String beforeLunchStart, String beforeLunchEnd,
                             String afterLunchStart, String afterLunchEnd, String beforeDinnerStart, String beforeDinnerEnd, String afterDinnerStart, String afterDinnerEnd,
                             String beforeSleepStart, String beforeSleepEnd) throws  Exception{
        PatientHealthTime patientHealthTime = new PatientHealthTime();
        patientHealthTime.setUser(user);
        patientHealthTime.setDeviceSN(deviceSN);
        patientHealthTime.setFastingStart(fastingStart);
        patientHealthTime.setFastingEnd(fastingEnd);
        patientHealthTime.setAfterBreakfastStart(afterBreakfastStart);
        patientHealthTime.setAfterBreakfastEnd(afterBreakfastEnd);
        patientHealthTime.setBeforeLunchStart(beforeLunchStart);
        patientHealthTime.setBeforeLunchEnd(beforeLunchEnd);
        patientHealthTime.setAfterLunchStart(afterLunchStart);
        patientHealthTime.setAfterLunchEnd(afterLunchEnd);
        patientHealthTime.setBeforeDinnerStart(beforeDinnerStart);
        patientHealthTime.setBeforeDinnerEnd(beforeDinnerEnd);
        patientHealthTime.setAfterDinnerStart(afterDinnerStart);
        patientHealthTime.setAfterDinnerEnd(afterDinnerEnd);
        patientHealthTime.setBeforeSleepStart(beforeSleepStart);
        patientHealthTime.setBeforeSleepEnd(beforeSleepEnd);
        patientHealthTime.setDel(1);
        patientHealthTime.setCzrq(new Date());
        patientHealthTimeDao.save(patientHealthTime);
    }
}

+ 54 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/feedback/AppealService.java

@ -0,0 +1,54 @@
package com.yihu.wlyy.service.app.feedback;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.feedback.Appeal;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.feedback.AppealDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Reece on 2017/5/6.
 */
@Service
@Transactional
public class AppealService extends BaseService {
    @Autowired
    private AppealDao appealDao;
    @Autowired
    private PatientService patientService;
    @Autowired
    private DoctorService doctorService;
    public void saveAppeal(String creater,String description,int type,String images,String phone,int identity) throws Exception{
        Appeal appeal = new Appeal();
        appeal.setCode(getCode());
        appeal.setCreater(creater);
        appeal.setDescription(description);
        appeal.setType(type);
        appeal.setImages(images);
        appeal.setPhone(phone);
        appeal.setStatus(0);
        appeal.setIdentity(identity);
        appeal.setDel(1);
        //通过creater获取创建人名字
        String name ="";
        if(creater!=null&&!"".equals(creater)){
            if(identity==1){//说明是患者
                Patient patient = patientService.findByCode(creater);
                name = patient.getName();
            }else{//说明是医生
                Doctor doctor = doctorService.findDoctorByCode(creater);
                name = doctor.getName();
            }
        }
        appeal.setCreaterName(name);
        appealDao.save(appeal);
    }
}

+ 53 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/feedback/FeedbackService.java

@ -0,0 +1,53 @@
package com.yihu.wlyy.service.app.feedback;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.feedback.Feedback;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.feedback.FeedbackDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Reece on 2017/5/6.
 */
@Service
@Transactional
public class FeedbackService extends BaseService {
    @Autowired
    private FeedbackDao feedbackDao;
    @Autowired
    private PatientService patientService;
    @Autowired
    private DoctorService doctorService;
    public void saveFeedback(String creater,int identity,String description,int type,String images,String contact) throws Exception{
        Feedback feedback = new Feedback();
        feedback.setCode(getCode());
        feedback.setCreater(creater);
        feedback.setIdentity(identity);
        feedback.setDescription(description);
        feedback.setType(type);
        feedback.setImages(images);
        feedback.setContact(contact);
        feedback.setStatus(0);
        feedback.setDel(1);
        //通过creater获取创建人名字
        String name ="";
        if(identity==1){//说明是患者
            Patient patient = patientService.findByCode(creater);
            name = patient.getName();
        }else{//说明是医生
            Doctor doctor = doctorService.findDoctorByCode(creater);
            name = doctor.getName();
        }
        feedback.setCreaterName(name);
        feedbackDao.save(feedback);
    }
}

+ 10 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/followup/FollowUpService.java

@ -17,6 +17,7 @@ import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.task.FollowupUploadTask;
import com.yihu.wlyy.task.PushMsgTask;
@ -77,6 +78,9 @@ public class FollowUpService extends BaseService {
    @Autowired
    SystemDictService dictService;
    @Autowired
    private PatientService patientService;
    /**
     * 转译随访信息
     */
@ -309,6 +313,9 @@ public class FollowUpService extends BaseService {
                followup.setCreater(doctorCode);
                followup.setAdminTeamCode(signFamily.getAdminTeamId());
                followup.setSignType(2);
                //新增签约保存CODE
                followup.setSignCode(patientService.getSignCodeByPatient(patientCode));
                followupPlan.add(followup);
            }
@ -399,6 +406,9 @@ public class FollowUpService extends BaseService {
        followup.setCreater(doctorCode);
        followup.setAdminTeamCode(signFamily.getAdminTeamId());
        followup.setSignType(2);
        //保存质询code
        followup.setSignCode(patientService.getSignCodeByPatient(patientCode));
        followupDao.save(followup);
        re = String.valueOf(followup.getId());
        return re;

+ 8 - 4
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleDoctorService.java

@ -92,16 +92,17 @@ public class HealthEduArticleDoctorService extends BaseService {
	 * @param pagesize 分页大小
	 * @return
	 */
	public List<Map<String, Object>> list(int page, int pagesize,String filter,String doctor,String patient) {
	public List<Map<String, Object>> list(int page, int pagesize,String filter,String doctor,String patient,Integer wheaType) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		if(page<0){
			page = 0;
		if(page<=0){
			page = 1;
		}
		page = page-1;
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select a.id,a.article,a.doctor,a.title,a.url,a.czrq,b.summary content,b.keyword");
		sql.append("select a.id,a.article,a.doctor,a.title,a.url,a.czrq,b.summary content,b.keyword,b.whea_type");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 1) as readAmount");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 2) as collectionAmount");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 3) as repeatAmount");
@ -112,6 +113,9 @@ public class HealthEduArticleDoctorService extends BaseService {
		}
		sql.append(" from wlyy_health_edu_article_doctor a left join wlyy_health_edu_article b on a.article = b.code ");//内联取文章内容
		String where = " where a.doctor = ?";
		if(wheaType>-1){
			where += " and  whea_type ="+wheaType;
		}
		params.add(doctor);
		if(StringUtils.isNotBlank(filter)){
			//记录搜索记录

+ 88 - 3
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticlePatientService.java

@ -5,6 +5,7 @@ import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.repository.education.HealthEduArticleDao;
import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
import com.yihu.wlyy.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@ -95,7 +96,7 @@ public class HealthEduArticlePatientService extends BaseService {
     * @param pagesize 分页大小
     * @return
     */
    public List<HealthEduArticlePatient> findByPatient(String patient, long id, int pagesize) {
    public List<HealthEduArticlePatient> findByPatient(String patient,int wheaType, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
@ -110,6 +111,7 @@ public class HealthEduArticlePatientService extends BaseService {
                "    ,b.summary as content" +
                "    ,a.is_read as 'read'" +
                "    ,a.czrq" +
                "    ,a.attached_content" +
                " from" +
                "     wlyy_health_edu_article_patient a" +
                "     , wlyy_health_edu_article b" +
@ -117,12 +119,95 @@ public class HealthEduArticlePatientService extends BaseService {
                "      a.article = b.code" +
                " and a.patient = ?" +
                (id > 0 ? " and a.id < ? " : "") +
                (wheaType > 0 ? " and a.wheaType = ? " : "") +
                " order by a.id desc limit 0," + pagesize;
        List<HealthEduArticlePatient> list = jdbcTemplate.query(sql,
                id > 0 ? new Object[]{patient,id} : new Object[]{patient}, new BeanPropertyRowMapper(HealthEduArticlePatient.class));
        Object params[] = null;
        if(wheaType>-1&&id>0){
            params = new Object[]{patient,id,wheaType};
        }else if(wheaType>-1&&id<0){
            params = new Object[]{patient,wheaType};
        }
        else if(wheaType<0&&id>0){
            params = new Object[]{patient,id};
        }else{
            params = new Object[]{patient};
        }
        List<HealthEduArticlePatient> list = jdbcTemplate.query(sql,params, new BeanPropertyRowMapper(HealthEduArticlePatient.class));
        return list;
    }
    /**
     * 查询患者文章
     *
     * @param doctor  医生标识
     * @param  page 第几页
     * @param pagesize 分页大小
     * @return
     */
    public List<Map<String,Object>> findByDoctor(String doctor,int page, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if(page<=0){
            page = 1 ;
        }
        int start = (page-1) * pagesize;
        String sql ="select a.article,b.title,b.summary,a.attached_content, a.czrq,count(a.patient) as amount,GROUP_CONCAT(p.name) as  patients,a.batch_no from "+
        " wlyy_health_edu_article_patient a, "+
        " wlyy_health_edu_article b,"+
        " wlyy_patient p"+
        " where"+
        " a.article = b.code"+
        " and a.patient = p.code"+
        " and a.doctor =? "+
        " group BY a.batch_no,a.article,a.attached_content,b.summary,a.doctor order by a.czrq desc  limit ?,? ";
        Object params[] = new Object[]{doctor,start,pagesize};
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
        return list;
    }
    /**
     * 查询批次号相关的文章及成员信息
     * @param doctor
     * @param article
     * @param batchNo
     * @return
     */
    public List<Map<String,Object>> findByBatchNo(String doctor,String article, String  batchNo) {
        String sql ="select a.article,b.title,b.content,a.attached_content,b.url, a.czrq as send_time,b.czrq,a.batch_no,sum(a.is_read) as no_read from "+
                " wlyy_health_edu_article_patient a, "+
                " wlyy_health_edu_article b,"+
                " wlyy_patient p"+
                " where"+
                " a.article = b.code"+
                " and a.patient = p.code"+
                " and a.doctor =? "+
                " and a.article =? "+
                (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":"and a.batch_no is null ")+
                " group BY a.batch_no,a.article,b.content,b.summary,a.doctor,b.title";
        Object params[] =  (StringUtils.isNotBlank(batchNo)?new Object[]{doctor,article,batchNo}:new Object[]{doctor,article});
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
        for(Map<String,Object> dataMap :list){
            String patientListSql ="select a.patient,p.name,a.is_read "+
            " from wlyy_health_edu_article_patient a,wlyy_health_edu_article b,wlyy_patient p"+
            " where "+
            " a.article = b.code " +
            " and a.doctor=? and  a.article =?"+
            (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":" and a.batch_no is null ")+
            " and a.patient = p.code " +
            " group BY a.batch_no,a.article,b.content,a.attached_content,a.patient,b.title";
            List<Map<String,Object>> patientList = jdbcTemplate.queryForList(patientListSql,params);
            dataMap.put("patients",patientList);
            dataMap.put("read_amount",patientList.size()-Integer.parseInt(dataMap.get("no_read").toString()));
            dataMap.put("amount",patientList.size());
        }
        return list;
    }
    /**
     * 文章更新为已读
     *

+ 23 - 9
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleService.java

@ -164,13 +164,14 @@ public class HealthEduArticleService extends BaseService {
     * @param pagesize 分页大小
     * @return 列表
     */
    public List<Map<String, Object>> findAll(int page, int pagesize, String filter, String doctor, String patient) {
    public List<Map<String, Object>> findAll(int page, int pagesize, String filter, String doctor, String patient,int wheaType) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        if (page < 0) {
            page = 0;
        if (page <=0) {
            page = 1;
        }
        page = page-1;
        List<Object> params = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.summary content,a.keyword");
@ -184,22 +185,23 @@ public class HealthEduArticleService extends BaseService {
            params.add(doctor);
            params.add(patient);
        }
        sql.append(" from wlyy_health_edu_article a ");//内联取文章内容
        String where = " ";
        sql.append(" from wlyy_health_edu_article a  ");//内联取文章内容
        String where = " where 1=1 ";
        if (StringUtils.isNotBlank(filter)) {
            //记录搜索记录
            healthEduArticleLabelService.saveOrUpdateLabel(filter, doctor);
            filter = "%" + filter + "%";
            where += " where ( a.title like ? or a.keyword like ? )";
            where += " and  ( a.title like ? or a.keyword like ? )";
            params.add(filter);
            params.add(filter);
        }
        if(wheaType>=0){
            where += " and  ( a.whea_type = ? )";
            params.add(wheaType);
        }
        int start = page * pagesize;
        String pageInfo = " limit " + start + "," + pagesize;
        String orderBy = " order by a.czrq,a.id desc";
        sql.append(where).append(orderBy).append(pageInfo);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        return result;
@ -226,6 +228,8 @@ public class HealthEduArticleService extends BaseService {
                "    ,d.name" +
                "    ,d.photo" +
                "    ,a.admin_team_code" +
                "    ,a.is_read" +
                "    ,a.attached_content" +
                "  from" +
                "    wlyy_health_edu_article_patient a" +
                "    ,wlyy_health_edu_article b" +
@ -252,6 +256,16 @@ public class HealthEduArticleService extends BaseService {
        return healthEduArticlePatientDao.updateRead(patient, article);
    }
    /**
     * 对当前用户的所有未读文章设置为已读
     *
     * @param patient
     * @return
     */
    public int readAllArticle(String patient) {
        return healthEduArticlePatientDao.readAllArticle(patient);
    }
    /**
     * 发送文章列表
     *

+ 5 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientHealthGuidanceDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
@ -46,6 +47,8 @@ public class PatientHealthGuidanceService extends BaseService {
	JdbcTemplate jdbcTemplate;
	@Autowired
	WeiXinOpenIdUtils weiXinOpenIdUtils;
	@Autowired
	private PatientService patientService;
	public JSONObject findById(Long id){
		PatientHealthGuidance guidance = patientHealthGuidanceDao.findOne(id);
@ -111,6 +114,8 @@ public class PatientHealthGuidanceService extends BaseService {
		guidance.setDel("1");
		guidance.setAdminTeamCode(signFamily.getAdminTeamId());
		guidance.setSignType(2);
		//保存签约CODE
		guidance.setSignCode(patientService.getSignCodeByPatient(patient.getCode()));
		guidance = patientHealthGuidanceDao.save(guidance);
		String openId = null;

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

@ -1,5 +1,6 @@
package com.yihu.wlyy.service.app.health;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.message.Message;
@ -39,6 +40,7 @@ import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import org.springside.modules.utils.Clock;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
@ -69,10 +71,96 @@ public class PatientHealthIndexService extends BaseService {
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    //更改接口(包括手动记录的修改和所有的删除)
    public void modify(long id, String value1, String value2, String value3, String value4) {
        Date time = new Date();
        String sql = "";
//            字段值均为空为删除
        if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2) && StringUtils.isEmpty(value3) && StringUtils.isEmpty(value4)) {
            sql = " update device.wlyy_patient_health_index a set a.del = 0 where a.id =? ";
            jdbcTemplate.update(sql, id);
        }
        sql = " update device.wlyy_patient_health_index a set ";
        if (StringUtils.isNotEmpty(value1)) {
            sql += " a.value1 = " +value1+" , ";
        }
        if (StringUtils.isNotEmpty(value2)) {
            sql +=  " a.value2 = " +value2+" , ";
        }
        if (StringUtils.isNotEmpty(value3)) {
            sql +=  " a.value3 = " +value3+" , ";
        }
        if (StringUtils.isNotEmpty(value4)) {
            sql += " a.value4 = " +value4+", ";
        }
         sql += " a.czrq = ?  where a.device_sn is null and a.id =? ";
        jdbcTemplate.update(sql, time, id);
    }
    /**
     * 获取居民最新各类健康记录
     */
    public Map findDataByPatient(String patient, int type) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sql = "SELECT " +
                " a.* " +
                " FROM " +
                "  device.wlyy_patient_health_index a " +
                " WHERE " +
                " a. USER = ? " +
                " AND a.type = ? " +
                " AND a.del = 1 " +
                " ORDER BY " +
                " a.record_date DESC " +
                "LIMIT 0,1 ";
        List<Map<String, Object>> devicePatient = jdbcTemplate.queryForList(sql, patient, type);
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> device : devicePatient) {
            String time = device.get("record_date") == null ? null : device.get("record_date").toString();
            String deviceSN = device.get("device_sn") == null ? "0" : "1";
            String value1 = device.get("value1") == null ? null : device.get("value1").toString();
            String value2 = device.get("value2") == null ? null : device.get("value2").toString();
            String value3 = device.get("value3") == null ? null : device.get("value3").toString();
            String value4 = device.get("value4") == null ? null : device.get("value4").toString();
            String value5 = device.get("value5") == null ? null : device.get("value5").toString();
            String value6 = device.get("value6") == null ? null : device.get("value6").toString();
            String value7 = device.get("value7") == null ? null : device.get("value7").toString();
            map.put("isDevice", deviceSN);
            if (StringUtils.isNotEmpty(time)) {
                Date date = sdf.parse(time);
                time = sdf.format(date);
                map.put("time", time);
            }
            if (StringUtils.isNotEmpty(value1)) {
                map.put("value1", value1);
            }
            if (StringUtils.isNotEmpty(value2)) {
                map.put("value2", value2);
            }
            if (StringUtils.isNotEmpty(value3)) {
                map.put("value3", value3);
            }
            if (StringUtils.isNotEmpty(value4)) {
                map.put("value4", value4);
            }
            if (StringUtils.isNotEmpty(value5)) {
                map.put("value5", value5);
            }
            if (StringUtils.isNotEmpty(value6)) {
                map.put("value6", value6);
            }
            if (StringUtils.isNotEmpty(value7)) {
                map.put("value7", value7);
            }
        }
        return map;
    }
    /**
     * 保存患者健康指标  (旧)
     */
    public DevicePatientHealthIndex save(DevicePatientHealthIndex model, int index, double value, String patientCode)throws Exception {
    public DevicePatientHealthIndex save(DevicePatientHealthIndex model, int index, double value, String patientCode) throws Exception {
        model.setCzrq(clock.getCurrentDate());
        model.setDel("1");
        PatientHealthStandard standard = null;
@ -194,7 +282,8 @@ public class PatientHealthIndexService extends BaseService {
                JSONObject jsonObject = doctorWorkTimeService.isDoctorWorking(receiver);
                if (jsonObject.getString("status").equals("1")) {
                    //如果在工作时间内就推送
                    array.put(json);  }
                    array.put(json);
                }
            }
            // 批量保存消息
            messageDao.save(messages);
@ -346,8 +435,8 @@ public class PatientHealthIndexService extends BaseService {
     *
     * @return
     */
    private JSONObject getPatientXT_Json(String patient, String dateString) {
        JSONObject obj = new JSONObject();
    private com.alibaba.fastjson.JSONObject getPatientXT_Json(String patient, String dateString) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user",patient);
        boolean hadData = false;
        Date date = DateUtil.strToDateShort(dateString);
@ -441,12 +530,11 @@ public class PatientHealthIndexService extends BaseService {
            // 餐后
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    msgContent += patient.getName() + "血糖异常("+value1+"mmol/L)";
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                }
            }
            else { //餐前
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    msgContent += patient.getName() + "血糖异常("+value1+"mmol/L)";
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                }
            }
        }
@ -475,8 +563,8 @@ public class PatientHealthIndexService extends BaseService {
                }
            }
            // 收缩压/舒张压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)||!checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                msgContent = patient.getName() +"血压异常(舒张压 "+value2+"mmHg、收缩压 "+value1+"mmHg)";
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY) || !checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                msgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg)";
            }
        }
@ -911,7 +999,7 @@ public class PatientHealthIndexService extends BaseService {
        }
    }
    public JSONObject findLastBypatient(String patientCode, int type){
    public com.alibaba.fastjson.JSONObject findLastBypatient(String patientCode, int type){
        if(type==1){
            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, 1);
            if (obj != null) {
@ -923,19 +1011,18 @@ public class PatientHealthIndexService extends BaseService {
        }else{
            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, type);
            if(obj != null){
                return new JSONObject(obj);
                return JSON.parseObject(JSON.toJSONString(obj));
            }else {
                return null;
            }
        }
    }
    /**
     * 获取患者健康指标历史记录
     * 1血糖,2血压,3体重,4腰围
     */
    public List<Map<String,String>> getHealthIndexHistory(String patientCode, int type,int page,int pagesize) throws Exception {
    public List<Map<String, String>> getHealthIndexHistory(String patientCode, int type, int page, int pagesize) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        // 排序

+ 99 - 8
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java

@ -12,20 +12,14 @@ import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientDisease;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SignFamilyCode;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientDiseaseDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.statistics.WlyySignFamilyCodeDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
@ -122,6 +116,9 @@ public class FamilyContractService extends BaseService {
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private SignFamilyRenewDao signFamilyRenewDao;
    public SignFamily findSignFamilyByCode(String code) {
        return signFamilyDao.findByCodeAndType(code, 2);
    }
@ -2876,4 +2873,98 @@ public class FamilyContractService extends BaseService {
        return result;
    }
    /**
     * 续签申请
     *
     * @param doctor  签约医生
     * @param patient 居民code
     * @return
     */
    public int signRenew(String doctor,String healthDoctor, String patient) throws Exception {
        Patient p = patientDao.findByCode(patient);
        if (p == null) {
            return -1;
        }
        SignFamilyRenew sc = signFamilyRenewDao.findByIdcard(p.getIdcard());
        //判断身份证号是否已签约
        if (sc != null) {
            return -2;
        }
        Doctor d = doctorDao.findByCode(doctor);
        Doctor hd = doctorDao.findByCode(healthDoctor);
        if (d == null) {
            return -3;
        }
        if (hd == null) {
            return -3;
        }
        SignFamilyRenew sf = new SignFamilyRenew();
        sf.setCode(getCode());
        sf.setCzrq(new Date());
        sf.setPatientApplyDate(new Date());
        sf.setDoctor(doctor);
        sf.setDoctorName(d.getName());
        sf.setDoctorHealth(healthDoctor);
        sf.setDoctorHealthName(hd.getName());
        sf.setMobile(p.getMobile());
        sf.setName(p.getName());
        sf.setIdcard(p.getIdcard());
        sf.setOpenid(p.getOpenid());
        sf.setPatient(patient);
        sf.setHospital(d.getHospital());
        sf.setHospitalName(d.getHospitalName());
        sf.setSsc(p.getSsc());
        sf.setStatus(0);//0为初始状态
        sf.setType(2);// 设置为家庭签约
        sf.setSignType("1");//用户申请
        sf.setSignSource("2");//签约来源【1 社区签约 2 移动签约】
        //******************扣费接口**********************/
        sf.setExpensesStatus("0");   //扣费状态 【0未扣费 1已扣费 2已退费】
        sf.setIsValid(0);
        SignFamilyRenew temp = signFamilyRenewDao.save(sf);
        if (temp != null) {
            // 添加签约消息
            Message message = new Message();
            message.setCzrq(new Date());
            message.setCreateTime(new Date());
            message.setContent(p.getName()+"申请与您续签家庭医生");
            message.setRead(1);//设置未读
            message.setReceiver(doctor);//设置接受医生的code
            message.setSender(patient);//设置发送的用户
            message.setSenderName(p.getName());
            message.setCode(getCode());
            message.setSenderPhoto(p.getPhoto());
            message.setTitle("家庭签约申请");
            message.setType(1);//家庭签约信息
            message.setReadonly(1);//是否只读消息
            message.setSignStatus("1");//新的签约
            message.setSex(p.getSex());
            message.setOver("1");//未处理
            message.setData(temp.getCode());
            messageDao.save(message);
            // 发送消息给医生
            JSONObject jsonObject = doctorWorkTimeService.isDoctorWorking(doctor);
            if (jsonObject.getString("status").equals("1")) {
                //如果在工作时间内就推送
                PushMsgTask.getInstance().put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_NEW_SIGN_WEB.D_SW_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_SIGN_WEB.家庭签约.name(), "您有一条新的家庭签约申请!", patient);
            }
        }
        return 1;
    }
}

+ 299 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java

@ -6,12 +6,17 @@ import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SignFamilyRenew;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.patient.SignFamilyRenewDao;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
@ -53,6 +58,10 @@ public class SignWebService extends BaseService {
    private AdminTeamService adminTeamService;
    @Autowired
    private SystemDictService systemDictService;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private SignFamilyRenewDao signFamilyRenewDao;
    /**
     * 根据医生代码及签约状态编码 获取该医生签约患者的信息列表
@ -356,8 +365,58 @@ public class SignWebService extends BaseService {
    }
    public JSONArray getSigns(String patient){
        List<SignFamily> signFamilys =  signFamilyDao.findAllActiveSignByPatient(patient);
        JSONArray jsonArray = new JSONArray();
        //加入续签表数据
//        List<SignFamilyRenew> renews = jdbcTemplate.queryForList(
//                "SELECT * FROM wlyy_sign_family_renew t " +
//                        "WHERE t.patient = '"+patient+"' AND t.status <> -1 and t.status <> -2",SignFamilyRenew.class);
        List<SignFamilyRenew> renews = signFamilyRenewDao.findAllActiveSignByPatient(patient);
        for(SignFamilyRenew renew: renews){
            AdminTeam adminTeam = null;
            Doctor doctor = null;
            if(renew.getAdminTeamId()!=null){
                adminTeam = adminTeamService.getTeam(renew.getAdminTeamId());
                doctor = doctorService.findDoctorByCode(adminTeam.getLeaderCode());
            }
            if(adminTeam==null)adminTeam = new AdminTeam();
            if(doctor==null)doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hospitalName",renew.getHospitalName());
            jsonObject.put("hospital",renew.getHospital());
            jsonObject.put("code",renew.getCode());
            jsonObject.put("teamCode",renew.getTeamCode());
            jsonObject.put("begin",renew.getBegin());
            jsonObject.put("end",renew.getEnd());
            jsonObject.put("status",renew.getStatus());
            jsonObject.put("leader",adminTeam.getLeaderCode());
            jsonObject.put("leaderName",doctor.getName());
            jsonObject.put("doctor",renew.getDoctor());
            jsonObject.put("doctorHealth",renew.getDoctorHealth());
            jsonObject.put("doctorName",renew.getDoctorName());
            jsonObject.put("doctorHealthName",renew.getDoctorHealthName());
            jsonObject.put("expensesStatus",StringUtils.isNotBlank(renew.getExpensesStatus())?renew.getExpensesStatus():"1");
            jsonObject.put("applyDate",renew.getApplyDate());
            jsonObject.put("createTime",renew.getCzrq());
            jsonObject.put("type",renew.getType());
            jsonObject.put("typeName",renew.getType()==1?"三师签约":"家庭签约");
            String statusName = "";
            switch (jsonObject.getInt("status")){
                case -4 : statusName = "已到期";break;
                case -3 : statusName ="已解约";break;
                case 0 : statusName ="待审核";break;
                case 1 : if(jsonObject.getInt("expensesStatus")==1){statusName ="已签约";}else{statusName ="待缴费";} break;
                case 2 : statusName ="患者申请取消签约";break;
                case 3 : statusName ="医生申请取消签约";break;
            }
            jsonObject.put("statusName",statusName);
            jsonArray.put(jsonObject);
        }
        //查询签约表数据
        List<SignFamily> signFamilys =  signFamilyDao.findAllActiveSignByPatient(patient);
        for(SignFamily signFamily: signFamilys){
            AdminTeam adminTeam = null;
            Doctor doctor = null;
@ -656,4 +715,243 @@ public class SignWebService extends BaseService {
        return resultObject;
    }
    /**
     * 根据医生代码及签约状态编码 获取该医生续签患者的信息列表
     *
     * @param doctor
     * @param status
     * @param page
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> getSignRenewWebByDoctor(String doctor, int status, int page, int pageSize) {
        // 查询语句
        String sql = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.idcard " +
                "    ,b.name " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                (status == 1 ? "    ,a.patient_apply_date as applyDate " : "    ,a.expenses_time as applyDate ") +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                " from " +
                " ( select code,patient,doctor,status,id,apply_date,patient_apply_date,expenses_time,reason,begin from wlyy_sign_family_renew where (doctor = ? or doctor_health = ?) and status = ? and type = 2" +
                " order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code  order by a.begin desc limit " + page * pageSize + "," + pageSize;
        // 未缴费查询语句
        String sqlExpenses = "select " +
                "    a.code " +
                "    ,a.doctor " +
                "    ,b.code  as  patient" +
                "    ,b.name " +
                "    ,b.idcard " +
                "    ,b.province_name  as provinceName" +
                "    ,b.city_name  as cityName" +
                "    ,b.town_name  as townName" +
                "    ,b.address " +
                "    ,b.photo " +
                "    ,a.status " +
                "    ,a.id " +
                "    ,a.apply_date as applyDate " +
                "    ,a.reason " +
                "    ,b.street_name as streetName" +
                "    ,b.sex" +
                "    ,b.openid" +
                " from " +
                " ( select code,patient,doctor,status,id,apply_date,reason,begin,expenses_status,LENGTH(trim(ifnull(expenses_status,''))) len from wlyy_sign_family_renew where (doctor = ? or doctor_health = ?) and status > ? and type = 2 order by begin desc ) a " +
                " ,wlyy_patient b " +
                " where a.patient = b.code and (a.expenses_status = '0' or a.len < 1) order by a.begin desc limit " + page * pageSize + "," + pageSize;
        //1:待签约 2, 待缴费 3 已签约
        Page<Object> list = null;
        List<Map<String, Object>> patients = null;
        switch (status) {
            case 1:// 待处理
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, doctor, 0});
                break;
            case 2:// 待缴费
                patients = jdbcTemplate.queryForList(sqlExpenses, new Object[]{doctor, doctor, 1});
                break;
            case 3:// 已签约
                patients = jdbcTemplate.queryForList(sql, new Object[]{doctor, doctor, 1});
                break;
        }
        return patients;
    }
    /**
     * 批量提醒用户
     * @param access_token
     * @param doctor
     * @return
     * @throws Exception
     */
    public int sendRenewToPatients(String access_token,String doctor) throws Exception{
        String sql = "SELECT p.name,p.openid,t.doctor_name doctorName,p.code,p.mobile FROM wlyy_sign_family t ,wlyy_patient p " +
                "WHERE t.patient = p.code AND t.doctor = ? AND t.status >=0 AND t.expenses_status ='1' AND " +
                "NOT EXISTS" +
                "(SELECT 1 FROM wlyy_sign_family_renew a WHERE a.patient =t.patient)  ";
        List<Map<String,Object>> signFamilies = jdbcTemplate.queryForList(sql,new Object[]{doctor});
        if(signFamilies!=null&&signFamilies.size()>0){
            for(Map<String,Object> signFamily : signFamilies){
                String openid = (String)signFamily.get("openid");
                String name = (String)signFamily.get("name");
                String doctorName =(String)signFamily.get("doctorName");
                JSONObject json = new JSONObject();
                json.put("keyword1", "续签家庭医生");
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark","提醒医生 :"+doctorName+"\n"
                        +"我们将继续为您提供优质的健康服务。");
                if(StringUtils.isNotBlank(openid)){
                    json.put("first",name+",您好!\n" +
                            "您的家庭医生签约将于7月31日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                    PushMsgTask.getInstance().putWxMsg(access_token, 16, openid, name, json);
                    return 1;
                }else{
                    //如果自己没有绑定,则发给家人
                    String code = (String)signFamily.get("code");
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(code);
                    Patient member = (Patient)j.get("member");
                    Patient p = patientService.findByCode(code);
                    if(StringUtils.isNotBlank(member.getOpenid())){
                        json.put("first",weiXinOpenIdUtils.getTitleMes(p,(int)j.get("relation"),member.getName())+"\n"+
                                name+",您好!\n" +
                                "您的家庭医生签约将于7月31日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 16, member.getOpenid(), member.getName(), json);
                        return 1;
                    }else{
                        //发送短信
                        String mobile = (String)signFamily.get("mobile");
                        if(StringUtils.isNotBlank(mobile)){
                            SMSService.sendMsg(mobile,name+"您好!您的家庭医生将于7月31日到期,为了继续给您提供健康服务,请关注“厦门i健康”公众号,回复“续签”,进行家庭医生线上续签。");
                            return 2;
                        }
                    }
                }
            }
        }
        return 0;
    }
    /**
     * 同意或拒绝签约签约
     * @param access_token
     * @param dotorCode
     * @param state 1成功 0拒绝
     * @return
     * @throws Exception
     */
    public int agreeRenew(String access_token,String dotorCode,String patientCode,String state) throws Exception{
        List<SignFamilyRenew> renews =  signFamilyRenewDao.findByDoctorAndPatient(dotorCode,patientCode);
        if(renews==null||renews.size()==0){
            renews =  signFamilyRenewDao.findByDoctorHealthAndPatient(dotorCode,patientCode);
        }
        if(renews!=null&&renews.size()>0){
            for(SignFamilyRenew renew : renews){
                if(StringUtils.isNotBlank(state)){
                    if ("0".equals(state)){
                        renew.setStatus(-2);
                    }else if("1".equals(state)){
                        renew.setStatus(1);
                    }
                }
                renew.setStatus(1);
                signFamilyRenewDao.save(renew);
                //发送微信模板消息
                JSONObject data = new JSONObject();
                data.put("doctorName",renew.getDoctorName());
                data.put("date",DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                data.put("content","家庭医生续签");
                Patient patient = patientService.findByCode(renew.getPatient());
                if(patient!=null && StringUtils.isNotBlank(patient.getOpenid())){
                    if ("0".equals(state)){
                        data.put("first",renew.getName()+",您好!\n"+
                                "您的家庭医生续签申请已被拒绝");
                        data.put("remark","您可在到期后选择其他医生进行签约。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 2, patient.getOpenid(), patient.getName(), data);
                    }else if("1".equals(state)){
                        data.put("first",renew.getName()+",您好!\n"+
                                "您的家庭医生续签申请已通过");
                        data.put("remark","待自动扣费成功后,家庭医生将续签成功。");
                        PushMsgTask.getInstance().putWxMsg(access_token, 1, patient.getOpenid(), patient.getName(), data);
                    }
                }else{
                    //如果自己没有绑定,则发给家人
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
                    Patient member = (Patient)j.get("member");
                    if(StringUtils.isNotBlank(member.getOpenid())){
                        if ("0".equals(state)){
                            data.put("first",weiXinOpenIdUtils.getTitleMes(patient,(int)j.get("relation"),member.getName())+"\n"+
                                    patient.getName()+",您好!\n" +
                                    "您的家庭医生续签申请已被拒绝");
                            data.put("remark","您可在到期后选择其他医生进行签约。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 2, member.getOpenid(), member.getName(), data);
                        }else if("1".equals(state)){
                            data.put("first",weiXinOpenIdUtils.getTitleMes(patient,(int)j.get("relation"),member.getName())+"\n"+
                                    patient.getName()+",您好!\n" +
                                    "您的家庭医生续签申请已通过");
                            data.put("remark","待自动扣费成功后,家庭医生将续签成功。");
                            PushMsgTask.getInstance().putWxMsg(access_token, 1, member.getOpenid(), member.getName(), data);
                        }
                    }
                }
            }
        }
        return 1;
    }
    /**
     * 获取年度列表
     * @return
     */
    public JSONObject getRenewYearCount(String doctorCode){
        StringBuffer sql = new StringBuffer("SELECT t.sign_year,COUNT(1) count " +
                "FROM  wlyy_sign_family t WHERE t.doctor ='"+doctorCode+"' AND t.end <=NOW() AND t.status=-4 AND sign_year IS NOT NULL GROUP BY t.sign_year DESC");
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result",rs);
        return json;
    }
    /**
     * 获取用户信息
     * @return
     */
    public JSONObject getOverDuePatients(String year,String doctorCode,Integer page,Integer pageSize){
        StringBuffer sql = new StringBuffer("SELECT IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age," +
                "p.code,p.idcard,p.name,p.mobile,p.openid,p.phone,p.photo," +
                "p.ssc,t.sign_type,p.sex,t.emer_mobile,t.expenses_time,t.expenses_status " +
                "FROM wlyy_sign_family t ,wlyy_patient p " +
                "WHERE t.patient = p.code AND t.doctor ='"+doctorCode+"' AND t.sign_year ='"+year+"' LIMIT "+page*pageSize+","+pageSize+";");
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql.toString());
        JSONObject json = new JSONObject();
        json.put("result",rs);
        return json;
    }
}

+ 17 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsAllService.java

@ -2461,10 +2461,27 @@ public class StatisticsAllService extends BaseService {
                    double rate = (double)bindCout/signCout*100;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    map.put("bindRate",decimalFormat.format(rate)+"%");
                    map.put("bindDoubleRate",rate);
                }else{
                    map.put("bindRate","0.00%");
                    map.put("bindDoubleRate",0.00);
                }
            }
            // 排序
            resultList.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if ((double)o1.get("bindDoubleRate")>=(double)o2.get("bindDoubleRate")) {
                        return -1;
                    } else if ((double)o1.get("bindDoubleRate")<(double)o2.get("bindDoubleRate")) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
            return new JSONArray(resultList);
        } else {
            return new JSONArray();

+ 43 - 2
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/SMSService.java

@ -4,8 +4,12 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
@ -24,6 +28,8 @@ import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import javax.print.Doc;
@Component
@Transactional(rollbackFor = Exception.class)
public class SMSService extends BaseService {
@ -32,7 +38,10 @@ public class SMSService extends BaseService {
    public SMSDao smsDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SignFamilyDao signFamilyDao;
    @Autowired
    DoctorDao doctorDao;
    /**
     * 发送短信验证码接口
     *
@ -81,9 +90,9 @@ public class SMSService extends BaseService {
        // 1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录
        if (type == 1) {
            // 患者注册
            sms.setContent("您的注册验证码为:" + captcha);
        } else if (type == 2 || type == 3) {
            // 找回密码
            sms.setContent("您找回密码验证码为:" + captcha);
        } else if (type == 4 || type == 5) {
            // 登录
@ -108,6 +117,38 @@ public class SMSService extends BaseService {
            // 其他验证码
            sms.setContent("验证码:" + captcha);
        }
        if(type==2||type==4||type==10) {//患者
            List<Patient> patients = patientDao.findByMobile(mobile);
            if(patients!=null&&patients.size()>0){
                SignFamily signFamily = signFamilyDao.findByMobile(mobile);
                if(signFamily!=null){
                    sms.setUserType(0);
                    sms.setUserCode(signFamily.getPatient());
                    sms.setHospital(signFamily.getHospital());
                }
            }
        }else if(type==3||type==5||type==6){//医生
            Doctor d = doctorDao.findByMobile(mobile);
            if(d!=null){
                sms.setUserType(0);
                sms.setUserCode(d.getCode());
                sms.setHospital(d.getHospital());
            }
        }else{//未知
            Doctor d = doctorDao.findByMobile(mobile);
            if(d!=null){
                sms.setUserType(0);
                sms.setUserCode(d.getCode());
                sms.setHospital(d.getHospital());
            }else{
                SignFamily signFamily = signFamilyDao.findByMobile(mobile);
                if(signFamily!=null){
                    sms.setUserType(0);
                    sms.setUserCode(signFamily.getPatient());
                    sms.setHospital(signFamily.getHospital());
                }
            }
        }
        sms.setCaptcha(captcha);
        Date date = new Date();
        // 延后5分钟

+ 72 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatient;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SignFamilyRenew;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientDao;
@ -30,6 +31,7 @@ import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@ -295,4 +297,74 @@ public class PatientService extends TokenService {
        return null;
    }
    /**
     * 判断是否续签
     * @param patient
     * @return
     */
    public JSONObject checkCanRenew(String patient){
        // 是否可以续签逻辑
        //A:wlyy_sign_family
        //B: wlyy_sign_family_renew
        //签约状态(-1患者已取消,-2已拒绝,-3已解约,-4已到期,0待签约,1已签约,2患者申请取消签约,3医生申请取消签约
        //扣费状态 【0未扣费 1已扣费 2已退费】
        JSONObject rs = new JSONObject();
        //判断是否签约
        List<SignFamily> signs =  jdbcTemplate.queryForList("SELECT t.id FROM wlyy_sign_family t WHERE t.status >=0 AND t.expenses_status ='1' AND  t.patient ='"+patient+"'  AND NOW() >= t.begin AND NOW() <= t.end",SignFamily.class);
        if(signs!=null){
            //当前年度已经签约
            rs.put("issign","1");
        }else{
            //当前年度未签约
            rs.put("issign","0");
        }
        //A表有已签约,但还没有扣费的记录的,不允许续签
        List<SignFamily>  signFamilys1 = jdbcTemplate.queryForList("SELECT t.id FROM wlyy_sign_family t WHERE t.status >=0 AND t.expenses_status <>'1' AND t.patient ='"+patient+"'",SignFamily.class);
        if(signFamilys1!=null){
            rs.put("isrenew","0");
            return rs;
        }
        //A表有已签约,且已扣费,当前日期超过了7月1日,且当前日期在合约的有效期范围内,不允许续签
        Calendar calendar =Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR)+"";
        List<SignFamily>  signFamilys2 = jdbcTemplate.queryForList("SELECT t.id FROM wlyy_sign_family t WHERE t.status >=0 AND t.expenses_status ='1' AND  t.patient ='"+patient+"' AND CURDATE()>'"+year+"-07-01' NOW() >= t.begin and NOW() <= t.end",SignFamily.class);
        if(signFamilys2!=null){
            rs.put("isrenew","0");
            return rs;
        }
        //B表:已签约且未生效,不允许续签
        List<SignFamilyRenew> signFamilyRenews = jdbcTemplate.queryForList("SELECT t.id FROM wlyy_sign_family_renew t WHERE t.status>=0 AND  t.is_valid = 0 AND t.patient ='"+patient+"'",SignFamilyRenew.class);
        if(signFamilyRenews!=null){
            rs.put("isrenew","0");
            return rs;
        }
        //都未有记录则允许续签
        rs.put("isrenew","1");
        return rs;
    }
    /**
     * 根据居民ID查询签约CODE
     * @param patient
     * @return
     */
    public String getSignCodeByPatient(String patient){
        if(StringUtils.isBlank(patient)){
            return "";
        }
        try{
            List<SignFamily> signFamilies = jdbcTemplate.queryForList("SELECT * FROM wlyy_sign_family WHERE t.patient = '"+patient+"' AND t.status >=0 AND t.expenses_status ='1' ",SignFamily.class);
            if(signFamilies!=null && signFamilies.size()>0){
                return signFamilies.get(0).getCode();
            }
        }catch (Exception e){
            return "";
        }
        return "";
    }
}

+ 15 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/task/PushMsgTask.java

@ -518,6 +518,21 @@ public class PushMsgTask {
                keyword2.setColor("#000000");
                keyword2.setValue(json.getString("keyword2"));
                m.put("keyword2", keyword2);
            }else if(type == 15){
                temp.setTemplate_id(SystemConf.getInstance().getSystemProperties().getProperty("template_doctor_survey"));
                WechatTemplateData  keyword1= new WechatTemplateData();
                keyword1.setColor("#000000");
                keyword1.setValue(json.getString("keyword1"));
                m.put("keyword1", keyword1);
            }else if(type == 16){
                temp.setTemplate_id(SystemConf.getInstance().getSystemProperties().getProperty("template_doctor_survey"));
                WechatTemplateData  keyword1= new WechatTemplateData();
                keyword1.setColor("#000000");
                keyword1.setValue(json.getString("keyword1"));
                WechatTemplateData  keyword2= new WechatTemplateData();
                keyword1.setColor("#000000");
                keyword1.setValue(json.getString("keyword2"));
                m.put("keyword2", keyword2);
            }
            temp.setData(m);

+ 78 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ClazzReflect.java

@ -0,0 +1,78 @@
package com.yihu.wlyy.util;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.Date;
/**
 * Created by 卓 on 2017/3/14.
 */
public class ClazzReflect {
    public Object formatToClazz(Object clazz, JSONObject jsonObject){
        Field[] field = clazz.getClass().getDeclaredFields(); // 获取实体类的所有属性,返回Field数组
            try {
            for (int j = 0; j < field.length; j++) { // 遍历所有属性
                String name = field[j].getName(); // 获取属性的名字
                String key = field[j].getName();
                if(jsonObject.isNull(name))continue;
                name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写,方便构造get,set方法
                String type = field[j].getGenericType().toString(); // 获取属性的类型
                Method m = null;
                if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
                    String value = jsonObject.getString(key);
                    m = clazz.getClass().getMethod("set"+name,String.class);
                    m.invoke(clazz, value);
                }
                if (type.equals("class java.lang.Integer")) {
                    Integer value =  jsonObject.getInt(key);
                    m = clazz.getClass().getMethod("set"+name,Integer.class);
                    m.invoke(clazz, value);
                }
                if (type.equals("class java.lang.Boolean")) {
                    Boolean value =  jsonObject.getBoolean(key);
                    m = clazz.getClass().getMethod("set"+name,Boolean.class);
                    m.invoke(clazz, value);
                }
                if (type.equals("class java.lang.Long")) {
                    Long value =  getJsonLong(jsonObject,key);
                    m = clazz.getClass().getMethod("set"+name,Long.class);
                    m.invoke(clazz, value);
                }
                if (type.equals("class java.util.Date")) {
                    String valueString = jsonObject.getString(key);
                    Date value =  DateUtil.strToDate(valueString);
                    m = clazz.getClass().getMethod("set"+name,Date.class);
                    m.invoke(clazz, value);
                }// 如果有需要,可以仿照上面继续进行扩充,再增加对其它类型的判断
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (Exception e){
              e.printStackTrace();
        }
        return clazz;
    }
    private Long getJsonLong(JSONObject jsonObject,String key){
            Object object = jsonObject.get(key);
            if(object==null||"".equals(object)){
                return null;
            }else{
                return jsonObject.getLong(key);
            }
    }
}

+ 23 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ImUtill.java

@ -32,6 +32,14 @@ public class ImUtill {
        return response;
    }
    public static void updateTopics(String topicId,String jsonValue){
        String imAddr = im_host + "api/v2/sessions/"+topicId+"/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id",topicId);
        params.put("data",jsonValue);
        HttpClientUtil.putBody(imAddr, params);
    }
    /**
     * 列表接口
     * 获取团队内医生的健康咨询状况
@ -90,6 +98,19 @@ public class ImUtill {
        return response;
    }
    /**
     * 更新会话状态
     *
     * @param sessionId       会话ID
     * @param status 状态
     */
    public static String updateTopicEvaluate(String sessionId,String status) {
        String imAddr = im_host + "api/v2/sessions/"+sessionId+"/status?status="+status+"&sessionId="+sessionId;
        JSONObject params = new JSONObject();
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 发送消息给IM
@ -328,4 +349,6 @@ public class ImUtill {
    public  static final String SESSION_TYPE_SYSTEM = "0";
    public  static final String SESSION_STATUS_PROCEEDINGS= "0";
    public  static final String SESSION_STATUS_END= "1";
    public  static final String CONTENT_TYPE_TEXT= "1";
}

+ 26 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java

@ -2,7 +2,9 @@ package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.job.QuartzHelper;
import com.yihu.wlyy.job.SignEndJob;
import com.yihu.wlyy.job.consult.EvaluateScoreJob;
import com.yihu.wlyy.job.consult.FamousConsultTimesJob;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.statistics.StatisticsService;
@ -18,12 +20,14 @@ import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
@ -52,6 +56,8 @@ public class ManagerUtilController extends BaseController {
    ManageUtilService manageUtilService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ConsultTeamDoctorDao consultTeamDoctorDao;
    /*********************************************患者疾病相关******************************************/
    /**
@ -265,4 +271,24 @@ public class ManagerUtilController extends BaseController {
            return error(-1, "启动失败");
        }
    }
    /**
     * 开始名医咨询剩余次数统计任务
     *
     * @return
     */
    @RequestMapping(value = "/start_evaluate_score_job")
    @ResponseBody
    public String startEvaluateScoreJob() {
        try {
            if (!quartzHelper.isExistJob("evaluate_score_job")) {
                quartzHelper.addJob(EvaluateScoreJob.class, "59 59 23 * * ?", "evaluate_score_job", new HashMap<String, Object>());
                return write(200, "启动成功");
            } else {
                return write(200, "任务已存在");
            }
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
}

+ 1 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java

@ -611,6 +611,7 @@ public class DoctorController extends BaseController {
                //获取医生角色和区域权限
                List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(temp.getCode());
                json.put("userRole", roleMap);
                json.put("evaluateScore", temp.getEvaluateScore());
//                是否团队长
                json.put("isLeader", leader == 0 ? "0" : "1");
                return write(200, "医生信息查询成功!", "data", json);

+ 82 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorEvaluateController.java

@ -0,0 +1,82 @@
package com.yihu.wlyy.web.doctor.consult;
import com.yihu.wlyy.entity.consult.Evaluate;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.EvaluateLabelService;
import com.yihu.wlyy.service.app.consult.EvaluateService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by 卓 on 2017/5/10.
 */
@Controller
@RequestMapping(value = "/doctor/consult/evaluate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生评价")
public class DoctorEvaluateController extends BaseController {
    @Autowired
    ConsultTeamService consultTeamService;
    @Autowired
    EvaluateService evaluateService;
    @Autowired
    EvaluateLabelService evaluateLabelService;
    /**
     * 获取评价
     * @param consult 咨询
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(@RequestParam(required = true,value="consult") String consult,@RequestParam(required = false,value="type") Integer type){
        try{
            List<Evaluate> evaluates = null;
            List<EvaluateLabel> evaluateLabels = new ArrayList<>();
            if(type==null){
                evaluates  =  evaluateService.getEvaluateByConsult(consult);
                evaluateLabels  =  evaluateLabelService.findByConsult(consult);
                JSONArray evaluatesJson = new JSONArray(evaluates);
                JSONArray evaluateLabelsJson = new JSONArray(evaluateLabels);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("evaluate",evaluatesJson);
                jsonObject.put("label",evaluateLabelsJson);
                return  write(200,"查询成功!","data",jsonObject);
            }else{
                evaluates = evaluateService.getEvaluateByConsultAndType(consult,type);
                return  write(200,"查询成功!","list",evaluates);
            }
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取去重的标签
     * @return
     */
    @RequestMapping(value = "label")
    @ResponseBody
    public String label(){
        try{
            List<Map<String,Object>> result = evaluateLabelService.findDistinctLabelByLaDoctor(getUID());
            return write(200,"查询成功!","list",result);
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
}

+ 92 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/feedback/DoctorFeedbackController.java

@ -0,0 +1,92 @@
package com.yihu.wlyy.web.doctor.feedback;
import com.yihu.wlyy.service.app.feedback.AppealService;
import com.yihu.wlyy.service.app.feedback.FeedbackService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
 * Created by Reece on 2017/5/6.
 */
@Controller
@RequestMapping(value = "/doctor/feedback")
@Api(description = "医生端意见反馈与账号申诉")
public class DoctorFeedbackController extends BaseController {
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private AppealService appealService;
    /**
     * 医生端保存意见反馈
     *
     * @param description 问题描述
     * @param type        选择类型
     * @param images      图片,多图逗号分隔
     * @param contact     联系方式
     * @return
     */
    @RequestMapping(value = "/saveFeedback", method = RequestMethod.POST)
    @ApiOperation(value = "医生端保存反馈")
    @ResponseBody
    public String saveFeedback(
            @RequestParam String description,
            @RequestParam int type,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String contact) {
        try {
//        图片上传
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
//        保存到数据库
            feedbackService.saveFeedback(getUID(),2,description,type,images,contact);
            return write(200, "保存成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 医生端保存账号申诉
     *
     * @param description 问题描述
     * @param type        选择类型
     * @param images      图片,多图逗号分隔
     * @param phone       手机号码
     * @return
     */
    @RequestMapping(value = "/saveAppeal", method = RequestMethod.POST)
    @ApiOperation(value = "医生端保存申诉")
    @ResponseBody
    public String saveAppeal(
            @RequestParam String description,
            @RequestParam int type,
            @RequestParam(required = false) String images,
            @RequestParam String phone) {
        try {
//        图片上传
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
//             保存到数据库
            appealService.saveAppeal(getUID(),description,type,images,phone,2);
            return write(200, "保存成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
}

+ 5 - 3
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java

@ -67,12 +67,14 @@ public class DoctorHealthController extends BaseController {
												   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
												   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2016-09-23 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			Iterable<DevicePatientHealthIndex> list = healthIndexService.findChartByPatien(patient, type, begin, end);
			Iterable<DevicePatientHealthIndex> list = healthIndexService.findChartByPatient(getUID(),type,gi_type,begin,end);
			if (list == null) {
				return success("查询成功!");
			}
@ -263,10 +265,10 @@ public class DoctorHealthController extends BaseController {
										   @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient,1);
			com.alibaba.fastjson.JSONObject xt = healthIndexService.findLastBypatient(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
				map.put("xt",xt.toJSONString());
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)

+ 76 - 30
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java

@ -11,12 +11,14 @@ import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.health.*;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.ImUtill;
import com.yihu.wlyy.web.WeixinBaseController;
import com.yihu.wlyy.web.doctor.message.DoctorMessageController;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
@ -84,13 +86,18 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
     * 查询
     *
     * @param pagesize 分页大小
     * @param wheaType 文章类型
     * @return 列表
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize, @RequestParam(value = "filter", required = false) String filter, @RequestParam(value = "patient", required = false) String patient) {
    public String list(@RequestParam(value = "page", required = true) int page,
                       @RequestParam(value = "pagesize", required = true) int pagesize,
                       @RequestParam(value = "wheaType", required = true) int wheaType,
                       @RequestParam(value = "filter", required = false) String filter,
                       @RequestParam(value = "patient", required = false) String patient) {
        try {
            List<Map<String, Object>> list = healthEduArticleService.findAll(page, pagesize, filter, getUID(), patient);
            List<Map<String, Object>> list = healthEduArticleService.findAll(page, pagesize, filter, getUID(), patient,wheaType);
            JSONArray jsonArray = new JSONArray();
            if (list != null) {
                for (Map<String, Object> map : list) {
@ -170,6 +177,10 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                    // 文章简介
                    //json.put("content", parsrHtml(map.get("content").toString()));
                    json.put("content", map.get("content").toString());
                    json.put("read", map.get("is_read"));
                    json.put("attached_content", map.get("attached_content"));
                    // 发送日期
                    json.put("czrq", DateUtil.dateToStrLong((Date) map.get("czrq")));
                    // 发送团队
@ -192,9 +203,9 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
     */
    @RequestMapping(value = "listDoctor")
    @ResponseBody
    public String listDoctor(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize, @RequestParam(value = "filter", required = false) String filter, @RequestParam(value = "patient", required = false) String patient) {
    public String listDoctor(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize, @RequestParam(value = "filter", required = false) String filter, @RequestParam(value = "patient", required = false) String patient, @RequestParam(value = "wheaType", required = false) Integer wheaType) {
        try {
            List<Map<String, Object>> list = healthEduArticleDoctorService.list(page, pagesize, filter, getUID(), patient);
            List<Map<String, Object>> list = healthEduArticleDoctorService.list(page, pagesize, filter, getUID(), patient,wheaType);
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
@ -223,6 +234,7 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                json.put("repeatAmount", map.get("repeatAmount"));
                //是否收藏(医生收藏的列表肯定是收藏的无需额外校验)
                json.put("collection", 1);
                jsonArray.put(json);
            }
            return write(200, "查询成功", "list", jsonArray);
@ -302,6 +314,7 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
     * @param code    文章标识,多个以逗号分隔
     * @param patient 患者标识,多个以逗号分隔
     * @param group   所选群组,多个用逗号分隔
     * @param  attachedContent 附加内容
     * @return
     */
    @RequestMapping(value = "send")
@ -310,7 +323,8 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                       @RequestParam(value = "patient", required = false) String patient,
                       @RequestParam(value = "group", required = false, defaultValue = "") String group,
                       @RequestParam(value = "labelType", required = false) String labelType,
                       @RequestParam(value = "teamCode", required = false) long teamCode) {
                       @RequestParam(value = "teamCode", required = false) long teamCode,
                       @RequestParam(value = "attachedContent", required = false) String attachedContent) {
        try {
            List<HealthEduArticlePatient> list = new ArrayList<HealthEduArticlePatient>();
            if (StringUtils.isEmpty(code)) {
@ -347,11 +361,15 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
            }
            // 查询医生信息
            Doctor doctor = doctorService.findDoctorByCode(getUID());
            //Doctor doctor = doctorService.findDoctorByCode("test00000000005");
            String msgHead = doctor.getName() + "医生给您发来了一篇患教文章";
            String endMsg = "为了您的健康," + doctor.getName() + "医生给您发送了一篇患教文章,请仔细查阅,如有问题,可随时咨询医生。";
            String endMsg = "";//"为了您的健康," + doctor.getName() + "医生给您发送了一篇患教文章,请仔细查阅,如有问题,可随时咨询医生。";
            if(StringUtils.isNotBlank(attachedContent)){
                endMsg = attachedContent;
            }
            JSONArray messages = new JSONArray();
            Map<String, Map<String, Object>> msgs = new HashMap<>();
            String batchNo = UUID.randomUUID().toString();
            Date createTime = new Date();
            for (String p : patientSet) {
                Patient patientTemp = patientService.findByCode(p);
                SignFamily signFamily = signFamilyDao.findByjiatingPatient(p);
@ -390,25 +408,34 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                    heap.setSignType(2);
                    // 行政团队
                    heap.setAdminTeamCode(signFamily.getAdminTeamId());
                    //附加内容
                    heap.setAttachedContent(attachedContent);
                    //批次号记录发送批次
                    heap.setBatchNo(batchNo);
                    //创建时间
                    heap.setCzrq(createTime);
                    heap.setSignCode(patientService.getSignCodeByPatient(p));
                    list.add(heap);
                    consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p, "{\"title\":\"" + temp.getTitle()+ "\",\"type\":0,\"id\":\"" + temp.getCode() + "\",\"img\":\"" + temp.getUrl() + "\",\"content\":\"为了您的健康,我给您发送了一篇文章,请咨询查阅,如有问题,可随时与我沟通\"}", "4", patientTemp.getName());
                    //if (StringUtils.isNotEmpty(patientTemp.getOpenid())) {
                        // 推送消息给微信端
                        JSONObject json = new JSONObject();
                        json.put("first", patientTemp.getName() + ",您好!\n" + msgHead);
                        json.put("toUser", p);
                        json.put("article", temp.getCode() + "");
                        json.put("title", temp.getTitle());
                        json.put("doctorName", doctor.getName());
                        json.put("date", DateUtil.dateToStrLong(DateUtil.getNowDate()));
                        json.put("remark", endMsg);
                        Map<String, Object> content = new HashMap<>();
                        content.put("openid", patientTemp.getOpenid());
                        content.put("name", patientTemp.getName());
                        content.put("json", json);
                        content.put("code",patientTemp.getCode());
                        msgs.put(patientTemp.getCode(), content);
                    //}
                    if(StringUtils.isNotBlank(attachedContent)){
                        //发送备注
                        consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p, attachedContent, ImUtill.CONTENT_TYPE_TEXT, patientTemp.getName());
                    }
                    // 推送消息给微信端
                    JSONObject json = new JSONObject();
                    json.put("first", patientTemp.getName() + ",您好!\n" + msgHead);
                    json.put("toUser", p);
                    json.put("article", temp.getCode() + "");
                    json.put("title", temp.getTitle());
                    json.put("doctorName", doctor.getName());
                    json.put("date", DateUtil.dateToStrLong(DateUtil.getNowDate()));
                    json.put("remark", endMsg);
                    Map<String, Object> content = new HashMap<>();
                    content.put("openid", patientTemp.getOpenid());
                    content.put("name", patientTemp.getName());
                    content.put("json", json);
                    content.put("code",patientTemp.getCode());
                    msgs.put(patientTemp.getCode(), content);
                }
            }
            // 保存到数据库
@ -432,20 +459,15 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                        JSONObject data = (JSONObject) map.get("json");
                        String first = (String)data.get("first");
                        data.remove("first");
                        data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),member.getName()));
                        data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.isNull("relation")?1:j.getInt("relation"),member.getName()));
                        if(StringUtils.isNotBlank(member.getOpenid())){
                            PushMsgTask.getInstance().putWxMsg(getAccessToken(), 9, member.getOpenid(), member.getName(), data);
                        }
                    }
                    JSONObject json = (JSONObject) map.get("json");
                }
                for (HealthEduArticlePatient heap : list) {
                    BusinessLogs.info(BusinessLogs.BusinessType.article, getUID(), heap.getPatient(), new JSONObject(heap));
                }
                // 推送消息给患者
                PushMsgTask.getInstance().put(messages);
                return success("发送成功!");
@ -516,6 +538,30 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
        }
    }
    @RequestMapping(value = "/logs")
    @ResponseBody
    public String getPatientHealthLogs(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize){
       try{
           List<Map<String,Object>> result  =  healthEduArticlePatientService.findByDoctor(getUID(),page,pagesize);
           return write(200,"查询成功!","list",result);
       }catch (Exception e){
           return write(-1,"查询失败!");
       }
    }
    @RequestMapping(value = "/log")
    @ResponseBody
    public String getPatientHealthLog(@RequestParam(value = "article", required = true) String article, @RequestParam(value = "batchNo", required = false) String batchNo){
        try{
            List<Map<String,Object>> result  =   healthEduArticlePatientService.findByBatchNo(getUID(),article,batchNo);
            return write(200,"查询成功!","list",result);
        }catch (Exception e){
            error(e);
            return write(-1,"查询失败!");
        }
    }
    private String parsrHtml(String html) {
        html = ("<span>" + html + "</span>");//拼接一个HTML标签,防止纯文字字符串转换在linux下面出现的异常。
        Parser parser = null;

+ 165 - 14
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/sign/DoctorSignController.java

@ -1,28 +1,28 @@
package com.yihu.wlyy.web.doctor.sign;
import java.text.SimpleDateFormat;
import java.util.*;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.sign.SignWebService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.sign.SignWebService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生端:签约管理控制类
@ -33,7 +33,7 @@ import com.yihu.wlyy.web.BaseController;
@RestController
@RequestMapping(value = "/doctor/sign", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-签约管理")
public class DoctorSignController extends BaseController {
public class DoctorSignController extends WeixinBaseController {
    //	@Autowired
//	private SignContractService signContractService;
@ -344,4 +344,155 @@ public class DoctorSignController extends BaseController {
            return error(-1,"查询失败");
        }
    }
    /**
     * 获取续签约患者信息
     *
     * @param status     签约状态 1:待签约 2 待缴费 3 已签约
     * @return
     */
    @RequestMapping("/sign_info_renew")
    @ApiOperation(value = "医生获取获取列表")
    public String getSignRenewInfoByDoctor(
            @RequestParam(required = true)int status,
            @RequestParam(required = true)int page,
            @RequestParam(required = true)int pageSize) {
        try {
            page = page > 0 ? page -1 : 0;
            List<Map<String, Object>> listSign = signWebService.getSignRenewWebByDoctor(getUID(), status, page, pageSize);
            //List<Map<String, Object>> listSign = signWebService.getSignRenewWebByDoctor("64de930c-5b15-11e6-8344-fa163e8aee56", status, page, pageSize);
            JSONObject data = new JSONObject();
            List<JSONObject> jsonArray = new ArrayList<>();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (listSign != null) {
                for (Map<String, Object> temp : listSign) {
                    if (temp == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", temp.get("code"));
                    json.put("doctorCode", temp.get("doctor"));
                    json.put("patientCode", temp.get("patient"));
                    json.put("patientName", temp.get("name"));
                    json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(temp.get("idcard"))));
                    json.put("provinceName", temp.get("provinceName"));
                    json.put("cityName", temp.get("cityName"));
                    json.put("townName", temp.get("townName"));
                    json.put("address", temp.get("address"));
                    json.put("photo", temp.get("photo"));
                    json.put("status", temp.get("status"));
                    json.put("openid", temp.get("openid"));
                    String statusName = "";
                    switch (Integer.parseInt(temp.get("status").toString())) {
                        case 0:
                            statusName = "待签约";
                            break;
                        case 1:
                            statusName = "已签约";
                            break;
                        case 2:
                            statusName = "待解约";
                            break;
                        case -3:
                        case -4:
                            statusName = "已解约";
                            break;
                    }
                    json.put("statusName", statusName);
                    json.put("id", temp.get("id"));
                    json.put("applyDate", DateUtil.dateToStrLong((Date) temp.get("applyDate")));
                    json.put("releaseSpeak", temp.get("reason"));
                    json.put("streetName", temp.get("streetName"));
                    json.put("sex", temp.get("sex"));
                    jsonArray.add(json);
                }
            }
            data.put("list", jsonArray);
            return write(200, "查询成功!", "data", data);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1, "系统错误,请联系管理员!");
        }
    }
    /**
     * 批量提醒居民续签
     * @return
     */
    @RequestMapping("/sendRenewToPatients")
    @ApiOperation(value = "提醒用户签约")
    public String sendRenewToPatients(){
        try{
            int rs = signWebService.sendRenewToPatients(getAccessToken(),getUID());
            //int rs = signWebService.sendRenewToPatients(getAccessToken(),"64de930c-5b15-11e6-8344-fa163e8aee56");
            if(rs == 0){
                return error(-1, "微信和短信,提醒失败");
            }else{
                return write(200, "提醒成功!", "data", rs);
            }
        }catch (Exception e){
            return error(-1, "提醒失败");
        }
    }
    /**
     * 同意或拒绝
     * @param state
     * @return
     */
    @RequestMapping("/agreeRenew")
    @ApiOperation(value = "医生处理签约")
    public String agreeRenew(@RequestParam(required = true)String state,
                             @RequestParam(required = true)String patient){
        try{
            int rs =signWebService.agreeRenew(getAccessToken(),getUID(),patient,state);
            //int rs =signWebService.agreeRenew(getAccessToken(),"64de930c-5b15-11e6-8344-fa163e8aee56",patient,state);
            if(rs == 0){
                return error(-1, "操作失败");
            }else{
                return write(200, "操作成功!", "data", rs);
            }
        }catch (Exception e){
            return error(-1, "请求失败");
        }
    }
    /**
     * 获取用户详情列表
     * @param year
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping("/getOverDuePatients")
    @ApiOperation(value = "获取用户详情列表")
    public String getOverDuePatients(@RequestParam(required = true)String year,
                                     @RequestParam(required = true)Integer page,
                                     @RequestParam(required = true)Integer pageSize){
        try{
            JSONObject rs =signWebService.getOverDuePatients(year,getUID(),page,pageSize);
            //JSONObject rs =signWebService.getOverDuePatients(year,"64de930c-5b15-11e6-8344-fa163e8aee56",page,pageSize);
            return write(200, "操作成功!", "data", rs);
        }catch (Exception e){
            return error(-1, "请求失败");
        }
    }
    /**
     *
     * 获取去医生下年度分组列表
     * @return
     */
    @RequestMapping("/getRenewYearCount")
    @ApiOperation(value = "获取年度分组")
    public String getRenewYearCount(){
        try{
            //JSONObject rs =signWebService.getRenewYearCount(getUID());
            JSONObject rs =signWebService.getRenewYearCount("64de930c-5b15-11e6-8344-fa163e8aee56");
            return write(200, "操作成功!", "data", rs);
        }catch (Exception e){
            return error(-1, "请求失败");
        }
    }
}

+ 3 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java

@ -106,6 +106,9 @@ public class ConsultController extends WeixinBaseController {
                    json.put("doctorCode", result[7]);
                    json.put("teamCode", result[8]);
                    json.put("evaluate", result[9]);
                    array.put(json);
                }
            }

+ 84 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/EvaluateController.java

@ -0,0 +1,84 @@
package com.yihu.wlyy.web.patient.consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.Evaluate;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.EvaluateLabelService;
import com.yihu.wlyy.service.app.consult.EvaluateService;
import com.yihu.wlyy.util.ClazzReflect;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by 卓 on 2017/5/10.
 */
@Controller
@RequestMapping(value = "/patient/consult/evaluate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生评价")
public class EvaluateController  extends BaseController {
    @Autowired
    ConsultTeamService consultTeamService;
    @Autowired
    EvaluateService evaluateService;
    @Autowired
    EvaluateLabelService evaluateLabelService;
    /**
     * 保存评价
     * @param evaluateJson 保存评价内容的JSON
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(@RequestParam(required = true,value="evaluate") String evaluateJson){
        try{
            evaluateService.saveByJson(evaluateJson,getUID());
            return  write(200,"保存成功!");
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取评价
     * @param consult 咨询
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(@RequestParam(required = true,value="consult") String consult,@RequestParam(required = false,value="type") Integer type){
        try{
            List<Evaluate> evaluates = null;
            List<EvaluateLabel> evaluateLabels = new ArrayList<>();
            if(type==null){
                evaluates  =  evaluateService.getEvaluateByConsult(consult);
                evaluateLabels  =  evaluateLabelService.findByConsult(consult);
                JSONArray evaluatesJson = new JSONArray(evaluates);
                JSONArray evaluateLabelsJson = new JSONArray(evaluateLabels);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("evaluate",evaluatesJson);
                jsonObject.put("label",evaluateLabelsJson);
                return  write(200,"查询成功!","data",jsonObject);
            }else{
                evaluates = evaluateService.getEvaluateByConsultAndType(consult,type);
                return  write(200,"查询成功!","list",evaluates);
            }
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
}

+ 154 - 107
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java

@ -16,123 +16,170 @@ 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.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 患者端:设备管理控制类
 * @author George
 *
 * @author George
 */
@Controller
@RequestMapping(value = "patient/device")
@Api(value = "患者设备管理", description = "患者设备管理")
public class PatientDeviceController extends BaseController {
	@Autowired
	private PatientDeviceService patientDeviceService;
	private ObjectMapper  objectMapper=new ObjectMapper();
	/**
	 * 设备保存接口
	 */
	@ApiOperation("设备保存接口")
	@RequestMapping(value = "SavePatientDevice",method = RequestMethod.POST)
	@ResponseBody
	public String saveDevice(@ApiParam(name="json",value="设备数据json",defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
							  @RequestParam(value="json",required = true) String json) {
		try {
			PatientDevice device = objectMapper.readValue(json,PatientDevice.class);
			// 设置患者标识
			device.setUser(getUID());
			patientDeviceService.saveDevice(device);
			return success("设备保存成功!");
		}
		catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 *  设备列表获取
	 * @return 操作结果
	 */
	@ApiOperation("患者设备列表获取")
	@RequestMapping(value = "PatientDeviceList",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceByPatient(@ApiParam(name="id",value="分页起始id",defaultValue = "0")
									  @RequestParam(value="id",required = true) long id,
									 @ApiParam(name="pagesize",value="每页条数",defaultValue = "10")
									 @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			Page<PatientDevice> list = patientDeviceService.findByPatient(getUID(), id, pagesize);
			return write(200, "查询成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("获取患者设备信息")
	@RequestMapping(value = "PatientDeviceInfo",method = RequestMethod.GET)
	@ResponseBody
	public String getPatientDeviceInfo(@ApiParam(name="id",value="患者设备ID",defaultValue = "146")
									 @RequestParam(value="id",required = true) String id) {
		try {
			PatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 *  通过sn码获取设备绑定情况
	 */
	@ApiOperation("通过sn码获取设备绑定情况")
	@RequestMapping(value = "PatientDeviceIdcard",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceUser(@ApiParam(name="type",value="设备类型",defaultValue = "1")
									     @RequestParam(value="type",required = true) String type,
										 @ApiParam(name="device_sn",value="设备SN码",defaultValue = "15L000002")
										 @RequestParam(value="device_sn",required = true) String deviceSn) {
		try {
			List<Map<String,String>> list = patientDeviceService.getDeviceUser(getUID(),deviceSn,type);
			return write(200, "获取设备绑定信息成功!", "data",list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除")
	@RequestMapping(value = "DeletePatientDevice")
	@ResponseBody
	public String delete(@ApiParam(name="id",value="删除设备关联ID")
						  @RequestParam(value="id",required = true) String id) {
		try {
			PatientDevice pd = patientDeviceService.findById(id);
			if(pd!=null)
			{
				if (!StringUtils.equals(pd.getUser(), getUID())) {
					return error(-1, "只允许删除自己的设备!");
				}
				// 删除设备
				patientDeviceService.deleteDevice(id,getUID());
				return success("设备已删除!");
			}
			else{
				return error(-1, "不存在该设备!");
			}
		} catch (Exception ex) {
			return invalidUserException(ex, -1,ex.getMessage());
		}
	}
    @Autowired
    private PatientDeviceService patientDeviceService;
    private ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 设置血糖仪时间段
     * 默认时间段如下
     * fasting: 00:00-07:59
     * afterBreakfast: 08:00-09:59
     * beforeLunch: 10:00-11:59
     * afterLunch: 12:00-13:59
     * beforeDinner: 14:00-17:59
     * afterDinner: 18:00-19:59
     * beforeSleep: 20:00-23:59
     */
    @ApiOperation("设置血糖仪时间段")
    @RequestMapping(value = "/setBloodTime", method = RequestMethod.GET)
    @ResponseBody
    public String setBloodTime(@RequestParam String fastingStart,
                               @RequestParam String fastingEnd,
                               @RequestParam String afterBreakfastStart,
                               @RequestParam String afterBreakfastEnd,
                               @RequestParam String beforeLunchStart,
                               @RequestParam String beforeLunchEnd,
                               @RequestParam String afterLunchStart,
                               @RequestParam String afterLunchEnd,
                               @RequestParam String beforeDinnerStart,
                               @RequestParam String beforeDinnerEnd,
                               @RequestParam String afterDinnerStart,
                               @RequestParam String afterDinnerEnd,
                               @RequestParam String beforeSleepStart,
                               @RequestParam String beforeSleepEnd,
                               @RequestParam String deviceSN) {
        try {
            String user = getUID();
            patientDeviceService.setBloodTime(user,deviceSN,fastingStart,fastingEnd,afterBreakfastStart,afterBreakfastEnd,beforeLunchStart,beforeLunchEnd,
                    afterLunchStart,afterLunchEnd,beforeDinnerStart,beforeDinnerEnd,afterDinnerStart,afterDinnerEnd,beforeSleepStart,beforeSleepEnd);
            return write(200,"设置成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e,-1,"设置失败!");
        }
    }
    /**
     * 设备保存接口  ---要增加血糖时间段保存
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    @ResponseBody
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            PatientDevice device = objectMapper.readValue(json, PatientDevice.class);
            // 设置患者标识
            device.setUser(getUID());
            patientDeviceService.saveDevice(device);
            return success("设备保存成功!");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceByPatient(@ApiParam(name = "id", value = "分页起始id", defaultValue = "0")
                                     @RequestParam(value = "id", required = true) long id,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            Page<PatientDevice> list = patientDeviceService.findByPatient(getUID(), id, pagesize);
            return write(200, "查询成功", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    //要增加时间段信息展示
    @ApiOperation("获取患者设备信息")
    @RequestMapping(value = "PatientDeviceInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            PatientDevice device = patientDeviceService.findById(id);
            String deviceSN = device.getDeviceSn();
            String user = device.getUser();
            Map map = patientDeviceService.getBloodSuggerTime(user,deviceSN);
            mapList.put("time",map);
            mapList.put("device",device);
            return write(200, "查询成功", "data", mapList);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 通过sn码获取设备绑定情况
     */
    @ApiOperation("通过sn码获取设备绑定情况")
    @RequestMapping(value = "PatientDeviceIdcard", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceUser(@ApiParam(name = "type", value = "设备类型", defaultValue = "1")
                                @RequestParam(value = "type", required = true) String type,
                                @ApiParam(name = "device_sn", value = "设备SN码", defaultValue = "15L000002")
                                @RequestParam(value = "device_sn", required = true) String deviceSn) {
        try {
            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getUID(), deviceSn, type);
            return write(200, "获取设备绑定信息成功!", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice")
    @ResponseBody
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
                if (!StringUtils.equals(pd.getUser(), getUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getUID());
                return success("设备已删除!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

+ 2 - 2
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/family/FamilyMemberController.java

@ -321,8 +321,8 @@ public class FamilyMemberController extends WeixinBaseController {
    @ApiOperation(value = "发送微信模板")
    public String sendWXTemp(@RequestParam("member")String member,@RequestParam("relation")int relation){
        try {
            int result = familyMemberService.sendWXTemp(getUID(),member,getAccessToken(),relation);
            //int result = familyMemberService.sendWXTemp("28ea723708514c9bbf5a84c1db6c0215",member,getAccessToken(),relation);
            //int result = familyMemberService.sendWXTemp(getUID(),member,getAccessToken(),relation);
            int result = familyMemberService.sendWXTemp("d682497b7552459797145b6cd63f0ef5",member,getAccessToken(),relation);
            if(result==-1){
                return error(-1, "居民信息查询失败");
            }else if(result==-2){

+ 158 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/feedback/PatientFeedbackController.java

@ -0,0 +1,158 @@
package com.yihu.wlyy.web.patient.feedback;
import com.yihu.wlyy.service.app.feedback.AppealService;
import com.yihu.wlyy.service.app.feedback.FeedbackService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
 * Created by Reece on 2017/5/6.
 */
@Controller
@RequestMapping(value = "/patient/feedback")
@Api(description = "居民端意见反馈与账号申诉")
public class PatientFeedbackController extends WeixinBaseController {
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private AppealService appealService;
    /**
     * 居民端保存意见反馈
     *
     * @param description 问题描述
     * @param type        选择类型
     * @param images      图片,多图逗号分隔
     * @param contact     联系方式
     * @return
     */
    @RequestMapping(value = "/saveFeedback", method = RequestMethod.POST)
    @ApiOperation(value = "居民端保存反馈")
    @ResponseBody
    public String saveFeedback(
            @RequestParam String description,
            @RequestParam int type,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String contact) {
        try {
//        图片上传
            String photos="";
            if (StringUtils.isNotEmpty(images)) {
                String[] mediaIds = images.split(",");
                for (String mediaId : mediaIds) {
                    if (StringUtils.isEmpty(mediaId)) {
                        continue;
                    }
                    String temp = saveImageToDisk(mediaId);
                    if (StringUtils.isNotEmpty(temp)) {
                        if (photos.length() == 0) {
                            photos = temp;
                        } else {
                            photos += "," + temp;
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(photos)) {
                photos = CommonUtil.copyTempImage(photos);
            }
//        保存到数据库
            feedbackService.saveFeedback(getUID(),1,description,type,photos,contact);
            return write(200, "保存成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 居民端保存账号申诉
     *
     * @param description 问题描述
     * @param type        选择类型
     * @param images      图片,多图逗号分隔
     * @param phone       手机号码
     * @return
     */
    @RequestMapping(value = "/saveAppeal", method = RequestMethod.POST)
    @ApiOperation(value = "居民端保存申诉")
    @ResponseBody
    public String saveAppeal(
            @RequestParam String description,
            @RequestParam int type,
            @RequestParam(required = false) String images,
            @RequestParam String phone) {
        try {
//        图片上传
            String photos="";
            if (StringUtils.isNotEmpty(images)) {
                String[] mediaIds = images.split(",");
                for (String mediaId : mediaIds) {
                    if (StringUtils.isEmpty(mediaId)) {
                        continue;
                    }
                    String temp = saveImageToDisk(mediaId);
                    if (StringUtils.isNotEmpty(temp)) {
                        if (photos.length() == 0) {
                            photos = temp;
                        } else {
                            photos += "," + temp;
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(photos)) {
                photos = CommonUtil.copyTempImage(photos);
            }
//             保存到数据库
            appealService.saveAppeal(getUID(),description,type,photos,phone,1);
            return write(200, "保存成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 获取微信服务器图片
     *
     * @return
     */
    public String fetchWxImages() {
        String photos = "";
        try {
            String images = request.getParameter("mediaIds");
            if (StringUtils.isEmpty(images)) {
                return photos;
            }
            String[] mediaIds = images.split(",");
            for (String mediaId : mediaIds) {
                if (StringUtils.isEmpty(mediaId)) {
                    continue;
                }
                String temp = saveImageToDisk(mediaId);
                if (StringUtils.isNotEmpty(temp)) {
                    if (photos.length() == 0) {
                        photos = temp;
                    } else {
                        photos += "," + temp;
                    }
                }
            }
        } catch (Exception e) {
            error(e);
        }
        return photos;
    }
}

+ 165 - 145
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/HealthEduArticleController.java

@ -33,155 +33,175 @@ import java.util.Map;
/**
 * 患者端:健康教育控制类
 * @author George
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient/health/edu", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-健康教育")
public class HealthEduArticleController extends BaseController {
	@Autowired
	private HealthEduArticlePatientService healthEduArticlePatientService;
	@Autowired
	private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
	@Autowired
	private HealthEduArticleService healthEduArticleService;
	@Autowired
	private DoctorService doctorService;
	/**
	 * 查询文章列表
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam("id")long id, @RequestParam("pagesize") int pagesize) {
		try {
			List<HealthEduArticlePatient> list = healthEduArticlePatientService.findByPatient(getUID(), id, pagesize);
			JSONArray jsonArray = new JSONArray();
			Map<String,Doctor> docMap = new HashMap<>();
			if (list != null) {
				for (HealthEduArticlePatient article : list) {
					JSONObject json = new JSONObject();
					json.put("id", article.getId());
					// 文章标识
					json.put("article", article.getArticle());
					// 医生姓名
					json.put("doctorName", article.getDoctorName());
					// 文章标题
					json.put("title", article.getTitle());
					// 文章查看URL
					json.put("url", article.getUrl());
					// 文章简介
					//json.put("content", parsrHtml(article.getContent()));
					json.put("content", article.getContent());
					// 是否已读:0已读,1未读
					json.put("read", article.getRead());
					// 添加日期
					json.put("czrq", DateUtil.dateToStrLong(article.getCzrq()));
					if(docMap.get(article.getDoctor())==null){
						Doctor doctor = doctorService.findDoctorByCode(article.getDoctor());
						docMap.put(article.getDoctor(),doctor);
						json.put("photo",doctor.getPhoto());
					}else{
						json.put("photo",docMap.get(article.getDoctor()).getPhoto());
					}
					//int collectionAmount =  healthEduArticleOpHistoryService.countCollectionAmount(article.getArticle());
					//int readAmount = healthEduArticleOpHistoryService.countReadAmount(article.getArticle());
					//int repeatAmount = healthEduArticleOpHistoryService.countRepeatAmount(article.getArticle());
					////阅读量
					//json.put("readAmount", readAmount);
					////收藏量
					//json.put("collectionAmount", collectionAmount);
					////转发量
					//json.put("repeatAmount", repeatAmount);
					jsonArray.put(json);
				}
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询文章列表
	 * @param article 数据文章唯一标示article
	 * @return 列表
	 */
	@RequestMapping(value = "article")
	@ResponseBody
	public String article(@RequestParam(value = "article",required = true) String article) {
		try {
			//获取单条文章记录
			List<HealthEduArticlePatient> healthEduArticlePatients = healthEduArticlePatientService.findByArticleAndPatient(article,getUID());
			if(healthEduArticlePatients==null||healthEduArticlePatients.size()==0){
				return error(-2,"对不起,该消息不是您的消息,您无法查看哦~");
			}
			int isRead  = healthEduArticleOpHistoryService.countByUserStatus(getUID(),HealthEduArticleOpHistory.READ_STATUS);
			//插入文章读取状态第一次阅读记录浏览数量//暂时更新每次都算一次浏览量
			HealthEduArticlePatient healthEduArticlePatient = healthEduArticlePatients.get(0);
			healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS,healthEduArticlePatient.getArticle(),healthEduArticlePatient.getTitle(),getUID());
			if(isRead==0){
				//将文章更新为已读
				healthEduArticlePatientService.updateRead(getUID(), healthEduArticlePatient.getArticle());
			}
			HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(healthEduArticlePatient.getArticle());
			JSONObject json = new JSONObject();
			json.put("id", healthEduArticle.getId());
			// 文章标识
			json.put("article", healthEduArticlePatient.getArticle());
			// 医生姓名
			json.put("doctorName", healthEduArticlePatient.getDoctorName());
			// 文章标题
			json.put("title", healthEduArticle.getTitle());
			// 文章内容
			json.put("content", healthEduArticle.getContent());
			json.put("url", healthEduArticle.getUrl());
			// 添加日期
			json.put("czrq", DateUtil.dateToStrLong(healthEduArticlePatient.getCzrq()));
			int readAmount = healthEduArticleOpHistoryService.countReadAmount(healthEduArticlePatient.getArticle());
			json.put("readAmount",readAmount);
			return write(200, "查询成功", "data", json);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 更新文章为已读
	 * @param article 文章标识
	 * @return
	 */
	@RequestMapping(value = "read")
	@ResponseBody
	public String read(@RequestParam("article") String article) {
		try {
			healthEduArticlePatientService.updateRead(getUID(), article);
			return success("操作成功!");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "操作失败!");
		}
	}
	private String parsrHtml(String html) throws ParserException {
		Parser parser = null;
		html = ("<span>"+html+"<span>");
		try{
			parser = new Parser(html);
		}catch (ParserException e){
			return html;//纯文本内容会转换失败,直接返回文本内容
		}
		TextExtractingVisitor visitor = new TextExtractingVisitor();
		parser.visitAllNodesWith(visitor);
		return StringUtils.isNotBlank(visitor.getExtractedText())?visitor.getExtractedText():"内容为图集,请点击查看";
	}
}
    @Autowired
    private HealthEduArticlePatientService healthEduArticlePatientService;
    @Autowired
    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
    @Autowired
    private HealthEduArticleService healthEduArticleService;
    @Autowired
    private DoctorService doctorService;
    /**
     * 查询文章列表
     *
     * @param pagesize 分页大小
     * @return 列表
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(@RequestParam("id") long id, @RequestParam("pagesize") int pagesize, @RequestParam(required = true, value = "wheaType") int wheaType) {
        try {
            List<HealthEduArticlePatient> list = healthEduArticlePatientService.findByPatient(getUID(), wheaType, id, pagesize);
            JSONArray jsonArray = new JSONArray();
            Map<String, Doctor> docMap = new HashMap<>();
            if (list != null) {
                for (HealthEduArticlePatient article : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", article.getId());
                    // 文章标识
                    json.put("article", article.getArticle());
                    // 医生姓名
                    json.put("doctorName", article.getDoctorName());
                    // 文章标题
                    json.put("title", article.getTitle());
                    // 文章查看URL
                    json.put("url", article.getUrl());
                    // 文章简介
                    //json.put("content", parsrHtml(article.getContent()));
                    json.put("content", article.getContent());
                    // 是否已读:0已读,1未读
                    json.put("read", article.getRead());
                    // 添加日期
                    json.put("czrq", DateUtil.dateToStrLong(article.getCzrq()));
                    //附加内容
                    json.put("attached_content", article.getAttachedContent());
                    if (docMap.get(article.getDoctor()) == null) {
                        Doctor doctor = doctorService.findDoctorByCode(article.getDoctor());
                        docMap.put(article.getDoctor(), doctor);
                        json.put("photo", doctor.getPhoto());
                    } else {
                        json.put("photo", docMap.get(article.getDoctor()).getPhoto());
                    }
                    jsonArray.put(json);
                }
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 查询文章列表
     *
     * @param article 数据文章唯一标示article
     * @return 列表
     */
    @RequestMapping(value = "article")
    @ResponseBody
    public String article(@RequestParam(value = "article", required = true) String article) {
        try {
            //获取单条文章记录
            List<HealthEduArticlePatient> healthEduArticlePatients = healthEduArticlePatientService.findByArticleAndPatient(article, getUID());
            if (healthEduArticlePatients == null || healthEduArticlePatients.size() == 0) {
                return error(-2, "对不起,该消息不是您的消息,您无法查看哦~");
            }
            int isRead = healthEduArticleOpHistoryService.countByUserStatus(getUID(), HealthEduArticleOpHistory.READ_STATUS);
            //插入文章读取状态第一次阅读记录浏览数量//暂时更新每次都算一次浏览量
            HealthEduArticlePatient healthEduArticlePatient = healthEduArticlePatients.get(0);
            healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS, healthEduArticlePatient.getArticle(), healthEduArticlePatient.getTitle(), getUID());
            if (isRead == 0) {
                //将文章更新为已读
                healthEduArticlePatientService.updateRead(getUID(), healthEduArticlePatient.getArticle());
            }
            HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(healthEduArticlePatient.getArticle());
            JSONObject json = new JSONObject();
            json.put("id", healthEduArticle.getId());
            // 文章标识
            json.put("article", healthEduArticlePatient.getArticle());
            // 医生姓名
            json.put("doctorName", healthEduArticlePatient.getDoctorName());
            // 文章标题
            json.put("title", healthEduArticle.getTitle());
            // 文章内容
            json.put("content", healthEduArticle.getContent());
            json.put("url", healthEduArticle.getUrl());
            // 添加日期
            json.put("czrq", DateUtil.dateToStrLong(healthEduArticlePatient.getCzrq()));
            int readAmount = healthEduArticleOpHistoryService.countReadAmount(healthEduArticlePatient.getArticle());
            json.put("readAmount", readAmount);
            return write(200, "查询成功", "data", json);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 更新文章为已读
     *
     * @param article 文章标识
     * @return
     */
    @RequestMapping(value = "read")
    @ResponseBody
    public String read(@RequestParam("article") String article) {
        try {
            healthEduArticlePatientService.updateRead(getUID(), article);
            return success("操作成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "操作失败!");
        }
    }
    private String parsrHtml(String html) throws ParserException {
        Parser parser = null;
        html = ("<span>" + html + "<span>");
        try {
            parser = new Parser(html);
        } catch (ParserException e) {
            return html;//纯文本内容会转换失败,直接返回文本内容
        }
        TextExtractingVisitor visitor = new TextExtractingVisitor();
        parser.visitAllNodesWith(visitor);
        return StringUtils.isNotBlank(visitor.getExtractedText()) ? visitor.getExtractedText() : "内容为图集,请点击查看";
    }
    /**
     * 对当前用户的所有未读文章设置为已读
     *
     * @return
     */
    @RequestMapping(value = "/readAllArticle",method = RequestMethod.GET)
    @ResponseBody
    public String readAllArticle() {
        try {
            String patient = getUID();
//            String patient = "0cc6e4562de2437ab2dbbf51a9fc3b49";
            int row = healthEduArticleService.readAllArticle(patient);
            System.out.println(row);
            return write(200,"更改状态成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e,-1,"更改状态失败!");
        }
    }
    }

+ 453 - 250
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java

@ -1,14 +1,12 @@
package com.yihu.wlyy.web.patient.health;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@ -31,28 +29,239 @@ import com.yihu.wlyy.web.BaseController;
@Api(description = "患者指标")
public class PatientHealthController extends BaseController {
	@Autowired
	private PatientHealthIndexService healthIndexService;
    @Autowired
    private PatientHealthIndexService healthIndexService;
	/**
	 * 患者最近填写的健康指标(旧)
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	public String recent() {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(getUID());
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
    /**
     * 更改接口(包括手动记录的修改和所有的删除)
     * 血糖  value1 血糖值 value2 1234567血糖时间段
     * 血压  value1 高压 value2 低压 value3脉搏 value4心率不齐(0否 1是)
     * 体重 value1 体重值
     * 腰围 value1 腰围值
     * @param id
     * @param value1 字段值
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    @ResponseBody
    public String modify(@RequestParam long id,
                         @RequestParam(required = false) String value1,
                         @RequestParam(required = false) String value2,
                         @RequestParam(required = false) String value3,
                         @RequestParam(required = false) String value4) {
        try {
            healthIndexService.modify(id,value1,value2,value3,value4);
            return write(200, "更改成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "更改失败!");
        }
    }
    /**
     * 患者最近的各项健康信息
     *
     * @return
     */
    @RequestMapping(value = "/getRecentData")
    @ResponseBody
    public String getRecentData() {
        try {
            List list = new ArrayList();
            String patient = getUID();
//            健康指标类型(1血糖,2血压,3体重,4腰围)
            Map map = healthIndexService.findDataByPatient(patient, 1);
            Map map1 = healthIndexService.findDataByPatient(patient, 2);
            Map map2 = healthIndexService.findDataByPatient(patient, 3);
            Map map3 = healthIndexService.findDataByPatient(patient, 4);
//            血糖各个时间段取值
            if (map.size() != 0) {
                Map sugar = new HashMap();
                Object time = map.get("time");
                String isDevice = map.get("isDevice").toString();
                Object value1 = map.get("value1");
                Object value2 = map.get("value2");
                Object value3 = map.get("value3");
                Object value4 = map.get("value4");
                Object value5 = map.get("value5");
                Object value6 = map.get("value6");
                Object value7 = map.get("value7");
                sugar.put("type", 1);
                sugar.put("isDevice", isDevice);
                if (time != null) {
                    sugar.put("time", time);
                }
                if (value1 != null) {
                    sugar.put("value1", value1);
                }
                if (value2 != null) {
                    sugar.put("value2", value2);
                }
                if (value3 != null) {
                    sugar.put("value3", value3);
                }
                if (value4 != null) {
                    sugar.put("value4", value4);
                }
                if (value5 != null) {
                    sugar.put("value5", value5);
                }
                if (value6 != null) {
                    sugar.put("value6", value6);
                }
                if (value7 != null) {
                    sugar.put("value7", value7);
                }
                list.add(sugar);
            }
//            血压  value1高压 value2低压 value3脉搏 value4心率不齐
            if (map1.size() != 0) {
                Map pa = new HashMap();
                Object time = map1.get("time");
                String isDevice = map1.get("isDevice").toString();
                Object value1 = map1.get("value1");
                Object value2 = map1.get("value2");
                Object value3 = map1.get("value3");
                Object value4 = map1.get("value4");
                Object value5 = map1.get("value5");
                Object value6 = map1.get("value6");
                Object value7 = map1.get("value7");
                pa.put("type", 2);
                pa.put("isDevice", isDevice);
                if (time != null) {
                    pa.put("time", time);
                }
                if (value1 != null) {
                    pa.put("value1", value1);
                }
                if (value2 != null) {
                    pa.put("value2", value2);
                }
                if (value3 != null) {
                    pa.put("value3", value3);
                }
                if (value4 != null) {
                    pa.put("value4", value4);
                }
                if (value5 != null) {
                    pa.put("value5", value5);
                }
                if (value6 != null) {
                    pa.put("value6", value6);
                }
                if (value7 != null) {
                    pa.put("value7", value7);
                }
                list.add(pa);
            }
//            体重 value1 体重
            if (map2.size() != 0) {
                Map weight = new HashMap();
                Object time = map2.get("time");
                String isDevice = map2.get("isDevice").toString();
                Object value1 = map2.get("value1");
                Object value2 = map2.get("value2");
                Object value3 = map2.get("value3");
                Object value4 = map2.get("value4");
                Object value5 = map2.get("value5");
                Object value6 = map2.get("value6");
                Object value7 = map2.get("value7");
                weight.put("type", 3);
                weight.put("isDevice", isDevice);
                if (time != null) {
                    weight.put("time", time);
                }
                if (value1 != null) {
                    weight.put("value1", value1);
                }
                if (value2 != null) {
                    weight.put("value2", value2);
                }
                if (value3 != null) {
                    weight.put("value3", value3);
                }
                if (value4 != null) {
                    weight.put("value4", value4);
                }
                if (value5 != null) {
                    weight.put("value5", value5);
                }
                if (value6 != null) {
                    weight.put("value6", value6);
                }
                if (value7 != null) {
                    weight.put("value7", value7);
                }
                list.add(weight);
            }
//            腰围 value1腰围
            if (map3.size() != 0) {
                Map waist = new HashMap();
                Object time = map3.get("time");
                String isDevice = map3.get("isDevice").toString();
                Object value1 = map3.get("value1");
                Object value2 = map3.get("value2");
                Object value3 = map3.get("value3");
                Object value4 = map3.get("value4");
                Object value5 = map3.get("value5");
                Object value6 = map3.get("value6");
                Object value7 = map3.get("value7");
                waist.put("type", 4);
                waist.put("isDevice", isDevice);
                if (time != null) {
                    waist.put("time", time);
                }
                if (value1 != null) {
                    waist.put("value1", value1);
                }
                if (value2 != null) {
                    waist.put("value2", value2);
                }
                if (value3 != null) {
                    waist.put("value3", value3);
                }
                if (value4 != null) {
                    waist.put("value4", value4);
                }
                if (value5 != null) {
                    waist.put("value5", value5);
                }
                if (value6 != null) {
                    waist.put("value6", value6);
                }
                if (value7 != null) {
                    waist.put("value7", value7);
                }
                list.add(waist);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    /**
     * 患者最近填写的健康指标
     *
     * @return
     */
    @RequestMapping(value = "recent")
    @ResponseBody
    public String recent() {
        try {
            JSONArray array = healthIndexService.findRecentByPatient(getUID());
            if (array != null) {
                return write(200, "查询成功", "list", array);
            } else {
                return error(-1, "查询失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
	/**
	 * 获取患者最后填写的健康指标(新)
@ -64,10 +273,10 @@ public class PatientHealthController extends BaseController {
		try {
			Map<String,Object> map = new HashMap<>();
			String patient = getUID();
			JSONObject xt = healthIndexService.findLastBypatient(patient,1);
			com.alibaba.fastjson.JSONObject xt = healthIndexService.findLastBypatient(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
				map.put("xt",xt.toString());
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)
@ -107,131 +316,124 @@ public class PatientHealthController extends BaseController {
	public String add(@RequestParam(required = false) String intervene, String time, String value1, String value2, String value3, String value4, String value5, String value6, String value7, int type) {
		try {
			DevicePatientHealthIndex healthIndex = null;
			if (type == 1) {
				// 血糖等一天只能存在一条数据
				Iterable<DevicePatientHealthIndex> list = healthIndexService.findByPatienDate(getUID(), type, DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
				if (list != null) {
					for (DevicePatientHealthIndex model : list) {
						healthIndex = model;
					}
				}
			}
			if (healthIndex == null) {
				healthIndex = new DevicePatientHealthIndex();
			}
			// 设置患者标识
			healthIndex.setUser(getUID());
			// 设置干预标识,默认为NULL
			healthIndex.setIntervene(intervene);
            DevicePatientHealthIndex healthIndex = null;
            if (type == 1) {
                // 血糖等一天只能存在一条数据
                Iterable<DevicePatientHealthIndex> list = healthIndexService.findByPatienDate(getUID(), type, DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
                if (list != null) {
                    for (DevicePatientHealthIndex model : list) {
                        healthIndex = model;
                    }
                }
            }
            if (healthIndex == null) {
                healthIndex = new DevicePatientHealthIndex();
            }
            // 设置患者标识
            healthIndex.setUser(getUID());
            // 设置干预标识,默认为NULL
            healthIndex.setIntervene(intervene);
			int index = 0;
			double value = 0;
            int index = 0;
            double value = 0;
			// 设置血糖/收缩压/体重/腰围/早餐前空腹
			if (NumberUtils.toDouble(value1, 0) > 0) {
				healthIndex.setValue1(value1);
				index = 1;
				value = NumberUtils.toDouble(value1, 0);
			}
			// 设置 舒张压/早餐后血糖
			if (NumberUtils.toDouble(value2, 0) > 0) {
				healthIndex.setValue2(value2);
				index = 2;
				value = NumberUtils.toDouble(value2, 0);
			}
			// 设置午餐前血糖
			if (NumberUtils.toDouble(value3, 0) > 0) {
				healthIndex.setValue3(value3);
				index = 3;
				value = NumberUtils.toDouble(value3, 0);
			}
			// 设置午餐后血糖
			if (NumberUtils.toDouble(value4, 0) > 0) {
				healthIndex.setValue4(value4);
				index = 4;
				value = NumberUtils.toDouble(value4, 0);
			}
			// 设置晚餐前血糖
			if (NumberUtils.toDouble(value5, 0) > 0) {
				healthIndex.setValue5(value5);
				index = 5;
				value = NumberUtils.toDouble(value5, 0);
			}
			// 设置晚餐后血糖
			if (NumberUtils.toDouble(value6, 0) > 0) {
				healthIndex.setValue6(value6);
				index = 6;
				value = NumberUtils.toDouble(value6, 0);
			}
			// 设置睡前血糖
			if (NumberUtils.toDouble(value7, 0) > 0) {
				healthIndex.setValue7(value7);
				index = 7;
				value = NumberUtils.toDouble(value7, 0);
			}
			// 设置健康指标类型(1血糖,2血压,3体重,4腰围)
			healthIndex.setType(type);
			// 设置记录时间
			if(type == 2){
				healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
			}else {
				healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
			}
			healthIndex.setSortDate(DateUtil.strToDateAppendNowTime(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
			// 保存到数据库
			healthIndex = healthIndexService.save(healthIndex, index, value,getUID());
			if (healthIndex == null) {
				return error(-1, "保存失败!");
			}
			return success("保存成功!");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "保存失败!");
		}
	}
            // 设置血糖/收缩压/体重/腰围/早餐前空腹
            if (NumberUtils.toDouble(value1, 0) > 0) {
                healthIndex.setValue1(value1);
                index = 1;
                value = NumberUtils.toDouble(value1, 0);
            }
            // 设置 舒张压/早餐后血糖
            if (NumberUtils.toDouble(value2, 0) > 0) {
                healthIndex.setValue2(value2);
                index = 2;
                value = NumberUtils.toDouble(value2, 0);
            }
            // 设置午餐前血糖
            if (NumberUtils.toDouble(value3, 0) > 0) {
                healthIndex.setValue3(value3);
                index = 3;
                value = NumberUtils.toDouble(value3, 0);
            }
            // 设置午餐后血糖
            if (NumberUtils.toDouble(value4, 0) > 0) {
                healthIndex.setValue4(value4);
                index = 4;
                value = NumberUtils.toDouble(value4, 0);
            }
            // 设置晚餐前血糖
            if (NumberUtils.toDouble(value5, 0) > 0) {
                healthIndex.setValue5(value5);
                index = 5;
                value = NumberUtils.toDouble(value5, 0);
            }
            // 设置晚餐后血糖
            if (NumberUtils.toDouble(value6, 0) > 0) {
                healthIndex.setValue6(value6);
                index = 6;
                value = NumberUtils.toDouble(value6, 0);
            }
            // 设置睡前血糖
            if (NumberUtils.toDouble(value7, 0) > 0) {
                healthIndex.setValue7(value7);
                index = 7;
                value = NumberUtils.toDouble(value7, 0);
            }
            // 设置健康指标类型(1血糖,2血压,3体重,4腰围)
            healthIndex.setType(type);
            // 设置记录时间
            if (type == 2) {
                healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
            } else {
                healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
            }
            healthIndex.setSortDate(DateUtil.strToDateAppendNowTime(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
            // 保存到数据库
            healthIndex = healthIndexService.save(healthIndex, index, value, getUID());
            if (healthIndex == null) {
                return error(-1, "保存失败!");
            }
            return success("保存成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "保存失败!");
        }
    }
	@RequestMapping(value = "addPatientHealthIndex",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("新增患者指标")
	public String addPatientHealthIndex(@ApiParam(name="data",value="指标数据",defaultValue = "{\"gi\":\"5.5\",\"gi_type\":\"1\"}")
										@RequestParam(value="data",required = true) String data,
										@ApiParam(name="type",value="指标类型",defaultValue = "1")
										@RequestParam(value="type",required = true) String type)
	{
		try {
			DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, getUID(), null);
			//血糖和血压需要校验
			if(type.equals("1")||type.equals("2"))
			{
				healthIndexService.verifyHealthIndex(obj.getId());
			}
    @RequestMapping(value = "addPatientHealthIndex", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("新增患者指标")
    public String addPatientHealthIndex(@ApiParam(name = "data", value = "指标数据", defaultValue = "{\"gi\":\"5.5\",\"gi_type\":\"1\"}")
                                        @RequestParam(value = "data", required = true) String data,
                                        @ApiParam(name = "type", value = "指标类型", defaultValue = "1")
                                        @RequestParam(value = "type", required = true) String type) {
        try {
            DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, getUID(), null);
            //血糖和血压需要校验
            if (type.equals("1") || type.equals("2")) {
                healthIndexService.verifyHealthIndex(obj.getId());
            }
			return success("新增患者指标成功!");
		}
		catch (Exception ex)
		{
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
            return success("新增患者指标成功!");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
	@RequestMapping(value = "verifyPatientHealthIndex",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("校验患者指标")
	public String verifyPatientHealthIndex(@ApiParam(name="id",value="指标id",defaultValue = "")
										@RequestParam(value="id",required = true) Long id)
	{
		try {
			healthIndexService.verifyHealthIndex(id);
    @RequestMapping(value = "verifyPatientHealthIndex", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("校验患者指标")
    public String verifyPatientHealthIndex(@ApiParam(name = "id", value = "指标id", defaultValue = "")
                                           @RequestParam(value = "id", required = true) Long id) {
        try {
            healthIndexService.verifyHealthIndex(id);
			return success("校验患者指标成功!");
		}
		catch (Exception ex)
		{
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
            return success("校验患者指标成功!");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
	/**
	 * 根据患者标志获取健康指标
@ -283,111 +485,112 @@ public class PatientHealthController extends BaseController {
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @param pagesize 页数
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("患者获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="type",value="指标类型",defaultValue = "1")
										   @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="start",value="开始时间",defaultValue = "2016-07-23 00:00:00")
										  @RequestParam(value="start",required = true) String start,
										  @ApiParam(name="end",value="结束时间",defaultValue = "2016-08-23 00:00:00")
										  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<DevicePatientHealthIndex> list = healthIndexService.findIndexByPatient(getUID(), type, start,end,page, pagesize);
			JSONArray jsonArray = new JSONArray();
			if (list != null) {
				for (DevicePatientHealthIndex model : list) {
					JSONObject modelJson = new JSONObject();
					modelJson.put("id", model.getId());
					modelJson.put("patient", model.getUser());
					modelJson.put("value1", model.getValue1());
					modelJson.put("value2", model.getValue2());
					modelJson.put("value3", model.getValue3());
					modelJson.put("value4", model.getValue4());
					modelJson.put("value5", model.getValue5());
					modelJson.put("value6", model.getValue6());
					modelJson.put("value7", model.getValue7());
					modelJson.put("type", model.getType());
					if(type == 2) {
						modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					}else{
						modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
					}
					modelJson.put("sortDate", DateUtil.dateToStrLong(model.getSortDate()));
					modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					jsonArray.put(modelJson);
				}
			}
    /**
     * 根据患者标志获取健康指标
     *
     * @param type     健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param pagesize 页数
     * @return 操作结果
     */
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("患者获取健康指标")
    public String getHealthIndexByPatient(@ApiParam(name = "type", value = "指标类型", defaultValue = "1")
                                          @RequestParam(value = "type", required = true) int type,
                                          @ApiParam(name = "start", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                          @RequestParam(value = "start", required = true) String start,
                                          @ApiParam(name = "end", value = "结束时间", defaultValue = "2016-08-23 00:00:00")
                                          @RequestParam(value = "end", required = true) String end,
                                          @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                          @RequestParam(value = "page", required = true) int page,
                                          @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                          @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            List<DevicePatientHealthIndex> list = healthIndexService.findIndexByPatient(getUID(), type, start, end, page, pagesize);
            JSONArray jsonArray = new JSONArray();
            if (list != null) {
                for (DevicePatientHealthIndex model : list) {
                    JSONObject modelJson = new JSONObject();
                    modelJson.put("id", model.getId());
                    modelJson.put("patient", model.getUser());
                    modelJson.put("value1", model.getValue1());
                    modelJson.put("value2", model.getValue2());
                    modelJson.put("value3", model.getValue3());
                    modelJson.put("value4", model.getValue4());
                    modelJson.put("value5", model.getValue5());
                    modelJson.put("value6", model.getValue6());
                    modelJson.put("value7", model.getValue7());
                    modelJson.put("type", model.getType());
                    if (type == 2) {
                        modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    } else {
                        modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
                    }
                    modelJson.put("sortDate", DateUtil.dateToStrLong(model.getSortDate()));
                    modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jsonArray.put(modelJson);
                }
            }
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
	/**
	 * 患者健康指标预警值查询
	 * @return
	 */
	@RequestMapping(value = "standard")
	@ResponseBody
	public String standard() {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(getUID());
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:3.9, max_value_1:6.1, min_value_2:4.4, max_value_2:7.8, type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:90, max_value_1:139, min_value_2:60, max_value_2:89, type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3体重,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败!");
		}
	}
    /**
     * 患者健康指标预警值查询
     *
     * @return
     */
    @RequestMapping(value = "standard")
    @ResponseBody
    public String standard() {
        try {
            JSONArray standardArray = new JSONArray();
            JSONArray userArray = new JSONArray();
            Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(getUID());
            Iterator<PatientHealthStandard> iterator = null;
            if (iterable != null) {
                iterator = iterable.iterator();
            }
            // 预警值未设置,返回默认值
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            // 默认血糖(餐前,餐后二小时)
            sb.append("{min_value_1:3.9, max_value_1:6.1, min_value_2:4.4, max_value_2:7.8, type:1},");
            // 默认血压(收缩压,舒张压)
            sb.append("{min_value_1:90, max_value_1:139, min_value_2:60, max_value_2:89, type:2}");
            sb.append("]");
            standardArray = new JSONArray(sb.toString());
            if (iterator != null) {
                while (iterator.hasNext()) {
                    PatientHealthStandard phs = iterator.next();
                    if (phs == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // 最低安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("min_value_1", phs.getMinValue1());
                    // 最高安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("max_value_1", phs.getMaxValue1());
                    // 最低安全值(血糖餐后\舒张压)
                    json.put("min_value_2", phs.getMinValue2());
                    // 最高安全值(血糖餐后\舒张压)
                    json.put("max_value_2", phs.getMaxValue2());
                    // 健康指标类型:1血糖,2血压,3体重,4腰围
                    json.put("type", phs.getType());
                    userArray.put(json);
                }
            }
            JSONObject json = new JSONObject();
            json.put("standard", standardArray);
            json.put("custom", userArray);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
}

+ 48 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/sign/FamilyContractController.java

@ -463,6 +463,38 @@ public class FamilyContractController extends BaseController {
        }
    }
    /**
     * 续签申请
     *
     * @param doctor     医生code
     * @return
     */
    @RequestMapping(value = "signRenew")
    @ResponseBody
    public String signRenew(@RequestParam(required = true) String doctor,
                            @RequestParam(required = true) String healthDoctor,
                            @RequestParam(required = true) String patient) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                return error(-1, "签约医生不能为空");
            }
            int result = familyContractService.signRenew(doctor,healthDoctor,patient);
            if (result == -1) {
                return error(-1, "用户信息查询失败");
            } else if (result == -2) {
                return error(-1, "用户已存在签约");
            } else if (result == -3) {
                return error(-1, "医生信息查询失败");
            } else {
                return write(200, "签约申请成功");
            }
        } catch (Exception e) {
            return error(-1, "签约申请失败");
        }
    }
    /**
     * 取消签约申请
     *
@ -612,4 +644,20 @@ public class FamilyContractController extends BaseController {
            return error(-1, "查询失败");
        }
    }
    /**
     * 验证是否允许签约
     * @param patient
     * @return
     */
    @RequestMapping(value = "/checkCanRenew", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String checkCanRenew(@RequestParam(required = true) String patient){
        try {
            JSONObject result = patientService.checkCanRenew(patient);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 1 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/sign/PatientSignController.java

@ -274,6 +274,7 @@ public class PatientSignController extends BaseController {
	public String getSigns() {
		try {
			JSONArray jsonArray  = signWebService.getSigns(getUID());
			//JSONArray jsonArray  = signWebService.getSigns("915cc456-5b1d-11e6-8344-fa163e8aee56");
			return write(200, "查询成功!", "data", jsonArray);
		} catch (Exception ex) {
			ex.printStackTrace();

+ 60 - 41
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java

@ -74,7 +74,7 @@ public class StatisticsController extends BaseController {
            if (index != null) {
                for (String idx : indexes) {
                    result.put("index_" + idx, statisticsService.getDateIncrementDetail(startDate, endDate, interval, area, level,idx,level2_type));
                    result.put("index_" + idx, statisticsService.getDateIncrementDetail(startDate, endDate, interval, area, level, idx, level2_type));
                }
            }
@ -119,14 +119,14 @@ public class StatisticsController extends BaseController {
    /**
     * 指标截止日期累积量
     *
     * @param endDate 结束时间
     * @param area 父code
     * @param level 等级  1 团队,2 机构,3 区,4 市
     * @param index 指标代码
     * @param level2_type  指标代码 例如性别 1 男 2 女  不传就返回男和女的总和
     * @param endDate     结束时间
     * @param area        父code
     * @param level       等级  1 团队,2 机构,3 区,4 市
     * @param index       指标代码
     * @param level2_type 指标代码 例如性别 1 男 2 女  不传就返回男和女的总和
     * @return
     */
    @RequestMapping("/total")
        @RequestMapping("/total")
    @ResponseBody
    public String getIndexTotal(@RequestParam(required = true) String endDate,
                                @RequestParam(required = true) String area,
@ -138,7 +138,7 @@ public class StatisticsController extends BaseController {
            JSONObject result = new JSONObject();
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsService.getTotalAmount(endDate, area, level, idx,level2_type));
                result.put("index_" + idx, statisticsService.getTotalAmount(endDate, area, level, idx, level2_type));
            }
            return write(200, "查询成功", "data", result);
@ -184,13 +184,13 @@ public class StatisticsController extends BaseController {
    /**
     * 指标截止日期增量
     *
     * @param endDate 结束时间
     * @param area 父code
     * @param level 等级  1 团队,2 机构,3 区,4 市
     * @param index 指标代码
     * @param sort 排序 1倒叙 2是 正序
     * @param endDate     结束时间
     * @param area        父code
     * @param level       等级  1 团队,2 机构,3 区,4 市
     * @param index       指标代码
     * @param sort        排序 1倒叙 2是 正序
     * @param lowLevel
     * @param level2_type  指标代码 例如性别 1 男 2 女  不传就返回男和女的总和
     * @param level2_type 指标代码 例如性别 1 男 2 女  不传就返回男和女的总和
     * @return
     */
    @RequestMapping("/lowlevel_total")
@ -207,7 +207,7 @@ public class StatisticsController extends BaseController {
            JSONObject result = new JSONObject();
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsService.getLowLevelTotalDetail(endDate, area, level, idx, sort, lowLevel,level2_type));
                result.put("index_" + idx, statisticsService.getLowLevelTotalDetail(endDate, area, level, idx, sort, lowLevel, level2_type));
            }
            return write(200, "查询成功", "data", result);
@ -240,39 +240,56 @@ public class StatisticsController extends BaseController {
            JSONArray returnJa = new JSONArray();
            List<JSONArray> jsonArrays = new ArrayList<>();
            JSONArray jsonArray1 = statisticsService.getLowLevelTotalDetail(endDate, area, level, indexes[0], sort, lowLevel,null);
            JSONArray jsonArray1 = statisticsService.getLowLevelTotalDetail(endDate, area, level, indexes[0], sort, lowLevel, null);
            jsonArrays.add(jsonArray1);
            JSONArray jsonArray2 = statisticsService.getLowLevelIncrementDetail(endDate, endDate, area, level, indexes[1], sort, lowLevel);
            jsonArrays.add(jsonArray2);
            //遍历合并2个指标中key值一样的
            for (int i = 0; i < jsonArrays.get(0).length(); i++) {
                if (jsonArrays.get(1).length() == 0) {
            if (jsonArrays.get(1).length() == 0) {
                //如果只有一个指标的时候 另外一个指标默认是0
                for (int i = 0; i < jsonArrays.get(0).length(); i++) {
                    //未回复咨询不存在的时候默认是0
                    JSONObject map1 = jsonArrays.get(0).getJSONObject(i);
                    String amount = map1.get("amount").toString() + ",0";
                    map1.put("amount", amount);
                    returnJa.put(map1);
                } else {
                    for (int j = 0; j < jsonArrays.get(1).length(); j++) {
                        JSONObject map1 = jsonArrays.get(0).getJSONObject(i);
                        JSONObject map2 = jsonArrays.get(1).getJSONObject(j);
                        String amount = "";
                        if (map1.get("code").equals(map2.get("code"))) {
                            amount = map1.get("amount").toString() + "," + map2.get("amount").toString();
                            map1.put("amount", amount);
                            returnJa.put(map1);
                        }
                    }
                }
            } else {
                //如果是2个指标的时候,分别放入map中,以减少查询次数
                Map<String,JSONObject> index1=new HashMap<>();
                Map<String,JSONObject> index2=new HashMap<>();
                for (int i = 0; i < jsonArrays.get(0).length(); i++) {
                    JSONObject map1 = jsonArrays.get(0).getJSONObject(i);
                    index1.put(map1.get("code").toString(),map1);
                }
                for (int i = 0; i < jsonArrays.get(1).length(); i++) {
                    JSONObject map1 = jsonArrays.get(1).getJSONObject(i);
                    index2.put(map1.get("code").toString(),map1);
                }
                for(Map.Entry<String , JSONObject> one:index1.entrySet()){
                    JSONObject map1 = one.getValue();
                    JSONObject map2 = index2.get(one.getKey());
                    String amount = map1.get("amount").toString() + "," + map2.get("amount").toString();
                    map1.put("amount", amount);
                    returnJa.put(map1);
                }
            }
            result.put("index_" + indexes[0], returnJa);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
        } catch (
                Exception e
                )
        {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
@ -450,6 +467,7 @@ public class StatisticsController extends BaseController {
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取三师转签或高危人群
     *
@ -572,13 +590,13 @@ public class StatisticsController extends BaseController {
    @RequestMapping("/Consulting_StatList")
    @ResponseBody
    public String getConsultingStatisticsList(@RequestParam(required = true) Integer level,
                                               @RequestParam(required = true) String area ,
                                               @RequestParam(required = false) String lowlevel) {
                                              @RequestParam(required = true) String area,
                                              @RequestParam(required = false) String lowlevel) {
        try {
            JSONObject data = statisticsService.getConsultingStatisticsList(level,area,lowlevel);
            if(data!=null){
            JSONObject data = statisticsService.getConsultingStatisticsList(level, area, lowlevel);
            if (data != null) {
                return write(200, "查询成功", "data", data);
            }else{
            } else {
                return error(-1, "查询失败");
            }
        } catch (Exception e) {
@ -599,12 +617,12 @@ public class StatisticsController extends BaseController {
    @RequestMapping("/Consulting_Title")
    @ResponseBody
    public String getConsultingTitle(@RequestParam(required = true) Integer level,
                                      @RequestParam(required = true) String area) {
                                     @RequestParam(required = true) String area) {
        try {
            JSONObject data = statisticsService.getConsultingTitle(level,area);
            if(data!=null){
            JSONObject data = statisticsService.getConsultingTitle(level, area);
            if (data != null) {
                return write(200, "查询成功", "data", data);
            }else{
            } else {
                return error(-1, "查询失败");
            }
        } catch (Exception e) {
@ -614,15 +632,16 @@ public class StatisticsController extends BaseController {
    /**
     * 获取回复数时间分布数
     *
     * @param level
     * @param area
     * @return
     */
    @RequestMapping("/getCoutListByTime")
    @ResponseBody
    public String getCoutListByTime(@RequestParam(required = true)String level,@RequestParam(required = true) String area){
    public String getCoutListByTime(@RequestParam(required = true) String level, @RequestParam(required = true) String area) {
        try {
            return write(200, "查询成功", "data", statisticsService.getCoutListByTime(level,area));
            return write(200, "查询成功", "data", statisticsService.getCoutListByTime(level, area));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }

+ 33 - 33
patient-co-wlyy/src/main/resources/application.properties

@ -53,45 +53,45 @@
##------------------------------------�����������ݿ�����------------------------------------#
#### mysql database setting
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
jdbc.username=root
jdbc.password=123456
#### health index
health.jdbc.driver=com.mysql.jdbc.Driver
health.jdbc.url=jdbc:mysql://172.19.103.77/device?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
health.jdbc.username=root
health.jdbc.password=123456
#### suifang
fv.jdbc.driver=com.mysql.jdbc.Driver
fv.jdbc.url=jdbc:mysql://172.19.103.77/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
fv.jdbc.username=root
fv.jdbc.password=123456
#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#jdbc.username=root
#jdbc.password=123456
#
##### health index
#health.jdbc.driver=com.mysql.jdbc.Driver
#health.jdbc.url=jdbc:mysql://172.19.103.77/device?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#health.jdbc.username=root
#health.jdbc.password=123456
#
##### suifang
#fv.jdbc.driver=com.mysql.jdbc.Driver
#fv.jdbc.url=jdbc:mysql://172.19.103.77/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#fv.jdbc.username=root
#fv.jdbc.password=123456
#### redis
redis.host=172.19.103.47
redis.port=6379
redis.password=
#---------------------------------���Ի������ݿ�����---------------------------------------#
###### mysql database setting
#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#jdbc.username=luofaqiang
#jdbc.password=luofaqiang
#
###### health index
#health.jdbc.driver=com.mysql.jdbc.Driver
#health.jdbc.url=jdbc:mysql://172.19.103.85/device?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#health.jdbc.username=luofaqiang
#health.jdbc.password=luofaqiang
#
###### suifang
#fv.jdbc.driver=com.mysql.jdbc.Driver
#fv.jdbc.url=jdbc:mysql://172.19.103.85/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#fv.jdbc.username=luofaqiang
#fv.jdbc.password=luofaqiang
##### mysql database setting
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
jdbc.username=linzhou
jdbc.password=linzhou
##### health index
health.jdbc.driver=com.mysql.jdbc.Driver
health.jdbc.url=jdbc:mysql://172.19.103.85/device?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
health.jdbc.username=linzhou
health.jdbc.password=linzhou
##### suifang
fv.jdbc.driver=com.mysql.jdbc.Driver
fv.jdbc.url=jdbc:mysql://172.19.103.85/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
fv.jdbc.username=linzhou
fv.jdbc.password=linzhou
#
###### redis
#redis.host=172.19.103.88

+ 2 - 2
patient-co-wlyy/src/main/resources/config/fdfs_client.conf

@ -6,10 +6,10 @@ http.anti_steal_token = no
http.secret_key = FastDFS1234567890
#-------------开发环境---------------#
tracker_server = 172.19.103.54:22122
#tracker_server = 172.19.103.54:22122
#-------------测试环境---------------#
#tracker_server = 172.19.103.54:22122
#-------------正式环境---------------#
#tracker_server = 192.168.0.239:22122
tracker_server = 192.168.0.239:22122

+ 4 - 2
patient-co-wlyy/src/main/resources/system.properties

@ -64,6 +64,8 @@ admin_token=0a5c5258-8863-4b07-a3f9-88c768528ab4
# 签约到期JOB触发时间
sign_end_job_trigger=0 0 0 * * ?
evaluate_score_job = 59 59 23 * * ?
#-------------------------开发环境配置-------------------------#
 服务器基本配置
server_ip=weixin.xmtyw.cn
@ -80,8 +82,8 @@ chat_server=http://weixin.xmtyw.cn/res/chat/
sign_check_upload=http://172.19.103.87:8011/wlyy_service
# IM配置
im_list_get=http://172.19.103.29:3008/
#im_list_get=http://192.168.131.102:3008/
#im_list_get=http://172.19.103.88:3000/
im_list_get=http://192.168.131.107:3000/
im_group_server=http://172.19.103.29:3000/api/v1/chats/gm
msg_push_server=http://172.19.103.29:3000/api/v1/chats/sm

+ 5 - 5
patient-co-wlyy/src/main/resources/weixin_menu.txt

@ -74,15 +74,15 @@
		   "name":"我的设备",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdsb%2fhtml%2fmy-equipments.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
		{
		   "type":"view",
		   "name":"我的预约",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdyy%2fhtml%2fmy-appointment.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
         	"type":"click",
         	"name":"操作说明",
         	"key":"caozuoshuoming"
        },
        {
        	 "type":"view",
        	 "name":"意见反馈",
        	 "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyjfk%2fhtml%2ffeedback.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	 ]
  }

+ 11 - 0
readme.MD

@ -0,0 +1,11 @@
patient-co-analysis  数据采集分析项目
    主要功能是监听kafka解析日志并且入库到mongodb
    
patient-co-figure 居民画像项目
    
patient-co-statistics 统计项目
    生成各种类统计指标
    
patient-co-wlyy
    i健康后台项目 包括医生端与患者端