Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy/patient-co-management into dev

Sand 8 years ago
parent
commit
5c1b633db7
84 changed files with 7674 additions and 2121 deletions
  1. 6 6
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/config/war/ServletInitializer.java
  2. 69 4
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java
  3. 23 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkTimeDao.java
  4. 40 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkWeekDao.java
  5. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/QuartzJobConfigDao.java
  6. 43 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/dataFilter/SignDataFilter.java
  7. 6 2
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/DBStorage.java
  8. 6 2
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/RedisStorage.java
  9. 116 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/AgeAndDiseaseJob.java
  10. 25 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/Constant.java
  11. 1 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ConsultJob.java
  12. 41 1
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/CurrentDayAllQuotaJob.java
  13. 33 3
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/check/CheckSignJob.java
  14. 193 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/check/ReportAllLogJob.java
  15. 30 12
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/message/HealthMessageJob.java
  16. 123 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/message/NoticeJob.java
  17. 116 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkTime.java
  18. 70 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkWeek.java
  19. 306 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/DoctorWorkTimeService.java
  20. 47 6
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/JobService.java
  21. 173 0
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/task/PushMsgTask.java
  22. 2 5
      patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/IdCardUtil.java
  23. 16 4
      patient-co-statistics/src/main/resources/application.yml
  24. 5 1
      patient-co-wlyy/pom.xml
  25. 1 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/Consult.java
  26. 10 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/ConsultTeam.java
  27. 9 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/doctor/profile/Doctor.java
  28. 10 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticle.java
  29. 88 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleDoctor.java
  30. 64 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleLabel.java
  31. 84 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleOpHistory.java
  32. 35 16
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamDao.java
  33. 1 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorAdminTeamDao.java
  34. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorDao.java
  35. 4 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamMemberDao.java
  36. 9 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleDao.java
  37. 26 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleDoctorDao.java
  38. 18 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleLabelDao.java
  39. 18 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleOpHistoryDao.java
  40. 6 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticlePatientDao.java
  41. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java
  42. 154 6
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  43. 7 5
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java
  44. 109 17
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java
  45. 61 2
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyMemberService.java
  46. 136 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleDoctorService.java
  47. 105 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleLabelService.java
  48. 95 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleOpHistoryService.java
  49. 96 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticlePatientService.java
  50. 50 38
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/HealthEduArticleService.java
  51. 3 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java
  52. 38 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/hospital/HospitalDeptService.java
  53. 50 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/hospital/HospitalService.java
  54. 217 207
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  55. 76 67
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/DrugService.java
  56. 832 103
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/EhrService.java
  57. 50 17
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/ExpensesRemindService.java
  58. 106 1
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  59. 462 35
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsAllService.java
  60. 62 10
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsService.java
  61. 651 20
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/talk/TalkGroupService.java
  62. 22 5
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/team/DrHealthTeamService.java
  63. 7 12
      patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/SMSService.java
  64. 51 3
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/BaseController.java
  65. 20 4
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java
  66. 17 7
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java
  67. 116 8
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java
  68. 74 3
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultController.java
  69. 759 656
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/discussion/DoctorDiscussionGroupController.java
  70. 251 25
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java
  71. 8 2
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/DoctorPatientGroupController.java
  72. 34 42
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java
  73. 52 14
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/sign/DoctorFamilyContractController.java
  74. 7 34
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/team/AdminTeamController.java
  75. 53 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/team/SignTeamController.java
  76. 29 13
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/account/PatientController.java
  77. 683 645
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java
  78. 7 3
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/family/FamilyMemberController.java
  79. 93 6
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/HealthEduArticleController.java
  80. 41 0
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/sign/FamilyContractController.java
  81. 87 24
      patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java
  82. 4 4
      patient-co-wlyy/src/main/resources/system.properties
  83. 11 6
      patient-co-wlyy/src/main/resources/weixin_menu.txt
  84. 8 8
      patient-co-wlyy/src/main/webapp/WEB-INF/web.xml

+ 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);
//    }
//}

+ 69 - 4
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java

@ -224,8 +224,8 @@ public class JobController extends BaseController {
     *
     * @return
     */
   // @ApiOperation(value = "启动檢查的任务")
  //  @RequestMapping(value = "startCheckSignJob", method = RequestMethod.GET)
    @ApiOperation(value = "启动檢查的任务")
    @RequestMapping(value = "startCheckSignJob", method = RequestMethod.GET)
    public String startCheckSignJob() {
        try {
            jobService.startCheckSignJob();
@ -240,8 +240,8 @@ public class JobController extends BaseController {
     *
     * @return
     */
   // @ApiOperation(value = "停止檢查的任务")
   // @RequestMapping(value = "stopCheckSignJob", method = RequestMethod.GET)
    @ApiOperation(value = "停止檢查的任务")
    @RequestMapping(value = "stopCheckSignJob", method = RequestMethod.GET)
    public String stopCheckSignJob() {
        try {
            jobService.stopCheckSignJob();
@ -402,4 +402,69 @@ public class JobController extends BaseController {
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动每天的统计报表任务
     *
     * @return
     */
    @ApiOperation(value = "启动每天的统计报表任务")
    @RequestMapping(value = "startEveryDayReportJob", method = RequestMethod.GET)
    public String startEveryDayReportJob() {
        try {
            jobService.startEveryDayReportJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止每天的统计报表任务
     *
     * @return
     */
    @ApiOperation(value = "停止每天的统计报表任务")
    @RequestMapping(value = "stopEveryDayReportJob", method = RequestMethod.GET)
    public String stopEveryDayReportJob() {
        try {
            jobService.stopEveryDayReportJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "启动通知任务")
    @RequestMapping(value = "startNoticeJob", method = RequestMethod.GET)
    public String startNoticeJob() {
        try {
            jobService.startNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "停止通知任务")
    @RequestMapping(value = "stopNoticeJob", method = RequestMethod.GET)
    public String stopNoticeJob() {
        try {
            jobService.stopNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 23 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkTimeDao.java

@ -0,0 +1,23 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkTime;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by lyr on 2016/08/19.
 */
public interface DoctorWorkTimeDao extends PagingAndSortingRepository<WlyyDoctorWorkTime, Long>, JpaSpecificationExecutor<WlyyDoctorWorkTime> {
    /**
     * 查询医生工作时间
     *
     * @param doctor
     * @return
     */
    @Query("select a from WlyyDoctorWorkTime a where a.doctor = ?1")
    WlyyDoctorWorkTime findDoctorWorkTime(String doctor);
}

+ 40 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/dao/DoctorWorkWeekDao.java

@ -0,0 +1,40 @@
package com.yihu.wlyy.statistics.dao;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkWeek;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr on 2016/08/19.
 */
public interface DoctorWorkWeekDao extends PagingAndSortingRepository<WlyyDoctorWorkWeek, Long>, JpaSpecificationExecutor<WlyyDoctorWorkWeek> {
    /**
     * 查询医生排班列表
     *
     * @param doctor
     * @return
     */
    @Query("select a from WlyyDoctorWorkWeek a where a.doctor = ?1")
    List<WlyyDoctorWorkWeek> findDoctorWorkWeeks(String doctor);
    /**
     * 查询医生某天排班信息
     *
     * @param doctor
     * @param week
     * @return
     */
    @Query("select a from WlyyDoctorWorkWeek a where a.doctor = ?1 and a.week = ?2")
    WlyyDoctorWorkWeek findDoctorWorkWeek(String doctor, String week);
    /**
     * 删除医生的排班信息
     *
     * @param doctor
     */
    void deleteByDoctor(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)  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)  and a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")

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

@ -36,6 +36,7 @@ public class SignDataFilter {
    public static String level2Expenses="4";//费用
    public static String level2Health="5";//健康服务分布
    public static String level2Age2="6";//年龄
    public static String level2AgeDisease="7";//年龄疾病
    public static String level3Disease="1";//疾病分组
@ -319,11 +320,53 @@ public class SignDataFilter {
                     returnLevel2Key = getAge2(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄疾病
                 case "7" :{
                     returnLevel2Key = getAgeDisease(signFamily);
                     return returnLevel2Key;
                 }
             }
        }
        return returnLevel2Key;
    }
    private String getAgeDisease(SignFamily signFamily) {
        //得到患者年龄
        StringBuffer returnLevel2KeyBuffer=new StringBuffer("0");
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        if(age>=65){
            returnLevel2KeyBuffer.append(",3");
        }
        //疾病标签
        String returnLevel2KeyTemp = "";
        boolean hasGXY=false;//有高血压
        boolean hasTNB=false;//糖尿病
        //得到患者的疾病标签
        List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
        if(diseaseList!=null&&diseaseList.size()>0){
            for (String diseaseCode:diseaseList){
                if("1".equals(diseaseCode)){//判斷是否有高血壓
                    returnLevel2KeyTemp="1";
                    hasGXY=true;
                }
                if("2".equals(diseaseCode)){//判斷是否有糖尿病
                    returnLevel2KeyTemp="2";
                    hasTNB=true;
                }
            }
        }
        if (hasTNB&&hasGXY){
            returnLevel2KeyTemp="1,2";
        }
        if(!StringUtils.isEmpty(returnLevel2KeyTemp)){
            returnLevel2KeyBuffer.append(","+returnLevel2KeyTemp);
        }
        return returnLevel2KeyBuffer.toString();
    }
    private String getAge2(SignFamily signFamily) {
        String returnLevel2Key;
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());

+ 6 - 2
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/DBStorage.java

@ -142,7 +142,7 @@ public class DBStorage   {
     * @param day
     * @param wlyyQuota
     * @param foreachNum 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布  6年龄2  7 年龄疾病
     */
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum,Integer type) throws Exception{
        Integer start=1;
@ -155,7 +155,7 @@ public class DBStorage   {
     * @param day
     * @param wlyyQuota
     * @param foreachNum 如果start是默认的 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布  6年龄2  7 年龄疾病
     * @param start 起始位置 默认是1
     */
    public List<WlyyQuotaResult> getLevel2(List<Map<String, Map<String, List<ETLModel>>>> data, String day, WlyyQuotaVO wlyyQuota,Integer foreachNum,Integer type,Integer start)throws Exception {
@ -812,6 +812,10 @@ public class DBStorage   {
                //年龄2
                return Constant.getLevelAge2(i);
            }
            case  7:{
                //年龄疾病
                return Constant.getLevelAgeDiseaseName(i);
            }
            default:{
                return "";
            }

+ 6 - 2
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/etl/storage/RedisStorage.java

@ -120,7 +120,7 @@ public class RedisStorage {
     * @param data
     * @param wlyyQuotaId
     * @param foreachNum 标识二级维度循环的次数  例如 年龄就传6  性别就传3
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布
     * @param type 1 性别 2 年龄 3 用户分组 4.签约费用 5 健康分布 6繳費未交費 7年齡疾病
     * @param start 循环开始
     */
    public void saveByLevel2(List<Map<String, Map<String, List<ETLModel>>>> data,List<Map<String, Map<String, List<ETLModel>>>> deleteData, String wlyyQuotaId,Integer foreachNum,Integer type,Integer start) throws Exception {
@ -1183,9 +1183,13 @@ public class RedisStorage {
                return Constant.getlevelHealthFbName(i);
            }
            case  6:{
                //疾病
                //繳費未交費
                return Constant.getLevelExpenseName(i);
            }
            case  7:{
                //疾病年齡
                return Constant.getLevelAgeDiseaseName(i);
            }
            default:{
                return "";
            }

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

@ -0,0 +1,116 @@
package com.yihu.wlyy.statistics.job.business;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.Level2Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
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.quartz.Calendar;
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.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Administrator on 2016.11.01.
 *  年龄和疾病
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution
public class AgeAndDiseaseJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;
    String yesterday;
    String daybefore;
    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){
            e.printStackTrace();
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }
    /**
     * 计算指标
     */
    private void computequota()throws Exception {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 17 + "'");
        try{
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2AgeDisease,cacheModel.getSql(),yesterday);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= level2Role.elt(returnDatas);;
            //保存数据
            dbStorage.saveByLevel2(level2Data,yesterday,wlyyQuota,3,7);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public String getYesterday() {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.add(java.util.Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
}

+ 25 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/Constant.java

@ -75,6 +75,15 @@ public class Constant {
    public static String level_health_fb_3_name="高危人群";
    public static String level_health_fb_4_name="恢复期人群";
    //二姐维度的年龄疾病
    public static String level_age_disease_1="1";
    public static String level_age_disease_2="2";
    public static String level_age_disease_3="3";
    public static String level_age_disease_1_name="高血压";
    public static String level_age_disease_2_name="糖尿病";
    public static String level_age_disease_3_name="65岁以上";
    //三级维度的疾病
    public static String level_disease_1="1";
    public static String level_disease_2="2";
@ -85,6 +94,8 @@ public class Constant {
    public static String level_disease_3_name="糖尿病和高血压";
    public static String level_disease_4_name="健康人群";
    public static String getlevelHealthFbName(String key){
        switch (key){
            case "1":{
@ -217,5 +228,18 @@ public class Constant {
        }
        return "";
    }
    public static String getLevelAgeDiseaseName(String key){
        switch (key){
            case "1":{
                return level_age_disease_1_name;
            }
            case "2":{
                return level_age_disease_2_name;
            }
            case "3":{
                return level_age_disease_3_name;
            }
        }
        return "";
    }
}

+ 1 - 1
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/business/ConsultJob.java

@ -87,7 +87,7 @@ public class ConsultJob implements Job {
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            String sql=" select admin_team_code,id from wlyy_consult_team a where a.type=2 and a.czrq>='"+daybefore+ Constant.quota_date_last+"' and a.czrq< '"+yesterday+ Constant.quota_date_last+"'";
            String sql=" select admin_team_code,id from wlyy_consult_team a where  a.czrq>='"+daybefore+ Constant.quota_date_last+"' and a.czrq< '"+yesterday+ Constant.quota_date_last+"'";
            //抽取數據
            List<ConsultTeam> consultTeams= dbExtract.extract(ConsultTeam.class,sql);
            //過濾數據

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

@ -169,6 +169,7 @@ public class CurrentDayAllQuotaJob implements Job {
        computequota_16_1(sql,signFamilies,null);//统计今天的签约数的扣费钱 1
        computequota_15(sql,signFamilies,null);//统计今天的健康分布统计
        //computequota_16_0(sql,signFamilies,null);//统计今天的签约数的未扣费 0
        computequota_17(sql,signFamilies,null);//统计今天的年龄疾病
        quartzJobLog.setJobContent(allContent.toString());
        quartzJobLog.setJobName("实时统计");
@ -177,6 +178,8 @@ public class CurrentDayAllQuotaJob implements Job {
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLogDao.save(quartzJobLog);
        initCurrentExpire();//初始化生命周期
        for (String key :RedisStorage.keys){
            redisTemplate.expire(key, Integer.valueOf(currentExpire), TimeUnit.HOURS);//2小时过期
        }
@ -189,6 +192,43 @@ public class CurrentDayAllQuotaJob implements Job {
        redisTemplate.opsForValue().set("quota:timeKey",RedisStorage.timeKey);
    }
    private void initCurrentExpire() {
        try{
            if(StringUtils.isEmpty(currentExpire)){
                currentExpire="2";//默认是2小时
            }
            if(!org.apache.commons.lang.StringUtils.isNumeric(currentExpire)){
                currentExpire="2";//默认是2小时
            }else{
                Integer cout =Integer.valueOf(currentExpire);
                if(cout<=0){
                    currentExpire="2";//默认是2小时
                }
            }
        }catch (Exception e){
            currentExpire="2";//默认是2小时
        }
    }
    private void computequota_17(String sql, List<SignFamily> signFamilies, Object o) {
        String quotaId="17";
        try{
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2AgeDisease,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据 1 表示:从1开始循环 6表示:循环6次 3表示 2级维度是 3
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,3,7,1);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------17----------");
    }
    private void computequota_16_1(String sql,List<SignFamily> signFamilies_1,List<SignFamily> deleteSignFamilies) {
        String quotaId="16";
        try{
@ -375,7 +415,7 @@ public class CurrentDayAllQuotaJob implements Job {
        String quotaId="3";
        try{
            //找出今天的咨询信息
            String sql=" select * from wlyy_consult_team a where a.type=2  and a.czrq>= '"+now+"'and a.czrq< '"+tomorrow+"'";
            String sql=" select * from wlyy_consult_team a where  a.czrq>= '"+now+"'and a.czrq< '"+tomorrow+"'";
            //抽取數據
            List<ConsultTeam> consultTeams= SpringUtil.getBean(DBExtract.class).extract(ConsultTeam.class,sql);
            //過濾數據

+ 33 - 3
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/check/CheckSignJob.java

@ -14,6 +14,7 @@ import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
@ -41,25 +42,54 @@ public class CheckSignJob implements Job{
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            String timeKey=redisTemplate.opsForValue().get("quota:timeKey");
            long produceTime=  redisTemplate.getExpire("quota:16:4:350200:"+timeKey);
            long now =new Date().getTime();
            long nh = 1000*60*60;//一小时的毫秒数
            long nm = 60;//一分钟的毫秒数
            //如果当前时间扣掉生成时间大于2小时
            if((now-Long.valueOf(timeKey))/nh>2){
                sendEmail("实时统计失败,redis数据生成失败,redis数据生成时间時間:"+ DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+",当前系统时间:"+ DateUtil.dateToStrLong(new Date())+",key剩下多少时间:"+ (produceTime/3600)+"小时"+(produceTime%3600/60)+"分钟"+(produceTime%3600%60)+"秒");
            }
            //判断当前时间是不是
            if(!redisTemplate.hasKey("quota:16:4:350200:"+timeKey)){
                //发送邮件给管理员
               // sendEmail();
               sendEmail("实时统计失败,redis数据生成失败,redis数据为空時間:"+ DateUtil.dateToStrLong(new Date()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void sendEmail() throws Exception {
    private void sendEmail(String text) throws Exception {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);//发送者.
        message.setSubject("实时统计失败");//邮件主题.
        message.setText("实时统计失败,redis数据生成失败 時間:"+ DateUtil.dateToStrLong(new Date()));//邮件内容.
        message.setText(text);//邮件内容.
        String[] tos=to.split(",");
        message.setTo(tos);
        javaMailSender.send(message);
    }
    public void dateDiff(String startTime, String endTime, String format) throws Exception{
        //按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000*24*60*60;//一天的毫秒数
        long nh = 1000*60*60;//一小时的毫秒数
        long nm = 1000*60;//一分钟的毫秒数
        long ns = 1000;//一秒钟的毫秒数long diff;try {
        //获得两个时间的毫秒时间差异
        long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        long day = diff/nd;//计算差多少天
        long hour = diff%nd/nh;//计算差多少小时
        long min = diff%nd%nh/nm;//计算差多少分钟
        long sec = diff%nd%nh%nm/ns;//计算差多少秒//输出结果
        System.out.println("时间相差:"+day+"天"+hour+"小时"+min+"分钟"+sec+"秒。");
    }
    public static void main(String[] args) {
        Long produceTime=47265L;
        System.out.println( );
    }
}

+ 193 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/check/ReportAllLogJob.java

@ -0,0 +1,193 @@
package com.yihu.wlyy.statistics.job.check;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by Administrator on 2016.10.31.
 * 每天的报表任务
 */
@Component
@Scope("prototype")
public class ReportAllLogJob implements Job {
    public static String jobKey="Report_All_LOG_JOB";
    public static String cron="0 55 0 * * ?";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.to}")
    private String to;
    @Autowired
    private CachePool cachePool;
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            String timeKey=redisTemplate.opsForValue().get("quota:timeKey");
            long produceTime=  redisTemplate.getExpire("quota:16:4:350200:"+timeKey);
            String date=getYesterday();
            //当前试试统计的key
            StringBuffer sb=new StringBuffer("<html><head><meta charset=\"UTF-8\"></head><body>");
            sb.append("<table width=\"100%\" border=\"blue solid 1px\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#FF9933\"  id=\"size\">\n");
            //报表时间
            sb.append("<tr><td>报表数据时间</td><td>"+date+"</td></tr>");//添加当前实时统计信息报表
            sb.append("<tr><td>报表生成时间</td><td>"+DateUtil.dateToStrLong(new Date())+"</td></tr>");//添加当前实时统计信息报表
            //今天签约信息
            String sqlCount="select count(id) from wlyy_sign_family a  where  status in(1,2) and a.type =2 and expenses_status=1 and a.expenses_time< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.expenses_time>= '"+getYesterday(-2)+ Constant.quota_date_last+"'";
            Integer count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增签约数</td><td>"+count+"个</td></tr>");
            //今天解约信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and a.status in(-3,-4) and a.apply_unsign_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.apply_unsign_date>= '"+getYesterday(-2)+ Constant.quota_date_last+"'";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增解约数</td><td>"+count+"个</td></tr>");
            //今天待签约信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2  and a.status=0 and  a.patient_apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"'  and  a.patient_apply_date >= '"+getYesterday(-2)+ Constant.quota_date_last+"'  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增待签约数</td><td>"+count+"个</td></tr>");
            //今天改签信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and a.status =100 and  a.patient_apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.expenses_status=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增改签数</td><td>"+count+"个</td></tr>");
            //今天未交费数目
            sqlCount= " select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and  a.apply_date>= '"+getYesterday(-2)+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增未缴费数</td><td>"+count+"个</td></tr>");
            //截止到今天的签约信息
            sb.append("<tr><td>截止到"+date+" 的签约数</td><td>"+cachePool.getSignFamilysWithExpenseStatus1ByDate(date).getSignFamilies().size()+"个</td></tr>");
            //截止到今天未交费数目
            sqlCount= " select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 的未缴费数</td><td>"+count+"个</td></tr>");
            //系统共有患者多少个
            sqlCount= " select count(id) from wlyy_patient  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 的患者用户数</td><td>"+count+"个</td></tr>");
            //系统共有多少个患者有签约
            sb.append("<tr><td>截止到"+date+" 签约患者数</td><td>"+cachePool.getSignFamilysWithExpenseStatus1ByDate(date).getSignFamilies().size()+"个</td></tr>");
            //系统共有多少个健康管理师
            sqlCount= " select count(id) from wlyy_doctor where level=3  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的健康管理师数</td><td>"+count+"个</td></tr>");
            //系统共有多少个全科医生
            sqlCount= " select count(id) from wlyy_doctor where level=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的全科医生数</td><td>"+count+"个</td></tr>");
            //系统共有多少个专科医生
            sqlCount= " select count(id) from wlyy_doctor where level=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的专科医生数</td><td>"+count+"个</td></tr>");
            //系统共有多少个医生行政团队
            sqlCount= " select count(id) from wlyy_admin_team where available=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的行政团队数</td><td>"+count+"个</td></tr>");
            //系统患者总共登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 患者总共登录成功次数</td><td>"+count+"次</td></tr>");
            //系统患者总共登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 患者总共登录失败次数</td><td>"+count+"次</td></tr>");
            //系统医生总共登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 医生总共登录成功次数</td><td>"+count+"次</td></tr>");
            //系统医生总共登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 医生总共登录失败次数</td><td>"+count+"次</td></tr>");
            //系统患者昨天登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=1 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 患者登录成功次数</td><td>"+count+"次</td></tr>");
            //系统患者昨天登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=1 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 患者登录失败次数</td><td>"+count+"次</td></tr>");
            //系统医生昨天登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=2 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 医生登录成功次数</td><td>"+count+"次</td></tr>");
            //系统医生昨天登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=2 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 医生登录失败次数</td><td>"+count+"次</td></tr>");
            //今天实时统计执行的次数
            sqlCount= " select count(a.id) from wlyy_job_log a where a.job_id=11 and a.job_start_time>= '"+getYesterday(-1)+ " 00:00:00'and a.job_start_time<=  '"+getYesterday(-1)+" 23:59:59 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 实时统计执行的次数</td><td>"+count+"次</td></tr>");
            sb.append("<tr><td>最近执行的实时统计的时间:</td><td>"+DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+"</td></tr>");
            //最新的实时统计信息
            String current="最新的redis数据生成时间時間:"+ DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+",当前系统时间:"+ DateUtil.dateToStrLong(new Date())+",最新的key剩下多少时间:"+ (produceTime/3600)+"小时"+(produceTime%3600/60)+"分钟"+(produceTime%3600%60)+"秒";
            sb.append("<tr><td>当前实时统计信息</td><td>"+current+"</td></tr>");//添加当前实时统计信息报表
            sb.append("</table></body></html>");
            sendEmail(sb.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void sendEmail(String text) throws Exception {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(text, "text/html;charset=utf-8");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        String[] tos=to.split(",");
        MimeMessage mimeMessage= javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("实时统计报表");
        messageHelper.setFrom(from);
        mimeMessage.setContent(mp);
        messageHelper.setTo(tos);
        javaMailSender.send(mimeMessage);
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public String getYesterday(int count) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, count);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
}

+ 30 - 12
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/message/HealthMessageJob.java

@ -6,7 +6,9 @@ import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
@ -28,7 +30,7 @@ import java.util.*;
@Scope("prototype")
public class HealthMessageJob implements Job {
    public static String jobKey="Health_Message_JOB";
    public static String cron="0 0 17 * * ?";
    public static String cron="0 0 8 * * ?";
    @Autowired
@ -57,15 +59,15 @@ public class HealthMessageJob implements Job {
                now=getYesterday(0,new Date());
            }
            //删除原来的数据
            String deleteSql="delete from wlyy_message where type=3 and czrq >= '"+yesterday+" 17:00:00'and czrq <= '"+now+" 17:00:00'";
            String deleteSql="delete from wlyy_message where type=3 and czrq >= '"+yesterday+" 00:00:00'and czrq <= '"+now+" 00:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql="select doctor,doctor_name from wlyy_sign_family " +
                    " where  status >0 and type='2' and expenses_status='1'  " +
                    " and expenses_time >='"+yesterday+" 17:00:00' and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '')" ;
                    " and expenses_time >='"+yesterday+" 00:00:00' and expenses_time<'"+now+" 00:00:00' and  (doctor_health is null or doctor_health = '')" ;
            String countSql="select count(id) from wlyy_sign_family " +
                    " where  status >0 and type='2' and expenses_status='1'  " +
                    " and expenses_time >='"+yesterday+" 17:00:00' and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '')" ;
                    " and expenses_time >='"+yesterday+" 00:00:00' and expenses_time<'"+now+" 00:00:00' and  (doctor_health is null or doctor_health = '')" ;
            List<SignFamily> signFamilyList=dbExtract.extractByPage(SignFamily.class,sql,countSql,true);
            Map<String,List<SignFamily>> signFamilyMap=new HashMap<String,List<SignFamily>>();
            for(int i=0;i<signFamilyList.size();i++){
@ -78,10 +80,11 @@ public class HealthMessageJob implements Job {
                    signFamilyMap.put(signFamilyTemp.getDoctor(),signFamilies);
                }
            }
            JSONArray jsonArray=new JSONArray();
            for(Map.Entry<String,List<SignFamily>> entry:signFamilyMap.entrySet()){
                 countSql="select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2' and expenses_status='1'  " +
                        "  and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '') and doctor='"+entry.getKey()+"'" ;
                        "  and expenses_time<'"+now+" 00:00:00' and  (doctor_health is null or doctor_health = '') and doctor='"+entry.getKey()+"'" ;
                Integer allCount=jdbcTemplate.queryForObject(countSql,Integer.class);
                Message message=new Message();
@ -90,20 +93,35 @@ public class HealthMessageJob implements Job {
                message.setOver("0");
                message.setDel("1");
                message.setSender("system");
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd").parse(now));
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday+" 23:59:00"));
                message.setState(1);
                message.setTitle("新增系统消息");
                SimpleDateFormat dateFormat=new SimpleDateFormat("MM月dd日");
                String date=  dateFormat.format(new Date());
                message.setContent(date+"新增"+entry.getValue().size()+"个签约居民待分配健管师,目前共"+allCount+"人待处理");
                String title="新增系统消息";
                message.setTitle(title);
                SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateFormat2=new SimpleDateFormat("MM月dd日");
                String content=dateFormat2.format(dateFormat1.parse(yesterday))+"新增"+entry.getValue().size()+"个签约居民待分配健管师,目前共"+allCount+"人待处理";
                message.setContent(content);
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(entry.getKey());
                messageDao.save(message);
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", entry.getKey());
                json.put("type", "D_NH_01");
                json.put("title", title);
                json.put("msg", content);
                json.put("data", "");
                jsonArray.add(json);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成"+now+"的健康管理师消息成功");
            quartzJobLog.setJobContent("生成"+yesterday+"的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            dbStorage.saveLog(quartzJobLog);
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
        }catch (Exception e){
            e.printStackTrace();
        }

+ 123 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/job/message/NoticeJob.java

@ -0,0 +1,123 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.job.business.QuartzHelper;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.service.DoctorWorkTimeService;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/11/7.
 */
@Component
@Scope("prototype")
public class NoticeJob implements Job {
    public static String jobKey = "Notice_JOB";
    public static String jobCron = "0 0 9,15,20 * * ?"; //每天9点,15点,20 点执行一次
    private static String[] noticeKey = {"no", "NO_ZX", "NO_QY", "NO_JKZD"};
    private static String[] noticeTitle = {"no", "咨询消息", "签约消息", "体征指标"};
    private static String[] noticeContent = {"no", "您有[SIZE]条新的咨询消息", "您有[SIZE]条新的签约消息", "您有[SIZE]条新的体征指标"};
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private QuartzJobLogDao dbStorage;
    @Autowired
    private DoctorDao doctorDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(jobKey);
        quartzJobLog.setJobName(jobKey);
        try {
            List<Doctor> doctors = doctorDao.findAllDoctors();
            //得到所有未发送的医生的通知
            Map<String, Map<String, Integer>> maps = new HashMap<>();
            //发送通知
            for (Doctor doctor : doctors) {
                //判断医生是不是在工作时间内
                if ("1".equals(doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).get("status"))) {
                    Map<String,Integer> map=new HashMap<>();
                    //得到医生多少条咨询消息
                    Integer size=getDoctorMesssageCount(doctor.getCode(),1);
                    addData(map, size, "1");
                    //得到医生多少条签约消息
                    size=getDoctorMesssageCount(doctor.getCode(),2);
                    addData(map, size, "2");
                    //得到医生多少条体征消息
                    size=getDoctorMesssageCount(doctor.getCode(),3);
                    addData(map, size, "3");
                    if(map.size()>0){
                        maps.put(doctor.getCode(),map);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            //发送通知
            for (Map.Entry<String, Map<String, Integer>> entry : maps.entrySet()) {
                for (Map.Entry<String, Integer> entry1 : entry.getValue().entrySet()) {
                    // 异常通知
                    JSONObject json = new JSONObject();
                    json.put("receiver", entry.getKey());
                    json.put("type", noticeKey[Integer.valueOf(entry1.getKey())]);
                    json.put("title", noticeTitle[Integer.valueOf(entry1.getKey())]);
                    json.put("msg", noticeContent[Integer.valueOf(entry1.getKey())].replace("[SIZE]", entry1.getValue() + ""));
                    json.put("data", "");
                    jsonArray.add(json);
                }
            }
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知成功");
            quartzJobLog.setJobType("1");
            dbStorage.save(quartzJobLog);
        } catch (Exception e) {
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知失败");
            quartzJobLog.setJobType("0");
            dbStorage.save(quartzJobLog);
            e.printStackTrace();
        }
    }
    private void addData(Map<String, Integer> map, Integer size, String key) {
        if (size > 0) {
            map.put(key, size);
        }
    }
    /**
     * 得到医生的未读数目
     * @param code 医生code
     * @param type 1是咨询 2个签约 3是体征
     * @return
     */
    private Integer getDoctorMesssageCount(String code, int type) {
        return 0;
    }
}

+ 116 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkTime.java

@ -0,0 +1,116 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by lyr on 2016/08/19.
 */
@Entity
@Table(name = "wlyy_doctor_work_time")
public class WlyyDoctorWorkTime extends IdEntity {
    // 医生标识
    private String doctor;
    // 医生姓名
    private String doctorName;
    // 接收咨询 0不接受 1接受
    private String receiveConsult;
    // 名医咨询次数
    private Integer famousConsultTimes;
    // 上午开始时间
    private String morningBegin;
    // 上午结束时间
    private String morningEnd;
    // 下午开始时间
    private String afternoonBegin;
    // 下午结束时间
    private String afternoonEnd;
    // 晚上开始时间
    private String nightBegin;
    // 晚上结束时间
    private String nightEnd;
    // 更新时间
    private Date czrq;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getReceiveConsult() {
        return receiveConsult;
    }
    public void setReceiveConsult(String receiveConsult) {
        this.receiveConsult = receiveConsult;
    }
    public Integer getFamousConsultTimes() {
        return famousConsultTimes;
    }
    public void setFamousConsultTimes(Integer famousConsultTimes) {
        this.famousConsultTimes = famousConsultTimes;
    }
    public String getMorningBegin() {
        return morningBegin;
    }
    public void setMorningBegin(String morningBegin) {
        this.morningBegin = morningBegin;
    }
    public String getMorningEnd() {
        return morningEnd;
    }
    public void setMorningEnd(String morningEnd) {
        this.morningEnd = morningEnd;
    }
    public String getAfternoonBegin() {
        return afternoonBegin;
    }
    public void setAfternoonBegin(String afternoonBegin) {
        this.afternoonBegin = afternoonBegin;
    }
    public String getAfternoonEnd() {
        return afternoonEnd;
    }
    public void setAfternoonEnd(String afternoonEnd) {
        this.afternoonEnd = afternoonEnd;
    }
    public String getNightBegin() {
        return nightBegin;
    }
    public void setNightBegin(String nightBegin) {
        this.nightBegin = nightBegin;
    }
    public String getNightEnd() {
        return nightEnd;
    }
    public void setNightEnd(String nightEnd) {
        this.nightEnd = nightEnd;
    }
    @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;
    }
}

+ 70 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/model/doctor/WlyyDoctorWorkWeek.java

@ -0,0 +1,70 @@
package com.yihu.wlyy.statistics.model.doctor;
import com.yihu.wlyy.statistics.model.IdEntity;
import javax.persistence.Entity;
import java.util.Date;
/**
 * Created by lyr on 2016/08/19.
 */
@Entity
public class WlyyDoctorWorkWeek extends IdEntity {
    private String doctor;
    private String doctorName;
    private String week;
    private String morning;
    private String afternoon;
    private String night;
    private Date czrq;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getWeek() {
        return week;
    }
    public void setWeek(String week) {
        this.week = week;
    }
    public String getMorning() {
        return morning;
    }
    public void setMorning(String morning) {
        this.morning = morning;
    }
    public String getAfternoon() {
        return afternoon;
    }
    public void setAfternoon(String afternoon) {
        this.afternoon = afternoon;
    }
    public String getNight() {
        return night;
    }
    public void setNight(String night) {
        this.night = night;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 306 - 0
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/DoctorWorkTimeService.java

@ -0,0 +1,306 @@
package com.yihu.wlyy.statistics.service;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.DoctorWorkTimeDao;
import com.yihu.wlyy.statistics.dao.DoctorWorkWeekDao;
import com.yihu.wlyy.statistics.model.doctor.Doctor;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkTime;
import com.yihu.wlyy.statistics.model.doctor.WlyyDoctorWorkWeek;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 医生工作排班
 * <p>
 * Created by lyr on 2016/08/19.
 */
@Service
@Transactional
public class DoctorWorkTimeService {
    static Object obj = new Object();
    @Autowired
    private DoctorWorkTimeDao doctorWorkTimeDao;
    @Autowired
    private DoctorWorkWeekDao doctorWorkWeekDao;
    @Autowired
    private DoctorDao doctorDao;
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public JSONObject findDoctorWeekWorkTime(String doctor, String week) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        result.put("workTime", workTime != null ? new JSONObject(workTime) : "");
        result.put("workWeek", workWeek != null ? new JSONObject(workWeek) : "");
        return result;
    }
    /**
     * 查询医生某天工作时间
     *
     * @param doctor 医生标识
     * @param week   某天
     * @return
     */
    public Map<String, Object> findDoctorWeekWork(String doctor, String week) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
            throw new Exception("doctor-worktime-error:doctor not exist");
        }
        WlyyDoctorWorkTime workTime = doctorWorkTimeDao.findDoctorWorkTime(doctor);
        WlyyDoctorWorkWeek workWeek = doctorWorkWeekDao.findDoctorWorkWeek(doctor, week);
        map.put("workTime", workTime);
        map.put("workWeek", workWeek);
        return map;
    }
    /**
     * 医生是否在工作
     *
     * @param doctor 医生
     * @return
     */
    public JSONObject isDoctorWorking(String doctor, Integer week) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        if (week < 0) {
            week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 0) {
                week = 7;
            }
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("msg", "医生当前接受咨询");
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                // 医生设置不接受咨询
                json.put("status", "0");
                json.put("msg", "医生不接受咨询");
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("msg", "医生当前接受咨询");
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        if (flag == 1) {
                            json.put("status", "1");
                            json.put("msg", "医生当前接受咨询");
                        } else {
                            json.put("status", "2");
                            json.put("msg", "医生当前不在工作时间");
                        }
                    } else {
                        json.put("status", "2");
                        json.put("msg", "医生当前不在工作时间");
                    }
                }
            }
        }
        return json;
    }
    public Date getDoctorWeek(String doctor, Integer week) throws Exception {
        Date json = new Date();
        Calendar calendar = Calendar.getInstance();
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            return json;
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                return null;
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    return json;
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                               String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                               preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                                preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                String preDate= DateUtil.dateToStr(json,"yyyy-MM-dd");
                                preDate=preDate+" "+currentStart;
                                return DateUtil.strToDate(preDate,"yyyy-MM-dd HH:mm");
                            }
                        }
                    } else {
                        return null;
                    }
                }
            }
        }
        return null;
    }
    /**
     * 得到医生的下次工作时间
     *
     * @param doctor
     * @return
     * @throws Exception
     */
    public Date getDoctorNextWork(String doctor) throws Exception {
        Calendar calendar = Calendar.getInstance();
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        //得到今天的是否有工作
        Date date=getDoctorWeek(doctor,week);
        if(date==null){
            //如果工作时间遍历得到最新的一天的时间
            for(int i=1;i<8;i++){
                int weekTemp=(i+week)%7;
                if(weekTemp==0){
                    weekTemp=7;
                }
                date=getDoctorWeek(doctor,weekTemp);
            }
        }
        return date;
    }
}

+ 47 - 6
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/service/JobService.java

@ -9,7 +9,9 @@ import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.QuartzHelper;
import com.yihu.wlyy.statistics.job.cache.CacheCleanJob;
import com.yihu.wlyy.statistics.job.check.CheckSignJob;
import com.yihu.wlyy.statistics.job.check.ReportAllLogJob;
import com.yihu.wlyy.statistics.job.message.HealthMessageJob;
import com.yihu.wlyy.statistics.job.message.NoticeJob;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import com.yihu.wlyy.statistics.model.job.WlyyQuota;
@ -331,9 +333,6 @@ public class JobService {
        return Integer.parseInt(String.valueOf(between_days));
    }
    public static void main(String[] args) {
        System.out.println(getYesterday(0,new Date()));
    }
    public void productDataByDayToDayAndId(String start, String end, String id) throws Exception {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
@ -408,13 +407,13 @@ public class JobService {
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        Map<String, Object> params = new HashMap<String, Object>();
        //往quartz框架添加任务
        params.put("now", day);
        params.put("yesterday", yesterday);
        params.put("now", yesterday);
        params.put("yesterday", day);
        quartzHelper.startNow(HealthMessageJob.class, HealthMessageJob.jobKey + UUID.randomUUID().toString().replace("-",""), params);
        Thread.sleep(20000L);
    }
@ -431,4 +430,46 @@ public class JobService {
            productHealthDataByOneDay(getYesterday(i,startDate));
        }
    }
    public static void main(String[] args) throws Exception{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date startDate=sdf.parse("2016-10-20");
        Date endDate=sdf.parse("2016-10-28");
        System.out.println(daysBetween(startDate,endDate));
        System.out.println(getYesterday(0,startDate));
    }
    public void startEveryDayReportJob()throws Exception {
        if(!quartzHelper.isExistJob(ReportAllLogJob.jobKey)){
            quartzHelper.addJob(ReportAllLogJob.class,ReportAllLogJob.cron,ReportAllLogJob.jobKey,new HashMap<>());
        }else{
            throw new Exception("已经启动");
        }
    }
    public void stopEveryDayReportJob() throws Exception{
        if(quartzHelper.isExistJob(ReportAllLogJob.jobKey)){
            quartzHelper.removeJob(ReportAllLogJob.jobKey);
        }else{
            throw new Exception("已经停止");
        }
    }
    public void startNoticeJob() throws Exception {
        if(!quartzHelper.isExistJob(NoticeJob.jobKey)){
            quartzHelper.addJob(NoticeJob.class,NoticeJob.jobCron,NoticeJob.jobKey,new HashMap<>());
        }else{
            throw new Exception("已经启动");
        }
    }
    public void stopNoticeJob()throws Exception  {
        if(quartzHelper.isExistJob(NoticeJob.jobKey)){
            quartzHelper.removeJob(NoticeJob.jobKey);
        }else{
            throw new Exception("已经停止");
        }
    }
}

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

@ -0,0 +1,173 @@
package com.yihu.wlyy.statistics.task;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.LinkedBlockingQueue;
public class PushMsgTask {
	private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
	private static PushMsgTask instance;
	private static Object lock = new Object();
	@Value("${systemConfig.msg_push_server}")
	private String msgPushServer;
	public static PushMsgTask getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new PushMsgTask();
				instance.run();
			}
		}
		return instance;
	}
	/**
	 * 添加一条推送消息
	 * @param receiver 接收人
	 * @param type 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public void put(String receiver, String type, String title, String msg, String data) {
		try {
			JSONObject json = new JSONObject();
			json.put("receiver", receiver);
			json.put("type", type);
			json.put("title", title);
			json.put("msg", msg);
			json.put("data", data);
			queue.put(json);
		} catch (Exception e) {
			logger.error("添加到消息队列失败!", e);
			e.printStackTrace();
		}
	}
	public void put(JSONArray array) {
		if (array == null || array.size() == 0) {
			return;
		}
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			if (json == null) {
				continue;
			}
			try {
				queue.put(json);
			} catch (Exception e) {
				logger.error("批量添加到消息队列失败!", e);
			}
		}
	}
	private void run() {
		new Thread(new ConsumerTask()).start();
	}
	// 消费者
	class ConsumerTask implements Runnable {
		@Override
		public void run() {
			try {
				while (true) {
					// 如果queue为空,则当前线程会堵塞,直到有新数据加入
					JSONObject json = queue.take();
					// 推送平台消息
					String receiver = json.has("receiver") ? json.getString("receiver") : "";
					String type = json.has("type") ? json.getString("type") : "";
					String title = json.has("title") ? json.getString("title") : "";
					String msg = json.has("msg") ? json.getString("msg") : "";
					String data = json.has("data") ? json.getString("data") : "";
					boolean res = pushMessage(receiver, type, title, msg, data);
					if (res) {
						logger.info("消息推送成功!");
					} else {
						logger.error("消息推送失败!");
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	/**
	 * 消息推送
	 *
	 * @param receiver 消息接收人
	 * @param msgType 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public static boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
		PrintWriter out = null;
		BufferedReader in = null;
		HttpURLConnection conn = null;
		try {
			//String server = getInstance().systemConfig.getMsgPushServer();
			String server = "http://127.0.0.1:3000/system/sendmsg.im";
			String url = server + "?to_uid=" + receiver + "&content=" + URLEncoder.encode(msg, "UTF-8") + "&type=" + msgType + "&title=" + URLEncoder.encode(title, "UTF-8") + "&data=" + data;
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			conn = (HttpURLConnection) realUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/json");
			// 读取返回内容
			StringBuffer buffer = new StringBuffer();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
				buffer.append("\n");
			}
			System.out.println(buffer.toString());
			JSONObject json = new JSONObject().fromObject(buffer.toString());
			if (json.getInt("errno") == 0) {
				// 成功
				return true;
			} else {
				// 失败
				return false;
			}
		} catch (Exception e) {
			logger.error("push message error:", e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}
}

+ 2 - 5
patient-co-statistics/src/main/java/com/yihu/wlyy/statistics/util/IdCardUtil.java

@ -95,7 +95,6 @@ public class IdCardUtil {
     */
    public static int getAgeForIdcard(String idcard) {
        int age = 0;
        try{
        if (StringUtils.isEmpty(idcard)) {
            return age;
@ -115,12 +114,10 @@ public class IdCardUtil {
        Calendar cal = Calendar.getInstance();
        age = cal.get(Calendar.YEAR) - year;
        //周岁计算
        if (cal.get(Calendar.MONTH) > (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) > day)) {
        if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
            age--;
        }
        }catch (Exception e){
            return age;
        }
        return age;
    }

+ 16 - 4
patient-co-statistics/src/main/resources/application.yml

@ -40,7 +40,6 @@ spring:
    # REDIS
  redis:
    database: 0 # Database index used by the connection factory.
    port: 6379 # Redis server port.
    password: # Login password of the redis server.
    timeout: 0 # Connection timeout in milliseconds.
      #sentinel:
@ -60,7 +59,7 @@ spring:
    port: 465
    username: 1501877145
    from: 1501877145@qq.com
    to: 494679975@qq.com,463166875@qq.com #接受者,多个接受逗号分隔,接受者邮箱要开启IMAP/SMTP服务(不开可能会在垃圾箱)
    to: 494679975@qq.com #接受者,多个接受逗号分隔,接受者邮箱要开启IMAP/SMTP服务(不开可能会在垃圾箱)
    password: pnubhfagxeophfej
    properties:
      mail:
@ -107,6 +106,7 @@ spring:
  redis:
    host: 172.19.103.88
    port: 6379 # Redis server port.
fv:
  jdbc:
@ -130,7 +130,8 @@ spring:
      password: ssgg
  redis:
      host: 172.19.103.88 # Redis server host.
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
@ -138,6 +139,9 @@ fv:
    username: ssgg
    password: ssgg
systemConfig:
  msg_push_server: http://127.0.0.1:3000/system/sendmsg.im
---
spring:
@ -155,6 +159,7 @@ spring:
  redis:
    host: 120.41.253.95 # Redis server host.
    port: 6380 # Redis server port.
fv:
  jdbc:
@ -163,6 +168,9 @@ fv:
    username: wlyy
    password: jkzlehr@123
systemConfig:
  msg_push_server: http://127.0.0.1:3000/system/sendmsg.im
---
spring:
@ -181,10 +189,14 @@ spring:
  redis:
    host: 172.19.103.47 # Redis server host.
    port: 6379 # Redis server port.
fv:
  jdbc:
    driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.19.103.77/fv?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: root
    password: 123456
    password: 123456
systemConfig:
  msg_push_server: http://127.0.0.1:3000/system/sendmsg.im

+ 5 - 1
patient-co-wlyy/pom.xml

@ -259,7 +259,11 @@
            <version>20160212</version>
        </dependency>
        <!-- JSON end -->
        <dependency>
            <groupId>org.htmlparser</groupId>
            <artifactId>htmlparser</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>

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

@ -27,7 +27,7 @@ public class Consult extends IdEntity {
	private String code;
	// 患者标识
	private String patient;
	// 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
	// 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈 6、患者名医咨询 7医生名医咨询
	private Integer type;
	// 咨询标题/主诉
	private String title;

+ 10 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/consult/ConsultTeam.java

@ -5,6 +5,7 @@ import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
@ -21,7 +22,7 @@ public class ConsultTeam extends IdEntity {
	private String consult;         // 咨询标识
	private String doctor;          // 医生标识
	private String team;            // 三师团队标识
	private Integer type;           //  1、三师咨询,2、家庭医生咨询,6、名医咨询
	private Integer type;           //  1、三师咨询,2、家庭医生咨询,6、名医咨询 7医生名医咨询
	private String patient;         // 提问者标识
	private String name;            // 患者姓名
	private Integer sex;            // 患者性别
@ -41,6 +42,7 @@ public class ConsultTeam extends IdEntity {
	private String del;             // 作废标识,1正常,0作废
	private Long adminTeamId;//行政团队ID
	private Long guidance;   //关联指导
	private String doctorName;//醫生名字
	@Column(name = "admin_team_code")
	public Long getAdminTeamId() {
@ -229,7 +231,14 @@ public class ConsultTeam extends IdEntity {
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	@Transient
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	public Long getGuidance() {
		return guidance;

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

@ -61,6 +61,7 @@ public class Doctor extends IdEntity {
	private String idcard;          //身份证号
	private Integer isFamous;       //是否是名医 1是  0或者空不是
	private String isPasswordPrompt;// 是否提示密码信息 1是 0或者空是否
	private String isHelp;//是否求助  1已经求助 0未求助
	public Doctor() {}
@ -351,6 +352,14 @@ public class Doctor extends IdEntity {
    public boolean isHealthDoctor(){
        return level == 3;
    }
	@Transient
	public String getIsHelp() {
		return isHelp;
	}
	public void setIsHelp(String isHelp) {
		this.isHelp = isHelp;
	}
	@Column(name = "is_password_prompt")
	public String getIsPasswordPrompt() {

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

@ -32,6 +32,16 @@ public class HealthEduArticle extends IdEntity {
	private String content;
	// 发布时间
	private Date czrq;
	//文章关键字
	private String keyword;
	public String getKeyword(){
		return keyword;
	}
	public void setKeyword(String keyword){
		this.keyword = keyword;
	}
	public String getCode() {
		return code;

+ 88 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleDoctor.java

@ -0,0 +1,88 @@
package com.yihu.wlyy.entity.education;
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_health_edu_article_doctor")
public class HealthEduArticleDoctor extends IdEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2828101406253527L;
	// 文章标识
	private String article;
	// 医生标识
	private String doctor;
	// 文章标题
	private String title;
	// 文章链接
	private String url;
	// 文章内容
	//private String content;
	// 发布时间
	private Date czrq;
	public String getArticle() {
		return article;
	}
	public void setArticle(String article) {
		this.article = article;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	//public String getContent() {
	//	return content;
	//}
    //
	//public void setContent(String content) {
	//	this.content = content;
	//}
	@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;
	}
}

+ 64 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleLabel.java

@ -0,0 +1,64 @@
package com.yihu.wlyy.entity.education;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 患者健康教育文章
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_health_edu_article_label")
public class HealthEduArticleLabel extends IdEntity {
	/**
	 *
	 */
	private static final long serialVersionUID = -1828201403253527L;
	// 文章搜索关键字
	private String keyword;
	// 总数
	private int amount;
	// 创建人
	private String creater;
	//创建日期
	private Date czrq;
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public int getAmount() {
		return amount;
	}
	public void setAmount(int amount) {
		this.amount = amount;
	}
	public String getCreater() {
		return creater;
	}
	public void setCreater(String creater) {
		this.creater = creater;
	}
}

+ 84 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/entity/education/HealthEduArticleOpHistory.java

@ -0,0 +1,84 @@
package com.yihu.wlyy.entity.education;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 健康教育文章操作历史表
 * @author linz
 *
 */
@Entity
@Table(name = "wlyy_health_edu_article_op_history")
public class HealthEduArticleOpHistory extends IdEntity {
	// 文章标识
	private String code;
	// 文章标题
	private String title;
	// 操作类型1.阅读 2.收藏 3.转发
	private String status;
	// 操作人
	private String creater;
	// 发布时间
	private Date createdTime;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getCreater() {
		return creater;
	}
	public void setCreater(String creater) {
		this.creater = creater;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCreatedTime() {
		return createdTime;
	}
	public void setCreatedTime(Date createdTime) {
		this.createdTime = createdTime;
	}
	/**
	 * 阅读状态
	 */
	public static final String READ_STATUS ="1";
	/**
	 * 收藏状态
	 */
	public static final String COLLECTION_STATUS ="2";
	/**
	 * 转发状态
	 */
	public static final String REPEAT_STATUS ="3";
}

+ 35 - 16
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/consult/ConsultTeamDao.java

@ -25,9 +25,12 @@ public interface ConsultTeamDao extends PagingAndSortingRepository<ConsultTeam,
	@Query("select a from ConsultTeam a where a.patient = ?1 and a.del = '1' and a.status = 0")
	List<ConsultTeam> findUnfinishedConsult(String patient);
	@Query("select a from ConsultTeam a where a.patient = ?1 and a.doctor = ?2 and a.del = '1' and a.status = 0")
	List<ConsultTeam> findUnfinishedConsultType(String patient,String doctor);
	// 统计未完成的数量
	@Query("select count(1) from ConsultTeam a where a.patient = ?1 and a.status = 0 and a.del = '1'and a.type=?2")
	int countByPatient(String patient,Integer signType);
	@Query("select count(1) from ConsultTeam a where a.patient = ?1 and a.status = 0 and a.del = '1'and a.doctor=?2")
	int countByPatient(String patient,String doctor);
	// 被指定且未结束列表
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and b.to = ?1 and a.del = '1' and b.del = '1' and a.type<3")
@ -165,31 +168,31 @@ public interface ConsultTeamDao extends PagingAndSortingRepository<ConsultTeam,
	@Query("SELECT a FROM ConsultTeam a WHERE a.type=2 and unix_timestamp(a.czrq)>=unix_timestamp(?1) and unix_timestamp(a.czrq)<unix_timestamp(?2) ")
	List<ConsultTeam> findByCzrqyYesterday(String yesterday,String now);
	//查找
	@Query("SELECT a FROM ConsultTeam a WHERE a.patient=?1 and a.status=0 and a.del=1 and a.type=6")
	ConsultTeam findFamousConsultByPatient(String uid);
	@Query("SELECT a FROM ConsultTeam a WHERE a.patient=?1 and a.doctor = ?2 and a.status=0 and a.del=1 and a.type=6")
	ConsultTeam findFamousConsultByPatient(String uid,String doctor);
	//名医咨询 -全部
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.id < ?2 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1 and a.id < ?2 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorAllList(String uid, long id, Pageable pageRequest);
	//名医咨询 -全部
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1  and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1  and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorAllList(String uid, Pageable pageRequest);
	//名医咨询 -全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.id < ?2 and a.symptoms like ?3 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1 and a.id < ?2 and a.symptoms like ?3 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorAllList(String uid, long id,String title, Pageable pageRequest);
	//名医咨询 -全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.symptoms like ?2  and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1 and a.symptoms like ?2  and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorAllList(String uid,String title, Pageable pageRequest);
	//名医咨询 -根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.id < ?2 and a.status = ?3 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1 and a.id < ?2 and a.status = ?3 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorDoingList(String uid, long id,Integer type, Pageable pageRequest);
	//名医咨询 -根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.status = ?2  and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 )and b.to = ?1 and a.status = ?2  and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorDoingList(String uid,Integer type, Pageable pageRequest);
	//名医咨询 -根据status 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.id < ?2 and a.symptoms like ?3 and a.status = ?4 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and b.to = ?1 and a.id < ?2 and a.symptoms like ?3 and a.status = ?4 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorDoingList(String uid, long id,String title,Integer type, Pageable pageRequest);
	//名医咨询 -根据status 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.to = ?1 and a.symptoms like ?2 and a.status = ?3 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 )and b.to = ?1 and a.symptoms like ?2 and a.status = ?3 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findFamousDoctorDoingList(String uid,String title,Integer type, Pageable pageRequest);
	@Query("select a from ConsultTeam a where  a.type=?3  and a.del = '1' and a.patient=?1 and a.doctor=?2 and  a.status=0 ")
@ -251,18 +254,34 @@ public interface ConsultTeamDao extends PagingAndSortingRepository<ConsultTeam,
	@Query("FROM ConsultTeam a where a.type=?1 and a.adminTeamId is null")
	List<ConsultTeam> findByTypeAndAdminTeamIdIsNull(Integer s);
	//名医咨询 -我咨询的全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.from = ?1 and a.id < ?2 and a.symptoms like ?3 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.id < ?2 and a.symptoms like ?3 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorAllList(String uid, long id, String title, Pageable pageRequest);
	//名医咨询 -我咨询的全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.from = ?1 and a.symptoms like ?2 and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.symptoms like ?2 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorAllList(String uid, String title, Pageable pageRequest);
	//名医咨询 -我咨询的全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.from = ?1 and a.id < ?2 and  a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.id < ?2 and  a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorAllList(String uid, Long id, Pageable pageRequest);
	//名医咨询 -我咨询的全部 带symptoms
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and a.type=6 and b.from = ?1  and a.del = '1' and b.del = '1'")
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1  and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorAllList(String uid, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms 根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2 and a.id < ?3 and a.symptoms like ?4 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorListByStatus(String uid, int status, long id, String title, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms 根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.symptoms like ?3 and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorListByStatus(String uid, int status, String title, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.id < ?3 and  a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorListByStatus(String uid, int status, long id, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms根据status
	@Query("select a from ConsultTeam a, ConsultTeamDoctor b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.del = '1' and b.del = '1'")
	Page<ConsultTeam> findMyFamousDoctorListByStatus(String uid, int status, Pageable pageRequest);
}

+ 1 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorAdminTeamDao.java

@ -54,7 +54,7 @@ public interface DoctorAdminTeamDao extends
     * @return
     */
    @Query("SELECT p FROM SignFamily s, Patient p WHERE s.doctorHealth = :healthDoctorCode AND s.patient = p.code and s.status >0 AND" +
            " s.adminTeamId = :teamId")
            " s.adminTeamId = :teamId AND s.type = 2")
    Page<Patient> getHealthDoctorSigningPatients(@Param(value = "healthDoctorCode") String healthDoctorCode,
                                                 @Param(value = "teamId") long teamId,
                                                 Pageable pageable);

+ 3 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorDao.java

@ -30,6 +30,9 @@ public interface DoctorDao extends PagingAndSortingRepository<Doctor, Long>, Jpa
    @Query("select d from Doctor d where d.del = 1")
    List<Doctor> findAllDoctors();
    @Query("select d from Doctor d where d.del = 1 and d.name like ?1")
    List<Doctor> findDoctorsByName(String name);
    @Query("select d from Doctor d where d.del = 1 and d.hospital = ?1")
    Iterable<Doctor> findHospitalDoctors(String hospital);

+ 4 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/doctor/DoctorTeamMemberDao.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.repository.doctor;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
@ -61,4 +62,7 @@ public interface DoctorTeamMemberDao extends PagingAndSortingRepository<DoctorTe
    @Query("SELECT case when count(a) > 0 THEN true else false END FROM DoctorTeamMember a WHERE a.signType = 1 AND a" +
            ".memberCode = :memberCode")
    Boolean isSanShiSigning(@Param("memberCode") String doctorCode);
    @Query("select d FROM DoctorTeamMember a,Doctor d WHERE a.memberCode=d.code  and  a.del='1'and  a.type=1 and a.team in ( select b.team from DoctorTeamMember b where b.memberCode= ?1 and b.del='1' and b.type=2) ")
    List<Doctor> getTeamZKByQK(String qkCode);
}

+ 9 - 1
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleDao.java

@ -1,12 +1,20 @@
package com.yihu.wlyy.repository.education;
import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
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.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import java.util.Date;
public interface HealthEduArticleDao extends PagingAndSortingRepository<HealthEduArticle, Long>, JpaSpecificationExecutor<HealthEduArticle> {
	HealthEduArticle findByCode(String code);
	
	@Query("SELECT a FROM HealthEduArticle a WHERE (a.title like ?1 or a.keyword like ?2) ORDER BY a.czrq DESC")
	Page<HealthEduArticle> list(String title, String keyword, Pageable pageRequest);
}

+ 26 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleDoctorDao.java

@ -0,0 +1,26 @@
package com.yihu.wlyy.repository.education;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticleDoctor;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import org.json.JSONArray;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface HealthEduArticleDoctorDao extends PagingAndSortingRepository<HealthEduArticleDoctor, Long>, JpaSpecificationExecutor<HealthEduArticleDoctor> {
	HealthEduArticleDoctor findByArticleAndDoctor(String article,String doctor);
	int deleteByArticleAndDoctor(String article,String doctor);
	@Query("SELECT b FROM HealthEduArticleDoctor a ,HealthEduArticle b where b.code = a.article and a.doctor =?1 ORDER BY a.czrq DESC")
	List<Object> list(String doctor,Pageable pageRequest);
	@Query("SELECT b FROM HealthEduArticleDoctor a ,HealthEduArticle b where b.code = a.article and (a.title like ?1 or b.keyword like?2) and a.doctor =?3 ORDER BY a.czrq DESC")
	List<Object> listFilter(String title,String keyword,String doctor,Pageable pageRequest);
}

+ 18 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleLabelDao.java

@ -0,0 +1,18 @@
package com.yihu.wlyy.repository.education;
import com.yihu.wlyy.entity.education.HealthEduArticleDoctor;
import com.yihu.wlyy.entity.education.HealthEduArticleLabel;
import org.springframework.data.domain.Pageable;
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 HealthEduArticleLabelDao extends PagingAndSortingRepository<HealthEduArticleLabel, Long>, JpaSpecificationExecutor<HealthEduArticleLabel> {
	HealthEduArticleLabel findByKeywordAndCreater(String keyword, String creater);
	@Query("select b from HealthEduArticleLabel b where b.keyword=?1 and b.creater ='public'")
	HealthEduArticleLabel findByPublicKeyword(String keyword);
}

+ 18 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/education/HealthEduArticleOpHistoryDao.java

@ -0,0 +1,18 @@
package com.yihu.wlyy.repository.education;
import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
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;
public interface HealthEduArticleOpHistoryDao extends PagingAndSortingRepository<HealthEduArticleOpHistory, Long>, JpaSpecificationExecutor<HealthEduArticleOpHistory> {
	@Query("select count(1) from HealthEduArticleOpHistory a where a.code = ?1 and a.status = ?2")
	int countByCodeStatus(String code,String status);
	@Query("select count(1) from HealthEduArticleOpHistory a where a.creater = ?1 and a.status = ?2")
	int countByUserStatus(String user,String status);
	int deleteByCodeAndStatusAndCreater(String code,String status,String creater);
}

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

@ -7,10 +7,16 @@ import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
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);
	List<HealthEduArticlePatient> findByArticleAndPatient(String article,String patient);
}

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

@ -308,4 +308,7 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
	@Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
	List<SignFamily> findAllSignByPatient(String patient);
	@Query("select a.patient from SignFamily a where a.doctor = ?1 and a.type = 2 and a.status > 0 and a.doctorHealth is null")
	List<String> findNohealthByDoctor(String doctor);
}

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

@ -32,7 +32,9 @@ import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.MD5;
import org.apache.commons.beanutils.converters.IntegerConverter;
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;
@ -40,7 +42,9 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
@ -59,7 +63,6 @@ import javax.print.Doc;
 */
// Spring Service Bean的标识.
@Component
@Transactional
public class DoctorInfoService extends BaseService {
    @Autowired
@ -101,6 +104,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatients(String doctor) {
        return signFamilyDao.findDoctorSignPatients(doctor);
    }
@ -111,6 +115,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsLikeName(String doctor, String patientName) {
        return signFamilyDao.findDoctorSignPatientsLikeName(doctor, patientName);
    }
@ -121,6 +126,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsBySignType(String doctor, int type) {
        return signFamilyDao.findDoctorSignPatientsBySignType(doctor, type);
    }
@ -131,14 +137,17 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> getDoctorSignPatientsByTypeName(String doctor, int type, String patientName) {
        return signFamilyDao.findDoctorSignPatientsByTypeName(doctor, type, patientName);
    }
    @Transactional
    public Doctor findDoctorByCode(String code) {
        return doctorDao.findByCode(code);
    }
    @Transactional
    public Doctor findDoctorByMobile(String mobile) {
        return doctorDao.findByMobile(mobile);
    }
@ -149,6 +158,7 @@ public class DoctorInfoService extends BaseService {
     * @param mobile
     * @return
     */
    @Transactional
    public Doctor findNormalByMobile(String mobile) {
        return doctorDao.findNormalByMobile(mobile);
    }
@ -159,6 +169,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public Doctor updateDoctor(Doctor doctor) {
        Province province = provinceDao.findByCode(doctor.getProvince());
        if (province != null) {
@ -190,6 +201,7 @@ public class DoctorInfoService extends BaseService {
    /**
     * 修改医生密码
     */
    @Transactional
    public void updateDoctorPwd(Doctor doctor) {
        EncodesUtil.entryptPassword(doctor);
        doctorDao.save(doctor);
@ -201,10 +213,12 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public List<Object> findPatientByDoctorSign(String doctor) {
        return doctorDao.findPatientByDoctorSign(doctor);
    }
    @Transactional
    public Page<Object> findPatientByDoctorSign(String doctor, long id,
                                                int pagesize, String patientName) {
        // return doctorDao.findPatientByDoctorSign(doctor);
@ -248,6 +262,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public int amountPatientByDoctorSign(String doctor) {
        return doctorDao.amountPatientByDoctorSign(doctor);
    }
@ -258,14 +273,17 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public Iterable<DoctorPatientGroup> findDoctorPatientGroup(String doctor) {
        return doctorDao.findDoctorPatientGroup(doctor);
    }
    @Transactional
    public Patient findPatientByCode(String code) {
        return doctorDao.findPatientByCode(code);
    }
    @Transactional
    public DoctorPatientGroupInfo findGroup(String user, String doctor) {
        return doctorDao.findGroup(user, doctor);
    }
@ -279,6 +297,7 @@ public class DoctorInfoService extends BaseService {
     *                 页数
     * @return
     */
    @Transactional
    public Page<Doctor> getDoctorListByHospital(String query, String hospital,
                                                long id, int pageSize) {
        // 排序
@ -304,22 +323,26 @@ public class DoctorInfoService extends BaseService {
        return doctorDao.findAll(spec, pageRequest);
    }
    @Transactional
    public List<Doctor> getDoctorCombobxByHospital(String type, String hospital) {
        return doctorDao.getDoctorCombobxByHospital(hospital, Integer.valueOf(type));
    }
    @Transactional
    public Doctor getDoctor(int consultType, String patientCode) {
        //根据病人ID查找团队
        //DoctorTeam doctorTeam =doctorTeamDao.getBy
        return null;
    }
    @Transactional
    public Page<Doctor> getDoctorListByPatientCode(int consultType, String patientCode, String name, int page, int pageSize) {
        //
        return null;
    }
    @Transactional
    public Page<Doctor> getDoctorListByHospital(String name, String paitentCode, Integer page, Integer pageSize) {
        if (pageSize == null | pageSize <= 0) {
            pageSize = 10;
@ -344,6 +367,7 @@ public class DoctorInfoService extends BaseService {
        return doctorDao.findAll(spec, pageRequest);
    }
    @Transactional
    public void doctor_1_Toteam(String teamCode, String doctor, String doctorName, String groupCode, String loginCode, String parientCode, String sickName, String sickNCode) {
        //得到患者所在的团队
        DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(parientCode);
@ -395,6 +419,7 @@ public class DoctorInfoService extends BaseService {
    }
    @Transactional
    public Doctor getDoctor2ByParient(String parientCode, String consultCode) {
        //得到咨询的类别
        Consult consult = consultDao.findByCode(consultCode);
@ -412,6 +437,7 @@ public class DoctorInfoService extends BaseService {
        return doctor;
    }
    @Transactional
    public List<Map> findNoInConsultDoctor(String existDoc, String consultCode, int page, int pageSzie) {
        int start = (page - 1) * pageSzie;
        String sql = "select p.* from wlyy_doctor p where " +
@ -422,6 +448,7 @@ public class DoctorInfoService extends BaseService {
        return rs;
    }
    @Transactional
    public int countNoInConsultDoctor(String existDoc, String consultCode) {
        String sql = "SELECT count(*) as c FROM (" +
                "select 1 as c from wlyy_doctor p where " +
@ -432,6 +459,7 @@ public class DoctorInfoService extends BaseService {
        return ((Long) ((Map) rs.get(0)).get("c")).intValue();
    }
    @Transactional
    public Map<String, Object> getDoctor1ByParient(String consultCode, String parientCode, Integer page, Integer pageSzie) {
        Map<String, Object> returnMap = new HashMap<>();
        if (pageSzie == null | pageSzie <= 0) {
@ -509,6 +537,7 @@ public class DoctorInfoService extends BaseService {
        return returnMap;
    }
    @Transactional
    public List<Doctor> findDoctorByLevelAndHospital(String hospital, Integer level) {
        return doctorDao.findDoctorByLevelAndHospital(hospital, level);
    }
@ -520,6 +549,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateDoctorIdcard(String idcard, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
@ -536,6 +566,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateExpertise(String expertise, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
@ -552,6 +583,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateSex(int sex, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
@ -568,6 +600,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public boolean updateIntroduce(String introduce, String doctor) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        if (doc == null) {
@ -592,6 +625,7 @@ public class DoctorInfoService extends BaseService {
        doctor.setIsFamous(status);
    }
    @Transactional
    public Page<Doctor> findDoctorByDept(String dept, String hosptial, String key, int page, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
@ -620,6 +654,7 @@ public class DoctorInfoService extends BaseService {
    }
    @Transactional
    public Page<Doctor> findFamousDoctor(String key, Integer type, int page, int pageSize, Integer level) {
        if (pageSize <= 0) {
            pageSize = 10;
@ -648,6 +683,7 @@ public class DoctorInfoService extends BaseService {
    }
    @Transactional
    public List<Doctor> findFamousDoctorList(String key, Integer type, int page, int pageSize, Integer level) throws Exception {
        if (pageSize <= 0) {
            pageSize = 10;
@ -681,7 +717,7 @@ public class DoctorInfoService extends BaseService {
        if (doctors.size() > 0) {
            for (Doctor doc : doctors) {
                if(workingDoctor.size() > end){
                if (workingDoctor.size() > end) {
                    break;
                }
                if (type != 1) {
@ -707,12 +743,63 @@ public class DoctorInfoService extends BaseService {
        return returnList;
    }
    @Transactional
    public JSONArray findWorkingDoctorListByDept(String dept, String hospital, String level, String key, int page, int pagesize) throws Exception {
        String sql = "select * from wlyy_doctor where  status = 1";
        List<Object> args = new ArrayList<>();
        if (!StringUtils.isEmpty(dept)) {
            sql += " and dept = ? ";
            args.add(dept);
        }
        if (!StringUtils.isEmpty(hospital)) {
            sql += " and hospital = ? ";
            args.add(hospital);
        }
        if (!StringUtils.isEmpty(level)) {
            sql += " and level = ? ";
            args.add(Integer.valueOf(level));
        }
        if (!StringUtils.isEmpty(key)) {
            sql += " and name like ? ";
            args.add("%" + key + "%");
        }
        if (page >= 0) {
            sql += " limit " + page * pagesize + "," + pagesize;
        }
        List<Doctor> doctors = jdbcTemplate.query(sql, args.toArray(), new BeanPropertyRowMapper(Doctor.class));
        JSONArray workingDoctor = new JSONArray();
        if (doctors.size() > 0) {
            for (Doctor doc : doctors) {
                JSONObject iswork = workTimeService.isDoctorWorking(doc.getCode());
                if (iswork.getString("status").equals("1")) {
                    JSONObject docJson = new JSONObject(doc);
                    if (docJson.has("password")) {
                        docJson.remove("password");
                    }
                    if (docJson.has("salt")) {
                        docJson.remove("salt");
                    }
                    workingDoctor.put(docJson);
                }
            }
        }
        return workingDoctor;
    }
    @Transactional
    public void updateTeamHealthDoctor(String newDoctorCode, String oldDoctorCode, String patient) throws Exception {
        //得到患者的签约信息
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        String groupCode = "";
        if (StringUtils.isNoneBlank(oldDoctorCode)) {
        //得到签约中的健管师
        oldDoctorCode = signFamily.getDoctorHealth();
        //如果存在旧的健管师
        if (!org.springframework.util.StringUtils.isEmpty(oldDoctorCode)) {
            //判断患者对旧的健管师是否存在健康咨询
            ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patient, oldDoctorCode, 2);
            if (consultTeam != null) {
                throw new Exception("存在没有关闭的健康咨询");
@ -723,7 +810,6 @@ public class DoctorInfoService extends BaseService {
                doctorTeamMember.setDel("0");
            }
        }
        Patient patientObj = patientDao.findByCode(patient);
        Doctor newD = doctorDao.findByCode(newDoctorCode);
        //修改签约中的健康管理师
        signFamily.setDoctorHealth(newD.getCode());
@ -742,6 +828,7 @@ public class DoctorInfoService extends BaseService {
        doctorTeamDoctor.save(newDoctorTeamMember);
    }
    @Transactional
    public void updateTeamHealthDoctors(String newDoctorCode, String oldDoctorCode, String patients) throws Exception {
        String[] patiensString = patients.split(",");
        for (int i = 0; i < patiensString.length; i++) {
@ -749,6 +836,52 @@ public class DoctorInfoService extends BaseService {
        }
    }
    @Transactional
    public int updateTeamHealthDoctorsAll(String newDoctorCode, String doctor) throws Exception {
        List<String> patients = signFamilyDao.findNohealthByDoctor(doctor);
        boolean hasNoTeam = false;
        if (patients != null) {
            for (String patient : patients) {
                try {
                    if (updateTeamHealthDoctorAll(newDoctorCode, patient) == -1) {
                        hasNoTeam = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return hasNoTeam ? 2 : 1;
    }
    @Transactional
    public int updateTeamHealthDoctorAll(String newDoctorCode, String patient) throws Exception {
        //得到患者的签约信息
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if (StringUtils.isEmpty(signFamily.getTeamCode())) {
            return -1;
        }
        Doctor newD = doctorDao.findByCode(newDoctorCode);
        //修改签约中的健康管理师
        signFamily.setDoctorHealth(newD.getCode());
        signFamily.setDoctorHealthName(newD.getName());
        //添加新的健康管理师到服务团队里
        DoctorTeamMember newDoctorTeamMember = new DoctorTeamMember();
        newDoctorTeamMember.setTeam(signFamily.getTeamCode());
        newDoctorTeamMember.setCzrq(new Date());
        newDoctorTeamMember.setName(newD.getName());
        newDoctorTeamMember.setMemberCode(newD.getCode());
        newDoctorTeamMember.setType(3);
        newDoctorTeamMember.setSignType("2");
        newDoctorTeamMember.setDel("1");
        newDoctorTeamMember.setCode(UUID.randomUUID().toString().replace("-", ""));
        doctorTeamDoctor.save(newDoctorTeamMember);
        return 1;
    }
    /**
     * 医生更换手机号
     *
@ -757,6 +890,7 @@ public class DoctorInfoService extends BaseService {
     * @param captcha 验证码
     * @return
     */
    @Transactional
    public int changeMobile(String doctor, String mobile, String captcha, int type) {
        Doctor doc = doctorDao.findByCode(doctor);
@ -776,7 +910,19 @@ public class DoctorInfoService extends BaseService {
        if (smsCheck != 1) {
            return -3;
        }
        //修改密码
        String oldPassword=doc.getPassword();
        //判断旧的密码是不是手机号码后六位
        String oldMobile=doc.getMobile();
        if(!org.springframework.util.StringUtils.isEmpty(oldMobile)){
            String passwordTemp=oldMobile.substring(5);
            passwordTemp=MD5.GetMD5Code(passwordTemp+doc.getSalt());
            if(passwordTemp.equals(oldPassword)){
                //如果密码是原来的电话号码后留位改成现在号码的后留位
                String newPassword=MD5.GetMD5Code(mobile.substring(5)+doc.getSalt());
                doc.setPassword(newPassword);
            }
        }
        doc.setMobile(mobile);
        return 1;
@ -806,6 +952,7 @@ public class DoctorInfoService extends BaseService {
     * @param doctor
     * @return
     */
    @Transactional
    public boolean isPatientSigned(String patient, String doctor) {
        boolean bo = false;
        //签约团队
@ -828,6 +975,7 @@ public class DoctorInfoService extends BaseService {
     * @param mobile
     * @return
     */
    @Transactional
    public int isMobileRegister(String mobile) {
        Doctor doc = doctorDao.findByMobile(mobile);

+ 7 - 5
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java

@ -151,11 +151,13 @@ public class PatientInfoService extends BaseService {
            return result;
        }
        PatientFamilyMember member = familyMemberService.getPatientFamilyMember(patient, family);
        // 家庭成员中不存在该人
        if (member == null) {
            result.put("status", -2);
            return result;
        if(!patient.equals(family)) {
            PatientFamilyMember member = familyMemberService.getPatientFamilyMember(patient, family);
            // 家庭成员中不存在该人
            if (member == null) {
                result.put("status", -2);
                return result;
            }
        }
        LoginLog loginLog = new LoginLog();

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

@ -83,8 +83,44 @@ public class ConsultTeamService extends ConsultService {
     * @param patient
     * @return
     */
    public boolean exist(String patient, Integer type) {
        int count = consultTeamDao.countByPatient(patient, type);
    public boolean exist(String patient, Integer type) throws Exception {
        DoctorTeamMember member = null;
        // 咨询三师
        if (type == 1) {
            // 查询三师签约信息
            SignFamily sc = signFamilyDao.findBySanshiPatientYes(patient);
            if(sc == null){
                throw new Exception("不存在三师签约");
            }
            // 设置健康管理师,三师咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findBySanshiParientCode(patient);
            //得到团队的健康管理师
            member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 3);
            if (member == null) {
                member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 2);
            }
        } else if (type == 2) {
            // 咨询家庭医生
            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
            if(sf == null){
                throw new Exception("不存在家庭签约");
            }
            // 设置健康管理师,家庭医生咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(patient);
            //得到团队的健康管理师
            member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 3);
            if (member == null) {
                member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 2);
            }
        }
        if(member == null){
            throw new Exception("找不到签约服务团队医生");
        }
        int count = consultTeamDao.countByPatient(patient, member.getMemberCode());
        return count > 0;
    }
@ -135,11 +171,37 @@ public class ConsultTeamService extends ConsultService {
            case 10:
                //我咨询的
                return findByDoctorType10(uid, id, pagesize, title);
            case 11:
                //我咨询的 进行中
                return findByDoctorType11(uid, 0, id, pagesize, title);
            case 12:
                //我咨询的 已结束中
                return findByDoctorType11(uid, 1, id, pagesize, title);
        }
        return null;
    }
    private Page<ConsultTeam> findByDoctorType10(String uid, long id, int pagesize,String title) {
    private Page<ConsultTeam> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
            }
        }
    }
    private Page<ConsultTeam> findByDoctorType10(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
@ -883,6 +945,18 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamDao.findUnfinishedConsult(patient);
    }
    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public List<ConsultTeam> getUnfinishedConsult(String patient, String doctor) {
        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
    }
    /**
     * 查询患者全部的咨询数目
     *
@ -916,28 +990,46 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamLogDao.findOne(logId);
    }
    public boolean isExistFamousConsult(String uid) {
        ConsultTeam consultTeam = consultTeamDao.findFamousConsultByPatient(uid);
        if (consultTeam != null) {
    public boolean isExistConsult(String uid, String doctor) {
        int consultTeam = consultTeamDao.countByPatient(uid, doctor);
        if (consultTeam > 0) {
            return true;
        } else {
            return false;
        }
    }
    public void addFamousTeamConsult(ConsultTeam ct, String uid) throws Exception {
    /**
     * @param ct
     * @param uid
     * @param type 1患者 2医生
     * @throws Exception
     */
    public void addFamousTeamConsult(ConsultTeam ct, String uid, String type) throws Exception {
        // 设置患者信息
        ct.setPatient(uid);
        // 查询患者信息
        Patient tempPatient = patientDao.findByCode(uid);
        // 设置患者姓名
        ct.setName(tempPatient.getName());
        // 设置患者生日
        ct.setBirthday(tempPatient.getBirthday());
        //新增性别
        ct.setSex(tempPatient.getSex());
        // 设置患者头像
        ct.setPhoto(tempPatient.getPhoto());
        if ("1".equals(type)) {
            // 查询患者信息
            Patient tempPatient = patientDao.findByCode(uid);
            // 设置患者姓名
            ct.setName(tempPatient.getName());
            // 设置患者生日
            ct.setBirthday(tempPatient.getBirthday());
            //新增性别
            ct.setSex(tempPatient.getSex());
            // 设置患者头像
            ct.setPhoto(tempPatient.getPhoto());
        } else if ("2".equals(type)) {
            Doctor doctorTemp = doctorDao.findByCode(uid);
            // 设置医生姓名
            ct.setName(doctorTemp.getName());
            // 设置医生生日
            ct.setBirthday(doctorTemp.getBirthday());
            //新增性别
            ct.setSex(doctorTemp.getSex());
            // 设置医生头像
            ct.setPhoto(doctorTemp.getPhoto());
        }
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");

+ 61 - 2
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyMemberService.java

@ -324,6 +324,65 @@ public class FamilyMemberService extends BaseService {
        return resultArray;
    }
    /**
     * 获取居民的家庭成员
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientMembers(String patient, String doctorCode, boolean isContain, String current) {
        JSONArray resultArray = getPatientFamilyMembers(patient,doctorCode);
        if(resultArray == null){
            resultArray = new JSONArray();
        }
        if (isContain && !patient.equals(current)) {
            Patient p = patientDao.findByCode(patient);
            JSONObject obj = new JSONObject();
            List<SignFamily> signs = contractService.findAllSignByPatient(p.getCode());
            boolean ssSign = false;
            boolean jtSign = false;
            for (SignFamily sign : signs) {
                if (sign.getType() == 1 && sign.getStatus() > 0) {
                    ssSign = true;
                } else if (sign.getType() == 2 && sign.getStatus() > 0) {
                    jtSign = true;
                } else if (sign.getStatus() == 0) {
                }
            }
            obj.put("code", p.getCode());
            obj.put("name", p.getName());
            obj.put("sex", p.getSex());
            obj.put("birthday", p.getBirthday());
            obj.put("idcard", StringUtils.isEmpty(p.getIdcard()) ? "" : p.getIdcard());
            obj.put("photo", StringUtils.isEmpty(p.getPhoto()) ? "" : p.getPhoto());
            obj.put("mobile", StringUtils.isEmpty(p.getMobile()) ? "" : p.getMobile());
            obj.put("address", StringUtils.isEmpty(p.getAddress()) ? "" : p.getAddress());
            obj.put("familyRelation", "-1");
            obj.put("familyRelationName", "自己");
            if (ssSign && jtSign) {
                obj.put("signType", 3);
            } else if (!ssSign && jtSign) {
                obj.put("signType", 2);
            } else if (ssSign && !jtSign) {
                obj.put("signType", 1);
            } else {
                obj.put("signType", 0);
            }
            resultArray.put(obj);
        }
        return resultArray;
    }
    /**
     * 查询居民的某个家庭成员
     *
@ -331,8 +390,8 @@ public class FamilyMemberService extends BaseService {
     * @param family
     * @return
     */
    public PatientFamilyMember getPatientFamilyMember(String patient,String family) {
        PatientFamilyMember member = memberDao.findByPatientAndFamilyMember(patient,family);
    public PatientFamilyMember getPatientFamilyMember(String patient, String family) {
        PatientFamilyMember member = memberDao.findByPatientAndFamilyMember(patient, family);
        return member;
    }

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

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

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

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

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

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

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

@ -0,0 +1,96 @@
package com.yihu.wlyy.service.app.health;
import com.yihu.wlyy.entity.education.HealthEduArticle;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * 健康教育患者业务逻辑类
 * @author linz
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class HealthEduArticlePatientService extends BaseService {
	@Autowired
	private HealthEduArticlePatientDao healthEduArticlePatientDao;
	/**
	 * 根据文章标示获取数据
	 * @param article
	 * @return
	 *
	 */
	@Deprecated
	public HealthEduArticlePatient findByArticle(String article) {
		return healthEduArticlePatientDao.findByArticle(article);
	}
	/**
	 * 根据文章id获取数据
	 * @param id
	 * @return
	 */
	public HealthEduArticlePatient findById(Long id) {
		return healthEduArticlePatientDao.findOne(id);
	}
	public List<HealthEduArticlePatient> findByArticleAndPatient(String article,String patient) {
		return healthEduArticlePatientDao.findByArticleAndPatient(article, patient);
	}
	/**
	 * 查询患者文章
	 * @param patient 患者标识
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<HealthEduArticlePatient> findByPatient(String patient, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		// 患者过滤
		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		Specification<HealthEduArticlePatient> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticlePatient.class);
		return healthEduArticlePatientDao.findAll(spec, pageRequest);
	}
	/**
	 * 文章更新为已读
	 * @param patient
	 * @param article
	 * @return
	 */
	public int updateRead(String patient, String article) {
		return healthEduArticlePatientDao.updateRead(patient, article);
	}
}

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

@ -1,16 +1,18 @@
package com.yihu.wlyy.service.app.health;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.util.*;
import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
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;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
@ -36,6 +38,12 @@ public class HealthEduArticleService extends BaseService {
	private HealthEduArticleDao healthEduArticleDao;
	@Autowired
	private HealthEduArticlePatientDao healthEduArticlePatientDao;
	@Autowired
	private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
	@Autowired
	private HealthEduArticleLabelService healthEduArticleLabelService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
	 * 查询文章信息
@ -52,46 +60,45 @@ public class HealthEduArticleService extends BaseService {
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	public Page<HealthEduArticle> findAll(long id, int pagesize) {
	public List<Map<String, Object>> findAll(int page, int pagesize,String filter,String doctor,String patient) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		if(page<0){
			page = 0;
		}
		Specification<HealthEduArticle> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticle.class);
		return healthEduArticleDao.findAll(spec, pageRequest);
	}
	/**
	 * 查询患者文章
	 * @param patient 患者标识
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<HealthEduArticlePatient> findByPatient(String patient, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.content,a.keyword");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 1) as readAmount");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 2) as collectionAmount");
		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 3) as repeatAmount");
		sql.append(",(select count(1) from wlyy_health_edu_article_doctor c where c.article = a.code and c.doctor =?) as collection");
		params.add(doctor);
		if(StringUtils.isNotBlank(patient)) {
			sql.append(",(select count(1) from wlyy_health_edu_article_patient c where c.article = a.code and c.doctor = ? and c.patient= ? ) as send");
			params.add(doctor);
			params.add(patient);
		}
		// 排序
		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("patient", Operator.EQ, patient));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		sql.append(" from wlyy_health_edu_article a ");//内联取文章内容
		String where = " ";
		if(StringUtils.isNotBlank(filter)){
			//记录搜索记录
			healthEduArticleLabelService.saveOrUpdateLabel(filter,doctor);
			filter="%"+filter+"%";
			where+=" where ( a.title like ? or a.keyword like ? )";
			params.add(filter);
			params.add(filter);
		}
		Specification<HealthEduArticlePatient> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticlePatient.class);
		return healthEduArticlePatientDao.findAll(spec, pageRequest);
		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;
	}
	/**
@ -111,11 +118,16 @@ public class HealthEduArticleService extends BaseService {
	 */
	public int send(List<HealthEduArticlePatient> list) {
		Iterable<HealthEduArticlePatient> iterable = healthEduArticlePatientDao.save(list);
		//记录转发量
		for(HealthEduArticlePatient healthEduArticlePatient:list){
			healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.REPEAT_STATUS,healthEduArticlePatient.getArticle(),healthEduArticlePatient.getTitle(),healthEduArticlePatient.getDoctor());
		}
		Iterator<HealthEduArticlePatient> iterator = iterable.iterator();
		if (iterator.hasNext()) {
			return 1;
		} else {
			return 0;
		}
	}
}

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

@ -47,6 +47,9 @@ public class PatientHealthGuidanceService extends BaseService {
			Patient p = patientDao.findByCode(guidance.getPatient());
			obj.put("doctorName",doc.getName());
			obj.put("photo",doc.getPhoto());
			obj.put("name",doc.getName());
			obj.put("level",doc.getLevel());
			obj.put("patientName",p.getName());
			obj.put("czrq",guidance.getCzrq()!= null ? DateUtil.dateToStr(guidance.getCzrq(),DateUtil.YYYY_MM_DD_HH_MM) :"");
			return obj;

+ 38 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/hospital/HospitalDeptService.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.service.app.hospital;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.organization.HospitalDept;
import com.yihu.wlyy.repository.organization.HospitalDeptDao;
import com.yihu.wlyy.service.BaseService;
@ -10,12 +11,16 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -27,6 +32,8 @@ import java.util.Map;
public class HospitalDeptService extends BaseService {
    @Autowired
    private HospitalDeptDao hospitalDeptDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    public Page<HospitalDept> findDeptByHsoptail(String hospital, String key, long id, int pageSize) {
        if (pageSize <= 0) {
@ -50,4 +57,35 @@ public class HospitalDeptService extends BaseService {
        Specification<HospitalDept> spec = DynamicSpecifications.bySearchFilter(filters.values(), HospitalDept.class);
        return hospitalDeptDao.findAll(spec,pageRequest);
    }
    /**
     * 查询科室列表
     *
     * @param hospital
     * @param key
     * @param page
     * @param pagesize
     * @return
     */
    public List<HospitalDept> getHospitalDept(String hospital, String key, int page, int pagesize){
        String sql = "select * from dm_hospital_dept " +
                " where" +
                "    exists (select * from wlyy_doctor where wlyy_doctor.dept = dm_hospital_dept.code)" +
                " and hospital = ? ";
        List<Object> args = new ArrayList<>();
        args.add(hospital);
        if(StringUtils.isNotEmpty(key)){
            sql += " and name like ? ";
            args.add("%" + key + "%");
        }
        sql += " limit "+ (page*pagesize) + "," + pagesize;
        List<HospitalDept> hosList = jdbcTemplate.query(sql,args.toArray(),new BeanPropertyRowMapper(HospitalDept.class));
        return hosList;
    }
}

+ 50 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/hospital/HospitalService.java

@ -1,11 +1,14 @@
package com.yihu.wlyy.service.app.hospital;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.repository.address.TownDao;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
@ -13,6 +16,8 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
@ -31,6 +36,8 @@ public class HospitalService extends BaseService {
	private HospitalDao hospitalDao;
	@Autowired
	private TownDao townDao;
	@Autowired
	JdbcTemplate jdbcTemplate;
	/**
	 * 获取医院列表
@ -71,4 +78,47 @@ public class HospitalService extends BaseService {
	public List<Hospital> getHositalByTownCode(String town) {
		return hospitalDao.findByTownCode(town);
	}
	/**
	 * 查询医院列表
	 *
	 * @param type
	 * @param province
	 * @param city
	 * @param town
	 * @param key
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public List<Hospital> getHospitals(int type,String province,String city,String town,String key,int page,int pagesize){
		String sql = "select * from dm_hospital where exists (select * from wlyy_doctor where wlyy_doctor.hospital = dm_hospital.code) and level = ? ";
		List<Object> args = new ArrayList<>();
		args.add(type);
		if(StringUtils.isNotEmpty(province)){
			sql += " and province = ? ";
			args.add(province);
		}
		if(StringUtils.isNotEmpty(city)){
			sql += " and city = ? ";
			args.add(city);
		}
		if(StringUtils.isNotEmpty(town)){
			sql += " and town = ? ";
			args.add(town);
		}
		if(StringUtils.isNotEmpty(key)){
			sql += " and name like ? ";
			args.add("%" + key + "%");
		}
		sql += " limit "+ (page*pagesize) + "," + pagesize;
		List<Hospital> hosList = jdbcTemplate.query(sql,args.toArray(),new BeanPropertyRowMapper(Hospital.class));
		return hosList;
	}
}

+ 217 - 207
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java

@ -1,6 +1,7 @@
package com.yihu.wlyy.service.app.label;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
@ -14,6 +15,7 @@ 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.service.BaseService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdCardUtil;
import org.apache.commons.beanutils.converters.CalendarConverter;
@ -57,6 +59,8 @@ public class SignPatientLabelInfoService extends BaseService {
    SignFamilyDao signFamilyDao;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    AdminTeamService adminTeamService;
    /**
     * 查询单个居民信息
@ -69,7 +73,7 @@ public class SignPatientLabelInfoService extends BaseService {
        JSONObject json = new JSONObject();
        Patient p = patientDao.findByCode(patient);
        if(p == null){
        if (p == null) {
            throw new Exception("patient info can not find");
        }
@ -81,6 +85,8 @@ public class SignPatientLabelInfoService extends BaseService {
        json.put("name", p.getName());
        // 设置患者手机号
        json.put("mobile", p.getMobile());
        // 设置患者微信openid
        json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
        // 设置患者联系电话
        json.put("phone", p.getPhone());
        // 设置患者头像
@ -94,18 +100,18 @@ public class SignPatientLabelInfoService extends BaseService {
        // 社保号
        json.put("ssc", p.getSsc());
        if(signs != null && signs.size() > 0){
        if (signs != null && signs.size() > 0) {
            SignFamily ssSign = null;
            SignFamily familySign = null;
            for(SignFamily sign : signs){
                if(sign.getType() == 1){
            for (SignFamily sign : signs) {
                if (sign.getType() == 1) {
                    ssSign = sign;
                } else if(sign.getType() == 2){
                } else if (sign.getType() == 2) {
                    familySign = sign;
                }
            }
            if(ssSign != null) {
            if (ssSign != null) {
                // 设置患者紧急联系人
                json.put("emerMobile", StringUtils.isEmpty(ssSign.getEmerMobile()) ? "" : String.valueOf(ssSign.getEmerMobile()));
                // 设置签约日期
@ -115,7 +121,7 @@ public class SignPatientLabelInfoService extends BaseService {
                // 设置签约状态
                json.put("ssStatus", ssSign.getStatus());
            }
            if(familySign != null){
            if (familySign != null) {
                // 设置患者紧急联系人
                json.put("emerMobile", StringUtils.isEmpty(familySign.getEmerMobile()) ? "" : String.valueOf(familySign.getEmerMobile()));
                // 设置签约日期
@ -133,14 +139,18 @@ public class SignPatientLabelInfoService extends BaseService {
                // 设置签约状态
                json.put("familyStatus", familySign.getStatus());
                if("1".equals(familySign.getExpensesStatus())){
                if ("1".equals(familySign.getExpensesStatus())) {
                    json.put("qyrq", familySign.getExpensesTime() != null ? DateUtil.dateToStr((Date) familySign.getExpensesTime(), DateUtil.YYYY_MM_DD) : "");
                }
            }
            if (json.has("expensesStatus") && (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0"))) {
                String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                String epTime = "";
                try {
                    epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (StringUtils.isEmpty(epTime)) {
                    json.put("expensesRemindStatus", 0);
                } else {
@ -181,7 +191,7 @@ public class SignPatientLabelInfoService extends BaseService {
            sql = "select * " +
                    " from " +
                    "     wlyy_sign_family " +
                    " where " + (doc.getLevel() == 2 ? " doctor" : "doctor_health") + " = ? and status > 0 and admin_team_code = ? ";
                    " where repdoctor = ? and status > 0 and admin_team_code = ? ";
            if (labelCode.equals("1")) {
                int week = today.get(Calendar.DAY_OF_WEEK) - 2;
@ -204,7 +214,7 @@ public class SignPatientLabelInfoService extends BaseService {
                throw new Exception("label is not exist");
            }
            args = new Object[]{doctor, teamCode};
            args = new Object[]{doctor, teamCode, doctor, teamCode};
        } else {
            if (labelCode.equals("0")) {
                sql = "SELECT " +
@ -212,17 +222,15 @@ public class SignPatientLabelInfoService extends BaseService {
                        " FROM " +
                        "    wlyy_sign_family t1 " +
                        " left join " +
                        "    (select patient,label,label_type from wlyy_sign_patient_label_info where patient in " +
                        "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + "='" + doctor + "' and status > 0) " +
                        "     and label_type = ? and status = 1) t2 " +
                        "    (select repl.patient,repl.label,repl.label_type,repl.label_name from wlyy_sign_family repf left join wlyy_sign_patient_label_info repl on repf.patient = repl.patient where repf.repdoctor = '" + doctor + "' and repf.status > 0 and repl.label_type = ?) t2 " +
                        " on t1.patient = t2.patient " +
                        " WHERE " +
                        "    t2.patient is null " +
                        "    AND t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                        "    AND t1.repdoctor = ? " +
                        "    AND t1.status > 0 " +
                        "    AND t1.admin_team_code = ? limit " + start + "," + pagesize;
                        "    AND t1.admin_team_code = ? ";
                args = new Object[]{labelType, doctor, teamCode};
                args = new Object[]{labelType, doctor, teamCode, labelType, doctor, teamCode};
            } else {
                sql = "SELECT " +
                        "    t1.* " +
@ -230,19 +238,23 @@ public class SignPatientLabelInfoService extends BaseService {
                        "    wlyy_sign_family t1, " +
                        "    wlyy_sign_patient_label_info t2 " +
                        " WHERE " +
                        "     t2.patient in (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0 ) " +
                        "    AND t2.label = ? " +
                        "    t2.label = ? " +
                        "    AND t2.label_type = ? " +
                        "    AND t2.status = 1 " +
                        "    AND t1.patient = t2.patient " +
                        "    AND t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                        "    AND t1.repdoctor = ? " +
                        "    AND t1.status > 0 " +
                        "    AND t1.admin_team_code = ? limit " + start + "," + pagesize;
                        "    AND t1.admin_team_code = ? ";
                args = new Object[]{labelCode, labelType, doctor, teamCode};
                args = new Object[]{labelCode, labelType, doctor, teamCode, labelCode, labelType, doctor, teamCode};
            }
        }
        String sqlDoc = sql.replaceAll("repdoctor", "doctor");
        String sqlDocHealth = sql.replaceAll("repdoctor", "doctor_health").replaceAll("t1", "t3").replaceAll("t2", "t4").replaceAll("repf", "repf1").replaceAll("repl", "repl1");
        sql = "select t.* from (" + sqlDoc + " union all " + sqlDocHealth + ") t limit " + start + "," + pagesize;
        signList = jdbcTemplate.queryForList(sql, args);
        if (signList != null && signList.size() > 0) {
@ -262,11 +274,11 @@ public class SignPatientLabelInfoService extends BaseService {
                    if (String.valueOf(sign.get("type")).equals("2")) {
                        jsonP.put("qyrq", sign.get("apply_date") != null ? DateUtil.dateToStr((Date) sign.get("apply_date"), DateUtil.YYYY_MM_DD) : "");
                        // 缴费情况
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")): "0");
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")) : "0");
                        // 缴费时间
                        jsonP.put("expensesTime", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD_HH_MM) : "");
                        // 缴费类型
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")): "");
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")) : "");
                        if (StringUtils.isEmpty(String.valueOf(jsonP.get("expensesStatus"))) || String.valueOf(jsonP.get("expensesStatus")).equals("0")) {
                            String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
@ -290,6 +302,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("name", p.getName());
                // 设置患者手机号
                json.put("mobile", p.getMobile());
                // 设置患者微信openid
                json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
                // 设置患者联系电话
                json.put("phone", p.getPhone());
                // 设置患者紧急联系人
@ -308,7 +322,7 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("idcard", p.getIdcard());
                // 社保号
                json.put("ssc", p.getSsc());
                if(String.valueOf(sign.get("type")).equals("2")) {
                if (String.valueOf(sign.get("type")).equals("2")) {
                    // 缴费情况
                    json.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")) : "0");
                    // 缴费时间
@ -320,14 +334,21 @@ public class SignPatientLabelInfoService extends BaseService {
//                    json.put("qyrq", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD) : "");
//                }
                    if (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0")) {
                        String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        String epTime = "";
                        try {
                            epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (StringUtils.isEmpty(epTime)) {
                            json.put("expensesRemindStatus", 0);
                        } else {
                            json.put("expensesRemindStatus", new SimpleDateFormat("yyyy-MM-dd").format(new Date()).equals(epTime) ? 1 : 0);
                        }
                    }
                } else {
                    // 缴费情况
                    json.put("expensesStatus", "1");
                }
                // 患者标签
                //json.put("labels", labels == null ? "" : labels);
@ -363,12 +384,13 @@ public class SignPatientLabelInfoService extends BaseService {
        Object[] args = null;
        sql = " select * from wlyy_sign_family where " +
                (doc.getLevel() == 2 ? " doctor" : "doctor_health") +
                " = ? and status > 0 and admin_team_code = ? " +
                " limit " + start + "," + pagesize;
                " repdoctor = ? and status > 0 and admin_team_code = ? ";
        args = new Object[]{doctor, teamCode};
        String sqlDoc = sql.replaceAll("repdoctor", "doctor");
        String sqlDocHealth = sql.replaceAll("repdoctor", "doctor_health");
        args = new Object[]{doctor, teamCode, doctor, teamCode};
        sql = "select t.* from (" + sqlDoc + " union all " + sqlDocHealth + ") t limit " + start + "," + pagesize;
        signList = jdbcTemplate.queryForList(sql, args);
        if (signList != null && signList.size() > 0) {
@ -388,11 +410,11 @@ public class SignPatientLabelInfoService extends BaseService {
                    if (String.valueOf(sign.get("type")).equals("2")) {
                        jsonP.put("qyrq", sign.get("apply_date") != null ? DateUtil.dateToStr((Date) sign.get("apply_date"), DateUtil.YYYY_MM_DD) : "");
                        // 缴费情况
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")): "0");
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")) : "0");
                        // 缴费时间
                        jsonP.put("expensesTime", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD_HH_MM) : "");
                        // 缴费类型
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")): "");
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")) : "");
                        if (StringUtils.isEmpty(String.valueOf(jsonP.get("expensesStatus"))) || String.valueOf(jsonP.get("expensesStatus")).equals("0")) {
                            String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
@ -429,6 +451,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("name", p.getName());
                // 设置患者手机号
                json.put("mobile", p.getMobile());
                // 设置患者微信openid
                json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
                // 设置患者联系电话
                json.put("phone", p.getPhone());
                // 设置患者紧急联系人
@ -447,7 +471,7 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("idcard", p.getIdcard());
                // 社保号
                json.put("ssc", p.getSsc());
                if(String.valueOf(sign.get("type")).equals("2")) {
                if (String.valueOf(sign.get("type")).equals("2")) {
                    // 缴费情况
                    json.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")) : "0");
                    // 缴费时间
@ -458,14 +482,21 @@ public class SignPatientLabelInfoService extends BaseService {
//                    json.put("qyrq", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD) : "");
//                }
                    if (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0")) {
                        String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        String epTime = "";
                        try {
                            epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (StringUtils.isEmpty(epTime)) {
                            json.put("expensesRemindStatus", 0);
                        } else {
                            json.put("expensesRemindStatus", new SimpleDateFormat("yyyy-MM-dd").format(new Date()).equals(epTime) ? 1 : 0);
                        }
                    }
                } else {
                    // 缴费情况
                    json.put("expensesStatus", "1");
                }
                // 患者标签
                json.put("labels", labels == null ? "" : labels);
@ -523,10 +554,10 @@ public class SignPatientLabelInfoService extends BaseService {
                    Calendar today = Calendar.getInstance();
                    Calendar startDate = Calendar.getInstance();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    sql = "select count(DISTINCT patient) count" +
                    sql = "select *" +
                            " from " +
                            "     wlyy_sign_family " +
                            " where " + (doc.getLevel() == 2 ? " doctor" : "doctor_health") + " = ? and status > 0 " +
                            " where repdoctor = ? and status > 0 " +
                            (teamCode > 0 ? " and admin_team_code = ? " : "");
                    if (label.getLabelCode().equals("1")) {
@ -549,56 +580,58 @@ public class SignPatientLabelInfoService extends BaseService {
                        throw new Exception("label is not exist");
                    }
                    if (teamCode > 0) {
                        args = new Object[]{doctor, teamCode};
                        args = new Object[]{doctor, teamCode, doctor, teamCode};
                    } else {
                        args = new Object[]{doctor};
                        args = new Object[]{doctor, doctor};
                    }
                } else {
                    if (label.getLabelCode().equals("0")) {
                        sql = " SELECT " +
                                "     count(DISTINCT t1.patient) count " +
                                "     t1.* " +
                                " FROM" +
                                "     wlyy_sign_family t1 " +
                                " left join " +
                                "    (SELECT patient,label,label_type from wlyy_sign_patient_label_info where patient in " +
                                "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                                "    and label_type = ? and status = 1)  t2 " +
                                "    (select repl.patient,repl.label,repl.label_type,repl.label_name from wlyy_sign_family repf left join wlyy_sign_patient_label_info repl on repf.patient = repl.patient where  repf.repdoctor = '" + doctor + "' and repf.status > 0 and repl.label_type = ?) t2 " +
                                " on t1.patient = t2.patient " +
                                " WHERE" +
                                "     t2.patient is null " +
                                "     AND t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                                "     AND t1.repdoctor = ? " +
                                "     AND t1.status > 0 " +
                                (teamCode > 0 ? "    AND t1.admin_team_code = ? " : "");
                        if (teamCode > 0) {
                            args = new Object[]{labelType, doctor, teamCode};
                            args = new Object[]{labelType, doctor, teamCode, labelType, doctor, teamCode};
                        } else {
                            args = new Object[]{labelType, doctor};
                            args = new Object[]{labelType, doctor, labelType, doctor};
                        }
                    } else {
                        sql = " SELECT " +
                                "     count(DISTINCT t1.patient) count " +
                                "     t1.* " +
                                " FROM" +
                                "     wlyy_sign_family t1, " +
                                "     wlyy_sign_patient_label_info t2 " +
                                " WHERE" +
                                "     t1.patient = t2.patient " +
                                "     AND t2.patient in (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                                "     AND t2.label = ? " +
                                "     AND t2.label_type = ? " +
                                "     AND t2.status = 1 " +
                                "     AND t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                                "     AND t1.repdoctor = ? " +
                                "     AND t1.status > 0 " +
                                (teamCode > 0 ? "    AND t1.admin_team_code = ? " : "");
                        if (teamCode > 0) {
                            args = new Object[]{label.getLabelCode(), labelType, doctor, teamCode};
                            args = new Object[]{label.getLabelCode(), labelType, doctor, teamCode, label.getLabelCode(), labelType, doctor, teamCode};
                        } else {
                            args = new Object[]{label.getLabelCode(), labelType, doctor};
                            args = new Object[]{label.getLabelCode(), labelType, doctor, label.getLabelCode(), labelType, doctor};
                        }
                    }
                }
                String sqlDoc = sql.replaceAll("repdoctor", "doctor");
                String sqlDocHealth = sql.replaceAll("repdoctor", "doctor_health").replaceAll("t1", "t3").replaceAll("t2", "t4").replaceAll("repf", "repf1").replaceAll("repl", "repl1");
                sql = "select count(DISTINCT t.patient) count from (" + sqlDoc + " union all " + sqlDocHealth + ") t";
                List<Map<String, Object>> count = jdbcTemplate.queryForList(sql, args);
                if (count != null && count.size() > 0 && count.get(0).containsKey("count")) {
@ -817,33 +850,35 @@ public class SignPatientLabelInfoService extends BaseService {
        List<Map<String, Object>> signList = new ArrayList<>();
        page = page * pagesize;
        Object[] args = null;
        String sql = "SELECT " +
        String sql = "select " +
                "    t1.* " +
                " FROM " +
                "    wlyy_sign_family t1 " +
                (StringUtils.isNotEmpty(labelCode) || StringUtils.isNotEmpty(labelType) ?
                        " join " : " left join ") +
                "    (select patient,label,label_name,label_type from wlyy_sign_patient_label_info  where patient in" +
                "    (select patient from wlyy_sign_family where " + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = '" + doctor + "' and status > 0) " +
                "     and status = 1 " +
                (StringUtils.isNotEmpty(labelCode) ? " AND label = ? " : "") +
                (StringUtils.isNotEmpty(labelType) ? " AND label_type = ? " : "") + ") t2" +
                "    wlyy_sign_patient_label_info t2 " +
                " ON t1.patient = t2.patient " +
                " WHERE " +
                "    t1." + (doc.getLevel() == 2 ? "doctor" : "doctor_health") + " = ? " +
                "    t1.repdoctor = ? " +
                "    AND t1.status > 0 " +
                "    AND (" + (StringUtils.isNotEmpty(labelCode) || StringUtils.isNotEmpty(labelType) ? "" : " t2.patient is null OR ") + " t2.status = 1) " +
                (StringUtils.isNotEmpty(labelCode) ? " AND t2.label = ? " : "") +
                (StringUtils.isNotEmpty(labelType) ? " AND t2.label_type = ? " : "") +
                (teamCode > 0 ? (" AND admin_team_code = " + teamCode) : "") +
                "    AND (t1.name like ? OR t2.label_name like ?) " +
                " limit " + page + "," + pagesize;
                "  AND (t1.name like ? or t2.label_name like ?) ";
        if (StringUtils.isNotEmpty(labelCode)) {
            args = new Object[]{labelCode, labelType, doctor, "%" + filter + "%", "%" + filter + "%"};
            args = new Object[]{doctor, labelCode, labelType, "%" + filter + "%", "%" + filter + "%", doctor, labelCode, labelType, "%" + filter + "%", "%" + filter + "%"};
        } else if (StringUtils.isEmpty(labelCode) && StringUtils.isNotEmpty(labelType)) {
            args = new Object[]{labelType, doctor, "%" + filter + "%", "%" + filter + "%"};
            args = new Object[]{doctor, labelType, "%" + filter + "%", "%" + filter + "%", doctor, labelType, "%" + filter + "%", "%" + filter + "%"};
        } else {
            args = new Object[]{doctor, "%" + filter + "%", "%" + filter + "%"};
            args = new Object[]{doctor, "%" + filter + "%", "%" + filter + "%", doctor, "%" + filter + "%", "%" + filter + "%"};
        }
        String sqlDoc = sql.replaceAll("repdoctor", "doctor");
        String sqlDocHealth = sql.replaceAll("repdoctor", "doctor_health").replaceAll("t1", "t3").replaceAll("t2", "t4");
        sql = "select DISTINCT t.* from (" + sqlDoc + " union all " + sqlDocHealth + ") t limit " + page + "," + pagesize;
        signList = jdbcTemplate.queryForList(sql, args);
        if (signList != null && signList.size() > 0) {
@ -863,11 +898,11 @@ public class SignPatientLabelInfoService extends BaseService {
                    if (String.valueOf(sign.get("type")).equals("2")) {
                        jsonP.put("qyrq", sign.get("apply_date") != null ? DateUtil.dateToStr((Date) sign.get("apply_date"), DateUtil.YYYY_MM_DD) : "");
                        // 缴费情况
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")): "0");
                        jsonP.put("expensesStatus", sign.get("expenses_status") != null ? String.valueOf(sign.get("expenses_status")) : "0");
                        // 缴费时间
                        jsonP.put("expensesTime", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD_HH_MM) : "");
                        // 缴费类型
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")): "");
                        jsonP.put("expensesType", sign.get("expenses_type") != null ? String.valueOf(sign.get("expenses_type")) : "");
                        if (StringUtils.isEmpty(String.valueOf(jsonP.get("expensesStatus"))) || String.valueOf(jsonP.get("expensesStatus")).equals("0")) {
                            String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
@ -896,13 +931,8 @@ public class SignPatientLabelInfoService extends BaseService {
                    }
                }
                List<SignPatientLabelInfo> labels = labelInfoDao.findByPatientAndStatus(sign.get("patient").toString(), 1);
                if (StringUtils.isEmpty(exLabelCode) || StringUtils.isEmpty(exLabelType)) {
                }
                JSONObject json = new JSONObject();
                // 设置患者标识
@ -911,6 +941,8 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("name", p.getName());
                // 设置患者手机号
                json.put("mobile", p.getMobile());
                // 设置患者微信openid
                json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
                // 设置患者联系电话
                json.put("phone", p.getPhone());
                // 设置患者紧急联系人
@ -940,14 +972,21 @@ public class SignPatientLabelInfoService extends BaseService {
//                    json.put("qyrq", sign.get("expenses_time") != null ? DateUtil.dateToStr((Date) sign.get("expenses_time"), DateUtil.YYYY_MM_DD) : "");
//                }
                    if (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0")) {
                        String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        String epTime = "";
                        try {
                            epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (StringUtils.isEmpty(epTime)) {
                            json.put("expensesRemindStatus", 0);
                        } else {
                            json.put("expensesRemindStatus", new SimpleDateFormat("yyyy-MM-dd").format(new Date()).equals(epTime) ? 1 : 0);
                        }
                    }
                } else {
                    // 缴费情况
                    json.put("expensesStatus", "1");
                }
                // 患者标签
                json.put("labels", labels == null ? "" : labels);
@ -959,6 +998,110 @@ public class SignPatientLabelInfoService extends BaseService {
        return result.size() > 0 ? new JSONArray(result.values()) : new JSONArray();
    }
    /**
     * 查询所有团队下患者
     *
     * @param filter 搜索关键字
     * @param doctor 医生
     * @return
     */
    public JSONArray searchTeamsPatients(String filter, String doctor, long teamCode, int page, int pagesize) throws Exception {
        JSONArray reArray = new JSONArray();
        Map<String, JSONArray> map = new HashMap<>();
        Map<Long, AdminTeam> teamMap = new HashMap<>();
        List<AdminTeam> teams = null;
        int start = page * pagesize;
        int size = pagesize;
        if (teamCode > 0) {
            teams = new ArrayList<>();
            AdminTeam team = adminTeamService.getTeam(teamCode);
            if (team == null) {
                throw new Exception("adminTeam is not exist");
            }
            teams.add(team);
        } else {
            teams = adminTeamService.getDoctorTeams(doctor);
        }
        String sql = "select distinct t.* from (" +
                " select " +
                "     f.patient " +
                "     ,f.name " +
                "     ,f.openid " +
                "     ,f.admin_team_code " +
                "     ,p.sex " +
                "     ,p.idcard " +
                "     ,p.photo " +
                " from " +
                "     wlyy_sign_family f,wlyy_patient p " +
                " where " +
                "      f.patient = p.code and f.doctor = ? and f.admin_team_code = ? and f.status > 0 and f.name like ? " +
                " union all " +
                "select " +
                "     f1.patient " +
                "     ,f1.name " +
                "     ,f1.openid " +
                "     ,f1.admin_team_code " +
                "     ,p1.sex " +
                "     ,p1.idcard " +
                "     ,p1.photo " +
                " from " +
                "     wlyy_sign_family f1,wlyy_patient p1" +
                " where " +
                "     f1.patient = p1.code and f1.doctor_health = ? and f1.admin_team_code = ? and f1.status > 0 and f1.name like ? " +
                ") t " + (page < 0 ? "" : "limit " + start + "," + size);
        if (teams != null) {
            for (AdminTeam team : teams) {
                teamMap.put(team.getId(), team);
                List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{doctor, team.getId(),
                        "%" + filter + "%", doctor, team.getId(), "%" + filter + "%"});
                if (result != null && result.size() > 0) {
                    for (Map<String, Object> p : result) {
                        JSONObject pJson = new JSONObject();
                        pJson.put("code", p.get("patient"));
                        pJson.put("name", p.get("name") != null ? p.get("name") : "");
                        pJson.put("openid", p.get("openid") != null ? p.get("openid") : "");
                        pJson.put("adminTeamCode", p.get("admin_team_code") != null ? p.get("admin_team_code") : "");
                        pJson.put("sex", p.get("sex") != null ? p.get("sex") : "");
                        pJson.put("age", p.get("idcard") != null ? IdCardUtil.getAgeForIdcard(String.valueOf(p.get("idcard"))) : "");
                        pJson.put("photo", p.get("photo") != null ? p.get("photo") : "");
                        List<SignPatientLabelInfo> labels = labelInfoDao.findByPatientAndStatus(String.valueOf(p.get("patient")), 1);
                        pJson.put("labels", labels == null ? "" : labels);
                        if (map.containsKey(String.valueOf(p.get("admin_team_code")))) {
                            JSONArray array = map.get(String.valueOf(p.get("admin_team_code")));
                            array.put(pJson);
                        } else {
                            JSONArray array = new JSONArray();
                            array.put(pJson);
                            map.put(String.valueOf(p.get("admin_team_code")), array);
                        }
                    }
                }
            }
            if (map != null && map.size() > 0) {
                for (String key : map.keySet()) {
                    AdminTeam team = teamMap.get(Long.valueOf(key));
                    JSONObject tJson = new JSONObject();
                    tJson.put("teamCode", team.getId());
                    tJson.put("teamName", team.getName());
                    tJson.put("patients", map.get(key));
                    reArray.put(tJson);
                }
            }
        }
        return reArray;
    }
    /**
     * 添加居民到某个标签
     *
@ -1102,137 +1245,4 @@ public class SignPatientLabelInfoService extends BaseService {
        return 1;
    }
    /**
     * 疾病转标签
     *
     * @return
     */
    public boolean diseaseToLabel() {
        List<PatientDisease> diseases = diseaseDao.findByDel("1");
        Iterator<Patient> patients = patientDao.findAll().iterator();
        Map<String, String> patientNames = new HashMap<>();
        while (patients.hasNext()) {
            Patient p = patients.next();
            patientNames.put(p.getCode(), p.getName());
        }
        for (PatientDisease disease : diseases) {
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            labelInfo.setPatient(disease.getPatient());
            labelInfo.setPname(patientNames.get(disease.getPatient()));
            labelInfo.setLabel(disease.getDisease());
            labelInfo.setLabelName(disease.getDiseaseName());
            labelInfo.setLabelType("3");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            labelInfoDao.save(labelInfo);
        }
        return true;
    }
    /**
     * 分组转标签
     *
     * @return
     */
    public boolean groupToLabel() throws Exception {
        Iterator<Patient> patients = patientDao.findAll().iterator();
        Map<String, Patient> patientNames = new HashMap<>();
        Map<String, SignPatientLabelInfo> normalLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> manbingLabel = new HashMap<>();
        Map<String, SignPatientLabelInfo> sixFiveLabel = new HashMap<>();
        while (patients.hasNext()) {
            Patient p = patients.next();
            patientNames.put(p.getCode(), p);
        }
        List<DoctorPatientGroupInfo> groupInfos = groupInfoDao.findByGroupAndStatus("1", 1);
        for (DoctorPatientGroupInfo groupInfo : groupInfos) {
            Patient p = patientNames.get(groupInfo.getPatient());
            if (p == null) {
                continue;
            }
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            labelInfo.setPatient(p.getCode());
            labelInfo.setPname(p.getName());
            labelInfo.setLabel("1");
            labelInfo.setLabelName("普通人群");
            labelInfo.setLabelType("1");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            normalLabel.put(p.getCode(), labelInfo);
        }
        List<DoctorPatientGroupInfo> groupInfos1 = groupInfoDao.findByGroupAndStatus("2", 1);
        for (DoctorPatientGroupInfo groupInfo : groupInfos1) {
            Patient p = patientNames.get(groupInfo.getPatient());
            if (p == null) {
                continue;
            }
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            labelInfo.setPatient(p.getCode());
            labelInfo.setPname(p.getName());
            labelInfo.setLabel("2");
            labelInfo.setLabelName("慢病人群");
            labelInfo.setLabelType("1");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            manbingLabel.put(p.getCode(), labelInfo);
        }
        List<DoctorPatientGroupInfo> groupInfos2 = groupInfoDao.findByGroupAndStatus("3", 1);
        for (DoctorPatientGroupInfo groupInfo : groupInfos2) {
            Patient p = patientNames.get(groupInfo.getPatient());
            if (p == null) {
                continue;
            }
            SignPatientLabelInfo labelInfo = new SignPatientLabelInfo();
            labelInfo.setPatient(p.getCode());
            labelInfo.setPname(p.getName());
            labelInfo.setLabel("3");
            labelInfo.setLabelName("65岁以上人群");
            labelInfo.setLabelType("1");
            labelInfo.setStatus(1);
            labelInfo.setCzrq(new Date());
            sixFiveLabel.put(p.getCode(), labelInfo);
        }
        if (normalLabel.size() > 0) {
            for (SignPatientLabelInfo labelInfo : normalLabel.values()) {
                labelInfoDao.save(labelInfo);
            }
        }
        if (manbingLabel.size() > 0) {
            for (SignPatientLabelInfo labelInfo : manbingLabel.values()) {
                labelInfoDao.save(labelInfo);
            }
        }
        if (sixFiveLabel.size() > 0) {
            for (SignPatientLabelInfo labelInfo : sixFiveLabel.values()) {
                labelInfoDao.save(labelInfo);
            }
        }
        return true;
    }
}

+ 76 - 67
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/DrugService.java

@ -27,90 +27,99 @@ public class DrugService extends BaseService {
    @Autowired
    SystemDictService systemDictService;
    @Autowired
    EhrService ehrService;
    /**
     * 获取用药记录
     */
    public String getDrugsList(String strSSID, String startNum,String endNum) throws Exception {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return ehrService.getDrugsList(strSSID);
        }
        else {
            String startDate = "1900-01-01";
            String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
            String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
            url = url + "/third/smjk/DrugsList";
        String startDate = "1900-01-01";
        String endDate = DateUtil.dateToStr(DateUtil.getNowDate(), DateUtil.YYYY_MM_DD);
        String url = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
        url = url + "/third/smjk/DrugsList";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strSSID", strSSID));
        params.add(new BasicNameValuePair("startDate", startDate));
        params.add(new BasicNameValuePair("endDate", endDate));
        params.add(new BasicNameValuePair("startNum", startNum));
        params.add(new BasicNameValuePair("endNum", endNum));
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            params.add(new BasicNameValuePair("startDate", startDate));
            params.add(new BasicNameValuePair("endDate", endDate));
            params.add(new BasicNameValuePair("startNum", startNum));
            params.add(new BasicNameValuePair("endNum", endNum));
        String response = HttpClientUtil.post(url, params, "UTF-8");
        JSONArray resultArray = new JSONArray();
        List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
        Map<String, String> systemDictMap = new HashMap<>();
        for (SystemDict systemDict : systemDictList) {
            systemDictMap.put(systemDict.getCode(), systemDict.getValue());
        }
            String response = HttpClientUtil.post(url, params, "UTF-8");
            JSONArray resultArray = new JSONArray();
            List<SystemDict> systemDictList = systemDictService.getDictByDictName("EHR_CATALOG");
            Map<String, String> systemDictMap = new HashMap<>();
            for (SystemDict systemDict : systemDictList) {
                systemDictMap.put(systemDict.getCode(), systemDict.getValue());
            }
        if (!StringUtils.isEmpty(response)){
            JSONObject responseObject = new JSONObject(response);
            int status = responseObject.getInt("status");
            if (status == 200){
                String data = responseObject.getString("data");
                if (!StringUtils.isEmpty(data)){
                    if (data.startsWith("error")) {
                        return data;
                    }
                    JSONObject jsonData = new JSONObject(data);
                    JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                    if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                        for (int i=0; i<jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String patientId = jsonObject.getString("XMAN_ID");
                            String eventNo = jsonObject.getString("EVENT");
                            Integer orgId = jsonObject.getInt("ORG_ID");
                            String key = patientId + eventNo + orgId;
                            JSONObject catalogObject = new JSONObject();
                            String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                            String endTimeNew = jsonObject.get("END_TIME").toString();
                            String catalogValue = systemDictMap.get(catalogCode);
                            jsonObject.remove("CATALOG_CODE");
                            if (jsonObjectMap.containsKey(key)) {
                                jsonObject = jsonObjectMap.get(key);
                                String endTimeOld = jsonObject.get("END_TIME").toString();
                                if (endTimeNew.compareTo(endTimeOld) < 0) {
                                    endTimeNew = endTimeOld;
            if (!StringUtils.isEmpty(response)) {
                JSONObject responseObject = new JSONObject(response);
                int status = responseObject.getInt("status");
                if (status == 200) {
                    String data = responseObject.getString("data");
                    if (!StringUtils.isEmpty(data)) {
                        if (data.startsWith("error")) {
                            return data;
                        }
                        JSONObject jsonData = new JSONObject(data);
                        JSONArray jsonArray = jsonData.getJSONArray("EhrList");
                        if (!jsonArray.isNull(0) && jsonArray.getJSONObject(0).length() != 0) {
                            Map<String, JSONObject> jsonObjectMap = new HashMap<>();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String patientId = jsonObject.getString("XMAN_ID");
                                String eventNo = jsonObject.getString("EVENT");
                                Integer orgId = jsonObject.getInt("ORG_ID");
                                String key = patientId + eventNo + orgId;
                                JSONObject catalogObject = new JSONObject();
                                String catalogCode = jsonObject.get("CATALOG_CODE").toString();
                                String endTimeNew = jsonObject.get("END_TIME").toString();
                                String catalogValue = systemDictMap.get(catalogCode);
                                jsonObject.remove("CATALOG_CODE");
                                if (jsonObjectMap.containsKey(key)) {
                                    jsonObject = jsonObjectMap.get(key);
                                    String endTimeOld = jsonObject.get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) < 0) {
                                        endTimeNew = endTimeOld;
                                    }
                                    catalogObject = jsonObject.getJSONObject("CATALOG");
                                }
                                catalogObject = jsonObject.getJSONObject("CATALOG");
                                catalogObject.put(catalogCode, catalogValue);
                                jsonObject.put("CATALOG", catalogObject);
                                jsonObject.put("END_TIME", endTimeNew);
                                jsonObjectMap.put(key, jsonObject);
                            }
                            catalogObject.put(catalogCode, catalogValue);
                            jsonObject.put("CATALOG", catalogObject);
                            jsonObject.put("END_TIME", endTimeNew);
                            jsonObjectMap.put(key, jsonObject);
                        }
                        for (String key : jsonObjectMap.keySet()) {
                            resultArray.put(jsonObjectMap.get(key));
                        }
                            for (String key : jsonObjectMap.keySet()) {
                                resultArray.put(jsonObjectMap.get(key));
                            }
                        JSONObject temp;
                        for (int i = 0; i < resultArray.length(); i++) {
                            for (int j = i+1; j < resultArray.length(); j++) {
                                String endTimeNew = resultArray.getJSONObject(j).get("END_TIME").toString();
                                String endTimeOld = resultArray.getJSONObject(i).get("END_TIME").toString();
                                if (endTimeNew.compareTo(endTimeOld) > 0) {
                                    temp = resultArray.getJSONObject(i);
                                    resultArray.put(i, resultArray.getJSONObject(j));
                                    resultArray.put(j, temp);  // 两个数交换位置
                            JSONObject temp;
                            for (int i = 0; i < resultArray.length(); i++) {
                                for (int j = i + 1; j < resultArray.length(); j++) {
                                    String endTimeNew = resultArray.getJSONObject(j).get("END_TIME").toString();
                                    String endTimeOld = resultArray.getJSONObject(i).get("END_TIME").toString();
                                    if (endTimeNew.compareTo(endTimeOld) > 0) {
                                        temp = resultArray.getJSONObject(i);
                                        resultArray.put(i, resultArray.getJSONObject(j));
                                        resultArray.put(j, temp);  // 两个数交换位置
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return resultArray.toString();
            return resultArray.toString();
        }
    }
}

+ 832 - 103
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/record/EhrService.java

@ -5,6 +5,7 @@ import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.util.SystemConf;
import org.json.JSONArray;
import org.json.JSONObject;
@ -67,7 +68,6 @@ public class EhrService extends BaseService {
        return re;
    }
    /**
     * 事件基本信息 (主表)
     */
@ -185,6 +185,14 @@ public class EhrService extends BaseService {
                JSONObject catalog = new JSONObject();
                catalog.put("0201","住院诊疗基本信息");
                //catalog.put("0212","入院病历记录");
                JSONObject master = getEventBaseInfo(profileId);
                if(master.has("EHR_000155"))
                {
                    catalog.put("0213","出院小结");
                }
                if(master.has("EHR_000255")) {
                    catalog.put("0217","死亡记录");
                }
                List<String> tables = containTables(profileId);
@ -193,9 +201,7 @@ public class EhrService extends BaseService {
                    catalog.put("0202","住院费用明细");
                }
                if(tables.contains("HDSC02_14")){
                    catalog.put("0213","出院小结");
                }
                if(tables.contains("HDSC02_12")){
                    catalog.put("0214","长期医嘱");
@ -209,9 +215,6 @@ public class EhrService extends BaseService {
                    catalog.put("0216","住院手术记录");
                }
                if(tables.contains("HDSC02_15")){
                    catalog.put("0217","死亡记录");
                }
                if(tables.contains("HDSD02_01")){
                    catalog.put("0221","住院检验报告");
@ -255,7 +258,7 @@ public class EhrService extends BaseService {
                JSONObject item = new JSONObject();
                item.put("END_TIME",jsonObject.has("EHR_000230")?jsonObject.optString("EHR_000230"):jsonObject.optString("event_date")); //入院时间
                item.put("END_TIME",jsonObject.optString("event_date")); //创建时间
                item.put("ORG_NAME",jsonObject.optString("org_name")); //机构名称
                item.put("ORG_CODE",jsonObject.optString("org_code")); //机构代码
                item.put("UNIONSSID",strSSID); //社保卡号
@ -302,16 +305,61 @@ public class EhrService extends BaseService {
        }
    }
    /**
     * 用药记录
     * 用药记录列表
     */
    public String getDrugsList(String idcard) {
        String url = ehrUrl + idcard +"/laboratory?demographic_id="+idcard;
        return HttpClientUtil.get(url, "UTF-8");
    }
    public String getDrugsList(String strSSID) {
        //通过ssid获取身份证
        Patient patient = patientDao.findBySsc(strSSID);
        if(patient!=null) {
            String url = ehrUrl + patient.getIdcard() +"/profile/medical_events?demographic_id=" + patient.getIdcard();
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONArray jsonArray = new JSONArray(response);
            JSONArray resultArray = new JSONArray();
            for (int i=0; i<jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONObject item = new JSONObject();
                item.put("END_TIME",jsonObject.optString("event_date")); //创建时间
                item.put("ORG_NAME",jsonObject.optString("org_name")); //机构名称
                item.put("ORG_CODE",jsonObject.optString("org_code")); //机构代码
                item.put("UNIONSSID",strSSID); //社保卡号
                item.put("NAME",jsonObject.optString("EHR_000004")); //姓名
                item.put("EVENT",jsonObject.optString("event_no")); //事件号
                String profileId = jsonObject.optString("rowkey");
                item.put("SERIAL",profileId); //rowkey
                //包含模板
                JSONObject catalog = new JSONObject();
                List<String> tables = containTables(profileId);
                //0门诊 1住院
                String eventType =  jsonObject.optString("event_type");
                //判断是否有检查报告
                if(tables.contains("HDSC01_09")){
                    if(eventType.equals("0")) {
                        catalog.put("0141", "门诊用药记录");
                    }
                    else{
                        catalog.put("0241","住院用药记录");
                    }
                }
                if(catalog.length()>0) {
                    item.put("CATALOG", catalog); //档案类别
                    resultArray.put(item);
                }
            }
            return resultArray.toString();
        }
        else{
            return "";
        }
    }
    /***************************************** 档案数据 ****************************************************************/
    /**
     * 获取档案数据
     * @return
@ -328,6 +376,12 @@ public class EhrService extends BaseService {
            else if (strCatalog.equals("0201")) {   //住院诊疗基本信息
                re = get0201(strSSID,strSerial);
            }
            else if (strCatalog.equals("0213")) {   //出院小结
                re = get0213(strSSID,strSerial);
            }
            else if (strCatalog.equals("0217")) {   //死亡记录
                re = get0217(strSSID,strSerial);
            }
            /******************************** 细表数据 ********************************************************/
            else if (strCatalog.equals("0102")) {   //门诊费用明细
@ -340,38 +394,31 @@ public class EhrService extends BaseService {
                re = getLaboratory(strSSID,strSerial,"0121");
            }
            else if (strCatalog.equals("0141")) {   //门诊用药记录
                re = getDrug(strSSID,strSerial,"0141");
            }
            else if (strCatalog.equals("0116")) {   //门诊手术记录
                re = get0116(strSSID,strSerial);
            }
            else if (strCatalog.equals("0202")) {   //住院费用明细
            }
            else if (strCatalog.equals("0213")) {   //出院小结
                re = get0202(strSSID,strSerial);
            }
            else if (strCatalog.equals("0214")) {   //长期医嘱
                re = get0214(strSSID,strSerial);
            }
            else if (strCatalog.equals("0215")) {   //临时医嘱
                re = get0215(strSSID,strSerial);
            }
            else if (strCatalog.equals("0216")) {   //住院手术记录
            }
            else if (strCatalog.equals("0217")) {   //死亡记录
                re = get0216(strSSID,strSerial);
            }
            else if (strCatalog.equals("0221")) {   //住院检验报告
                re = getLaboratory(strSSID,strSerial,"0221");
            }
            else if (strCatalog.equals("0231")) {   //住院检查报告
                re = getExamination(strSSID,strSerial,"0231");
            }
            else if (strCatalog.equals("0241")) {   //住院用药记录
                re = getDrug(strSSID,strSerial,"0241");
            }
        }
@ -384,9 +431,6 @@ public class EhrService extends BaseService {
        return re;
    }
    //门诊基本诊疗信息
    public String get0101(String ssid,String profileId)
    {
@ -604,6 +648,223 @@ public class EhrService extends BaseService {
        }
    }
    //出院小结
    public String get0213(String ssid,String profileId)
    {
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                    "  <ehr code=\"0213\" codeSystem=\"STD_EHR\">出院小结</ehr>\n" +
                    "  <title>出院小结</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "      <sex code=\"" + info.optString("EHR_000019") + "\" codeSystem=\"GB/T2261.1-2003\">" + info.optString("EHR_000019_VALUE") + "</sex>\n" +
                    "      <nation code=\""+ info.optString("EHR_000016") + "\" codeSystem=\"GB 3304-1991\">"+ info.optString("EHR_000016_VALUE") +"</nation>\n" +
                    "      <work code=\""+ info.optString("EHR_000022") +"\" codeSystem=\"GB/T 6565-1999\">"+ info.optString("EHR_000022_VALUE") +"</work>\n" +
                    "      <birthAdd>"+ info.optString("EHR_000015") +"</birthAdd>\n" +
                    "      <birthDate>" + info.optString("EHR_000007") + "</birthDate>\n" +
                    "      <age>"+ IdCardUtil.getAgeForIdcard(info.optString("demographic_id") )+"</age>\n" +
                    "      <marriage code=\"" + info.optString("EHR_000014") + "\" codeSystem=\"GB/T 2261.2-2003\">" + info.optString("EHR_000014_VALUE") + "</marriage>\n" +
                    "      <address>【现住址】</address>\n" +
                    "      <organization>"+ info.optString("EHR_000009") +"</organization>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <residentDoctor>\n" +
                    "    <time value=\""+ info.optString("EHR_000173") +"\"/>\n" +
                    "    <id extension=\""+ info.optString("EHR_000171") +"\"/>\n" +
                    "    <name>"+ info.optString("EHR_000172") +"</name>\n" +
                    "  </residentDoctor>\n" +
                    "  <inChargeDoctor>\n" +
                    "    <time value=\""+ info.optString("EHR_000169") +"\"/>\n" +
                    "    <id extension=\""+ info.optString("EHR_000167") +"\"/>\n" +
                    "    <name>"+ info.optString("EHR_000168") +"</name>\n" +
                    "  </inChargeDoctor>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"出院小结\"/>\n" +
                    "      <entry>\n" +
                    "        <residence>\n" +
                    "          <serial>"+ info.optString("EHR_000234") +"</serial>\n" +
                    "          <code>"+ info.optString("EHR_000236") +"</code>\n" +
                    "        </residence>\n" +
                    "        <inTime value=\""+ info.optString("EHR_000162") +"\"/>\n" +
                    "        <outTime value=\""+ info.optString("EHR_000155") +"\"/>\n" +
                    "        <inDept code=\""+ info.optString("EHR_000228") +"\" codeSystem=\"GB/T 2261.2-2003\">"+ info.optString("EHR_000229") +"</inDept>\n" +
                    "        <bed>"+ info.optString("EHR_000227") +"</bed>\n" +
                    "        <inHospitalDay>"+ info.optString("EHR_000170") +"</inHospitalDay>\n" +
                    "        <inDiagnosis code=\""+ info.optString("EHR_000163") +"\" codeSystem=\"ICD-10\">"+ info.optString("EHR_000164") +"</inDiagnosis>\n" +
                    "        <inCondition>"+ info.optString("EHR_000161") +"</inCondition>\n" +
                    "        <remedialCourse>"+ info.optString("EHR_000165") +"</remedialCourse>\n" +
                    "        <outCondition>"+ info.optString("EHR_000161") +"</outCondition>\n" +
                    "        <outDiagnosis code=\""+ info.optString("EHR_000158") +"\" codeSystem=\"ICD-10\">"+ info.optString("EHR_000159") +"\n" +
                    "        <outOrder>"+ info.optString("EHR_000157") +"</outOrder>\n" +
                    "        <remedialResult>"+ info.optString("EHR_000166") +"</remedialResult>\n" +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";
            return re;
        }
        else{
            return "";
        }
    }
    //死亡记录
    public String get0217(String ssid,String profileId)
    {
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            //死亡链(业务对接不上)
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                    "  <ehr code=\"0217\" codeSystem=\"STD_EHR\">死亡医学证明</ehr>\n" +
                    "  <title>死亡医学证明</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "      <sex code=\"" + info.optString("EHR_000019") + "\" codeSystem=\"GB/T2261.1-2003\">" + info.optString("EHR_000019_VALUE") + "</sex>\n" +
                    "      <nation code=\""+ info.optString("EHR_000016") + "\" codeSystem=\"GB 3304-1991\">"+ info.optString("EHR_000016_VALUE") +"</nation>\n" +
                    "      <work code=\""+ info.optString("EHR_000022") +"\" codeSystem=\"GB/T 6565-1999\">"+ info.optString("EHR_000022_VALUE") +"</work>\n" +
                    "      <birthAdd>"+ info.optString("EHR_000015") +"</birthAdd>\n" +
                    "      <birthDate>" + info.optString("EHR_000007") + "</birthDate>\n" +
                    "      <age>"+ IdCardUtil.getAgeForIdcard(info.optString("demographic_id") )+"</age>\n" +
                    "      <marriage code=\"" + info.optString("EHR_000014") + "\" codeSystem=\"GB/T 2261.2-2003\">" + info.optString("EHR_000014_VALUE") + "</marriage>\n" +
                    "      <degree code=\""+ info.optString("EHR_000020") + "\" codeSystem=\"GB/T 4658-1984\">"+ info.optString("EHR_000020_VALUE") + "</degree>\n" +
                    "      <country code=\""+ info.optString("EHR_000010") + "\" codeSystem=\"GB/T 2659-2000\">"+ info.optString("EHR_000010_VALUE") + "</country>\n" +
                    "      <idno>"+ info.optString("demographic_id") + "</idno>\n" +
                    "      <!--现住址-->\n" +
                    "      <address>\n" +
                    "        <type code=\"09\" codeSystem=\"CV0300.01\">现住址</type>\n" +
                    "        <adminDivision code=\"【行政区划代码(字典STD_ADMIN_DIVISION)】\" codeSystem=\"GB/T 2260-2007\">【行政区划名称】</adminDivision>\n" +
                    "        <country code=\"【国籍代码(字典STD_COUNTRY)】\" codeSystem=\"GB/T 2659-2000\">【国家名称】</country>\n" +
                    "        <state>【省份】</state>\n" +
                    "        <city>【市】</city>\n" +
                    "        <county>【区、县】</county>\n" +
                    "        <street>【街道、镇】</street>\n" +
                    "        <village>【村、街、路、弄】</village>\n" +
                    "        <houseNo>【门牌号】</houseNo>\n" +
                    "        <streetAddressLine>"+ info.optString("EHR_000241") +"</streetAddressLine>\n" +
                    "        <postalCode>【邮政编码】</postalCode>\n" +
                    "      </address>\n" +
                    "      <!--户口地址-->\n" +
                    "      <registeredAddress>\n" +
                    "        <type code=\"01\" codeSystem=\"CV0300.01\">户口地址</type>\n" +
                    "        <adminDivision code=\"【行政区划代码(字典STD_ADMIN_DIVISION)】\" codeSystem=\"GB/T 2260-2007\">【行政区划名称】</adminDivision>\n" +
                    "        <country code=\""+ info.optString("EHR_000010") +"\" codeSystem=\"GB/T 2659-2000\">"+ info.optString("EHR_000010_VALUE") +"</country>\n" +
                    "        <state>【省份】</state>\n" +
                    "        <city>【市】</city>\n" +
                    "        <county>【区、县】</county>\n" +
                    "        <street>【街道、镇】</street>\n" +
                    "        <village>【村、街、路、弄】</village>\n" +
                    "        <houseNo>【门牌号】</houseNo>\n" +
                    "        <streetAddressLine>"+ info.optString("EHR_000013") +"</streetAddressLine>\n" +
                    "        <postalCode>"+ info.optString("EHR_000012") +"</postalCode>\n" +
                    "      </registeredAddress>\n" +
                    "      <organization telephone=\"【联系电话】\" postalCode=\"【邮政编码】\" address=\"【地址】\">"+ info.optString("EHR_000009") +"</organization>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <contactPerson>\n" +
                    "    <type>"+ info.optString("EHR_000252") +"</type>\n" +
                    "    <name>"+ info.optString("EHR_000253") +"</name>\n" +
                    "    <telephone>【联系人:电话】</telephone>\n" +
                    "    <address>"+ info.optString("EHR_000251") +"</address>\n" +
                    "  </contactPerson>\n" +
                    "  <author>\n" +
                    "    <time>"+info.optString("EHR_000262")+"</time>\n" +
                    "    <id extension=\""+info.optString("EHR_000263")+"\"/>\n" +
                    "    <name>"+info.optString("EHR_000264")+"</name>\n" +
                    "  </author>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <!--档案子类别,用于类别的扩展,code子类别编码;displayName名称。当前为固定值-->\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"死亡医学证明\"/>\n" +
                    "      <entry>\n" +
                    "        <inTime>"+info.optString("EHR_000250")+"</inTime>\n" +
                    "        <deathTime>"+info.optString("EHR_000255")+"</deathTime>\n" +
                    "        <placeType code=\""+info.optString("EHR_000254")+"\" codeSystem=\"CV8500.01\">"+info.optString("EHR_000254_VALUE")+"</placeType>\n" +
                    "        <causeOfDeath>\n" +
                   /* "          <causeOfDeathA>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值1\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <icd10 code=\"疾病ICD10编码(字典STD_ICD)\" codeSystem=\"ICD-10\">疾病名称</icd10>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>直接死亡原因A(导致死亡的最后疾病或情况)</detail>\n" +
                    "          </causeOfDeathA>\n" +
                    "          <causeOfDeathB>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值2\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <icd10 code=\"疾病ICD10编码(字典STD_ICD)\" codeSystem=\"ICD-10\">疾病名称</icd10>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>直接死亡原因B(引起A的最后疾病或情况)</detail>\n" +
                    "          </causeOfDeathB>\n" +
                    "          <causeOfDeathC>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值3\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <icd10 code=\"疾病ICD10编码(字典STD_ICD)\" codeSystem=\"ICD-10\">疾病名称</icd10>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>直接死亡原因C(引起B的最后疾病或情况)</detail>\n" +
                    "          </causeOfDeathC>\n" +
                    "          <causeOfDeathD>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值4\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <icd10 code=\"疾病ICD10编码(字典STD_ICD)\" codeSystem=\"ICD-10\">疾病名称</icd10>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>直接死亡原因D(引起C的最后疾病或情况)</detail>\n" +
                    "          </causeOfDeathD>\n" +
                    "          <causeOfDeathOther1>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值9\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>促进死亡,但与导致死亡的疾病或情况无关的其他重要情况1</detail>\n" +
                    "          </causeOfDeathOther1>\n" +
                    "          <causeOfDeathOther2>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值9\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>促进死亡,但与导致死亡的疾病或情况无关的其他重要情况2</detail>\n" +
                    "          </causeOfDeathOther2>\n" +
                    "          <causeOfDeathOther3>\n" +
                    "            <type code=\"死因链代码(字典STD_DEATH_CAUSE_CHAIN):固定值9\" codeSystem=\"CV8500.05\">死因链名称</type>\n" +
                    "            <interval code=\"时间间隔单位类别(字典STD_TIME_INTERVAL_UNIT):固定值4\">发病到死亡的大概时间间隔(单位:日)</interval>\n" +
                    "            <detail>促进死亡,但与导致死亡的疾病或情况无关的其他重要情况3</detail>\n" +
                    "          </causeOfDeathOther3>\n" +*/
                    "        </causeOfDeath>\n" +
                    "        <deathOrg code=\""+info.optString("EHR_000256")+"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("EHR_000257")+"</deathOrg>\n" +
                    "        <deathcatalog code=\""+info.optString("EHR_000258")+"\" codeSystem=\"STD_DEAD_CATALOG\">"+info.optString("EHR_000258_VALUE")+"</deathcatalog>\n" +
                    "        <highestDiagnosis>\n" +
                    "          <level code=\""+info.optString("EHR_000260")+"\" codeSystem=\"CV8500.03\">"+info.optString("EHR_000260_VALUE")+"</level>\n" +
                    "          <org code=\""+info.optString("EHR_000259")+"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("EHR_000259")+"</org>\n" +
                    "          <diagnosisGist code=\""+info.optString("EHR_000261")+"\" codeSystem=\"CV8500.02\">"+info.optString("EHR_000261")+"</diagnosisGist>\n" +
                    "        </highestDiagnosis>\n" +
                    "        <remedialCourse>"+info.optString("EHR_000266")+"</remedialCourse>\n" +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";
            return re;
        }
        else{
            return "";
        }
    }
    //检查报告单(取第一条)
    public String getExamination(String ssid,String profileId,String catalog)
    {
@ -831,6 +1092,292 @@ public class EhrService extends BaseService {
        return re;
    }
    //长期医嘱
    public String get0214(String ssid,String profileId)
    {
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            String orderString = "";
            //获取长期医嘱
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/orders/longtime?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject obj = new JSONObject(response);
            if (obj.getBoolean("successFlg") && obj.getInt("totalCount") > 0) {
                JSONArray array = obj.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject item = array.getJSONObject(i);
                        orderString += "<item>\n" +
                                "            <orderTime>"+item.optString("EHR_000279") +"</orderTime>\n" +
                                "            <orderDoctor>"+item.optString("EHR_000280") +"</orderDoctor>\n" +
                                "            <checkNurse>"+item.optString("EHR_000281") +"</checkNurse>\n" +
                                "            <stopTime>"+item.optString("EHR_000277") +"</stopTime>\n" +
                                "            <stopDoctor>"+item.optString("EHR_000278") +"</stopDoctor>\n" +
                                "            <stopNurse>"+item.optString("EHR_000276") +"</stopNurse>\n" +
                                "            <orderCode>"+item.optString("EHR_000282") +"</orderCode>\n" +
                                "            <stdCode>"+item.optString("EHR_000283") +"</stdCode>\n" +
                                "            <orderName>"+item.optString("EHR_000285") +"</orderName>\n" +
                                "            <freq>"+item.optString("EHR_000275") +"</freq>\n" +
                                "</item>\n";
                    }
                }
            }
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                    "  <ehr code=\"0214\" codeSystem=\"STD_EHR\">长期医嘱</ehr>\n" +
                    "  <title>长期医嘱</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"长期医嘱\"/>\n" +
                    "      <entry>\n" +
                    "        <order>\n" +
                    orderString +
                    "        </order>\n" +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";
            return re;
        }
        else{
            return "";
        }
    }
    //临时医嘱
    public String get0215(String ssid,String profileId)
    {
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            String orderString = "";
            //获取长期医嘱
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/orders/longtime?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject obj = new JSONObject(response);
            if (obj.getBoolean("successFlg") && obj.getInt("totalCount") > 0) {
                JSONArray array = obj.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject item = array.getJSONObject(i);
                        orderString += "          <item>\n" +
                                "            <orderTime>"+item.optString("EHR_000207") +"</orderTime>\n" +
                                "            <orderDoctor>"+item.optString("EHR_000208") +"</orderDoctor>\n" +
                                "            <checkNurse>"+item.optString("EHR_000209") +"</checkNurse>\n" +
                                "            <execNurse>"+item.optString("EHR_000218") +"</execNurse>\n" +
                                "            <execTime>"+item.optString("EHR_000219") +"</execTime>\n" +
                                "            <orderCode>"+item.optString("EHR_000210") +"</orderCode>\n" +
                                "            <stdCode>"+item.optString("EHR_000211") +"</stdCode>\n" +
                                "            <orderName>"+item.optString("EHR_000213") +"</orderName>\n" +
                                "          </item>\n";
                    }
                }
            }
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                    "  <ehr code=\"0215\" codeSystem=\"STD_EHR\">临时医嘱</ehr>\n" +
                    "  <title>临时医嘱</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"临时医嘱\"/>\n" +
                    "      <entry>\n" +
                    "        <order>\n" +
                    orderString +
                    "        </order>\n" +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";
            return re;
        }
        else{
            return "";
        }
    }
    //门诊手术记录 (取第一条)
    public String get0116(String ssid,String profileId)
    {
        String re = "";
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            //获取手术记录
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/laboratory?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject json = new JSONObject(response);
            if (json.getBoolean("successFlg") && json.getInt("totalCount") > 0) {
                JSONArray array = json.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    JSONObject obj = array.getJSONObject(0);
                    re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                            "<ClinicalDocument>\n" +
                            "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                            "  <ehr code=\"0116\" codeSystem=\"STD_EHR\">门诊手术记录</ehr>\n" +
                            "  <title>门诊手术记录</title>\n" +
                            "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                            "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                            "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                            "  <recordTarget>\n" +
                            "    <patient>\n" +
                            "      <id extension=\""+ssid+"\"></id>\n" +
                            "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                            "    </patient>\n" +
                            "  </recordTarget>\n" +
                            "  <author>\n" +
                            "    <time>"+obj.optString("EHR_000408")+"</time>\n" +
                            "    <id extension=\""+obj.optString("EHR_000409")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000410")+"</name>\n" +
                            "  </author>\n" +
                            "  <surgeon>\n" +
                            "    <id extension=\""+obj.optString("EHR_000424")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000425")+"</name>\n" +
                            "  </surgeon>\n" +
                            "  <assistant1>\n" +
                            "    <id extension=\""+obj.optString("EHR_000404")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000405")+"</name>\n" +
                            "  </assistant1>\n" +
                            "  <assistant2>\n" +
                            "    <id extension=\""+obj.optString("EHR_000406")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000407")+"</name>\n" +
                            "  </assistant2>\n" +
                            "  <anesthesiologist>\n" +
                            "    <id extension=\""+obj.optString("EHR_000412")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000413")+"</name>\n" +
                            "  </anesthesiologist>\n" +
                            "  <component>\n" +
                            "    <section>\n" +
                            "      <!--档案子类别,用于类别的扩展,code子类别编码;displayName名称。当前为固定值-->\n" +
                            "      <code code=\"common\" codeSystem=\"\" displayName=\"门诊手术记录\"/>\n" +
                            "      <entry>\n" +
                            "        <time>"+obj.optString("EHR_000417")+"</time>\n" +
                            "        <preDiagnosis code=\""+obj.optString("EHR_000426")+"\" codeSystem=\"ICD-10\">"+obj.optString("EHR_000426_VALUE")+"</preDiagnosis>\n" +
                            "        <midDiagnosis code=\""+obj.optString("EHR_000427")+"\" codeSystem=\"ICD-10\">"+obj.optString("EHR_000427_VALUE")+"</midDiagnosis>\n" +
                            "        <operation code=\""+obj.optString("EHR_000416")+"\" codeSystem=\"ICD-9-CM\">"+obj.optString("EHR_000418")+"</operation>\n" +
                            "        <part code=\""+obj.optString("EHR_000419")+"\" codeSystem=\"CV5201.23\">"+obj.optString("EHR_000420")+"</part>\n" +
                            "        <anesthesia>"+obj.optString("EHR_000411")+"</anesthesia>\n" +
                            "        <operationCourse>"+obj.optString("EHR_000422")+"</operationCourse>\n" +
                            "      </entry>\n" +
                            "    </section>\n" +
                            "  </component>\n" +
                            "</ClinicalDocument>";
                }
            }
        }
        return re;
    }
    //住院手术记录  (取第一条)
    public String get0216(String ssid,String profileId)
    {
        String re = "";
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            //获取手术记录
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/laboratory?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject json = new JSONObject(response);
            if (json.getBoolean("successFlg") && json.getInt("totalCount") > 0) {
                JSONArray array = json.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    JSONObject obj = array.getJSONObject(0);
                    re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                            "<ClinicalDocument>\n" +
                            "  <version code=\"2.0.0.0\" date=\"2009-12-01\">根据卫生部标准第一次修订</version>\n" +
                            "  <ehr code=\"0216\" codeSystem=\"STD_EHR\">住院手术记录</ehr>\n" +
                            "  <title>住院手术记录</title>\n" +
                            "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                            "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                            "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                            "  <recordTarget>\n" +
                            "    <patient>\n" +
                            "      <id extension=\""+ssid+"\"></id>\n" +
                            "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                            "    </patient>\n" +
                            "  </recordTarget>\n" +
                            "  <author>\n" +
                            "    <time>"+obj.optString("EHR_000408")+"</time>\n" +
                            "    <id extension=\""+obj.optString("EHR_000409")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000410")+"</name>\n" +
                            "  </author>\n" +
                            "  <surgeon>\n" +
                            "    <id extension=\""+obj.optString("EHR_000424")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000425")+"</name>\n" +
                            "  </surgeon>\n" +
                            "  <assistant1>\n" +
                            "    <id extension=\""+obj.optString("EHR_000404")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000405")+"</name>\n" +
                            "  </assistant1>\n" +
                            "  <assistant2>\n" +
                            "    <id extension=\""+obj.optString("EHR_000406")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000407")+"</name>\n" +
                            "  </assistant2>\n" +
                            "  <anesthesiologist>\n" +
                            "    <id extension=\""+obj.optString("EHR_000412")+"\"/>\n" +
                            "    <name>"+obj.optString("EHR_000413")+"</name>\n" +
                            "  </anesthesiologist>\n" +
                            "  <component>\n" +
                            "    <section>\n" +
                            "      <!--档案子类别,用于类别的扩展,code子类别编码;displayName名称。当前为固定值-->\n" +
                            "      <code code=\"common\" codeSystem=\"\" displayName=\"住院手术记录\"/>\n" +
                            "      <entry>\n" +
                            "        <time>"+obj.optString("EHR_000417")+"</time>\n" +
                            "        <preDiagnosis code=\""+obj.optString("EHR_000426")+"\" codeSystem=\"ICD-10\">"+obj.optString("EHR_000426_VALUE")+"</preDiagnosis>\n" +
                            "        <midDiagnosis code=\""+obj.optString("EHR_000427")+"\" codeSystem=\"ICD-10\">"+obj.optString("EHR_000427_VALUE")+"</midDiagnosis>\n" +
                            "        <operation code=\""+obj.optString("EHR_000416")+"\" codeSystem=\"ICD-9-CM\">"+obj.optString("EHR_000418")+"</operation>\n" +
                            "        <part code=\""+obj.optString("EHR_000419")+"\" codeSystem=\"CV5201.23\">"+obj.optString("EHR_000420")+"</part>\n" +
                            "        <anesthesia>"+obj.optString("EHR_000411")+"</anesthesia>\n" +
                            "        <operationCourse>"+obj.optString("EHR_000422")+"</operationCourse>\n" +
                            "      </entry>\n" +
                            "    </section>\n" +
                            "  </component>\n" +
                            "</ClinicalDocument>";
                }
            }
        }
        return re;
    }
    //门诊费用明细
    public String get0102(String ssid,String profileId)
@ -839,34 +1386,139 @@ public class EhrService extends BaseService {
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            //住院症状
            String symptomUrl = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/symptom?profile_id=" + profileId;
            String symptomResponse = HttpClientUtil.get(symptomUrl, "UTF-8");
            JSONObject symptomObj = new JSONObject(symptomResponse);
            String symptomString = "";
            if (symptomObj.getBoolean("successFlg") && symptomObj.getInt("totalCount") > 0) {
                JSONArray array = symptomObj.getJSONArray("detailModelList");
            String costString = "";
            //门诊费用汇总
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/outpatient/cost/master?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject json = new JSONObject(response);
            if (json.getBoolean("successFlg") && json.getInt("totalCount") > 0) {
                JSONArray array = json.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                    for(int i=0;i<array.length();i++)
                    {
                        JSONObject item = array.getJSONObject(i);
                        symptomString += "<item code=\"" + item.optString("EHR_000301") + "\" codeSystem=\"CV5101.27\">" + item.optString("EHR_000302") + "</item>\n";
                        String type =  item.optString("EHR_000044");
                        costString += "<group>\n" +
                                "          <type code=\""+item.optString("EHR_000044")+"\" codeSystem=\"CV5600.01\">"+item.optString("EHR_000044_VALUE")+"</type>\n" +
                                "          <payway code=\"【门诊费用支付方式代码(字典STD_OUTPATIENT_PAY_WAY)】\" codeSystem=\"CV5600.02\">【门诊费用支付方式】</payway>\n" +
                                "          <fee>"+item.optString("EHR_000045")+"</fee>\n";
                        //获取门诊费用详细
                        String urlDetail = ehrUrl + URLEncoder.encode("{demographic_id}")+"/outpatient/cost/detail?profile_id=" + profileId;
                        String responseDetail = HttpClientUtil.get(urlDetail, "UTF-8");
                        JSONObject jsonDetail = new JSONObject(responseDetail);
                        if (jsonDetail.getBoolean("successFlg") && jsonDetail.getInt("totalCount") > 0) {
                            JSONArray arrayDetail = jsonDetail.getJSONArray("detailModelList");
                            if (arrayDetail != null && arrayDetail.length() > 0) {
                                for(int j=0;j<arrayDetail.length();j++)
                                {
                                    JSONObject itemDetail = arrayDetail.getJSONObject(i);
                                    if(itemDetail.optString("EHR_000050").equals(type)) {
                                        costString += "<item>\n" +
                                                "    <time>" + itemDetail.optString("EHR_000054") + "</time>\n" +
                                                "    <value code=\"【市标准扣费代码(以医保为蓝本的厦门编码)】\" >【标准项目名称】</value>\n" +
                                                "    <custome code=\"" + itemDetail.optString("EHR_000056") + "\">" + itemDetail.optString("EHR_000057") + "</custome>\n" +
                                                "    <quantity>" + itemDetail.optString("EHR_000055") + "</quantity>\n" +
                                                "    <unit>" + itemDetail.optString("EHR_000048") + "</unit>\n" +
                                                "    <price>" + itemDetail.optString("EHR_000047") + "</price>\n" +
                                                "    <total>" + itemDetail.optString("EHR_000049") + "</total>\n" +
                                                "    <notes>" + itemDetail.optString("EHR_000046") + "</notes>\n" +
                                                "</item>\n";
                                    }
                                }
                            }
                        }
                        costString += " </group>\n";
                    }
                }
            }
            //住院诊断
            String diagnosisUrl = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/diagnosis?profile_id=" + profileId;
            String diagnosisResponse = HttpClientUtil.get(diagnosisUrl, "UTF-8");
            JSONObject diagnosisObj = new JSONObject(diagnosisResponse);
            String diagnosisString = "";
            if (diagnosisObj.getBoolean("successFlg") && diagnosisObj.getInt("totalCount") > 0) {
                JSONArray array = diagnosisObj.getJSONArray("detailModelList");
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.1\" date=\"2011-06-01\">根据卫生部标准第2次修订</version>\n" +
                    "  <ehr code=\"0102\" codeSystem=\"STD_EHR\"></ehr>\n" +
                    "  <title>门诊费用明细</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\"  displayName=\"门诊费用明细\"/>\n" +
                    "      <entry>\n" +
                    costString +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";;
            return re;
        }
        else{
            return "";
        }
    }
    //住院费用明细
    public String get0202(String ssid,String profileId)
    {
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        if(info!=null) {
            String costString = "";
            //住院费用汇总
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/cost/master?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject json = new JSONObject(response);
            if (json.getBoolean("successFlg") && json.getInt("totalCount") > 0) {
                JSONArray array = json.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                    for(int i=0;i<array.length();i++)
                    {
                        JSONObject item = array.getJSONObject(i);
                        diagnosisString +="<item>\n" +
                                "      <icd code=\""+item.optString("EHR_000293")+"\" codeSystem=\"ICD-10\">"+item.optString("EHR_000295")+"</icd>\n" +
                                "</item>\n";
                        String type =  item.optString("EHR_000174");
                        costString += "<group>\n" +
                                "          <type code=\""+item.optString("EHR_000174")+"\" codeSystem=\"CV5600.01\">"+item.optString("EHR_000174_VALUE")+"</type>\n" +
                                "          <payway code=\"【医疗付款方式代码】\" codeSystem=\"CV5600.02\">【医疗付款方式代码】</payway>\n" +
                                "          <fee>"+item.optString("EHR_000175")+"</fee>\n";
                        //获取住院费用详细
                        String urlDetail = ehrUrl + URLEncoder.encode("{demographic_id}")+"/hospitalized/cost/detail?profile_id=" + profileId;
                        String responseDetail = HttpClientUtil.get(urlDetail, "UTF-8");
                        JSONObject jsonDetail = new JSONObject(responseDetail);
                        if (jsonDetail.getBoolean("successFlg") && jsonDetail.getInt("totalCount") > 0) {
                            JSONArray arrayDetail = jsonDetail.getJSONArray("detailModelList");
                            if (arrayDetail != null && arrayDetail.length() > 0) {
                                for(int j=0;j<arrayDetail.length();j++)
                                {
                                    JSONObject itemDetail = arrayDetail.getJSONObject(i);
                                    if(itemDetail.optString("EHR_000187").equals(type)) {
                                        costString += "<item>\n" +
                                                "    <time>" + itemDetail.optString("EHR_000054") + "</time>\n" +
                                                "    <value code=\"【市标准扣费代码(以医保为蓝本的厦门编码)】\" >【标准项目名称】</value>\n" +
                                                "    <custome code=\"" + itemDetail.optString("EHR_000185") + "\">" + itemDetail.optString("EHR_000186") + "</custome>\n" +
                                                "    <quantity>" + itemDetail.optString("EHR_000184") + "</quantity>\n" +
                                                "    <unit>" + itemDetail.optString("EHR_000178") + "</unit>\n" +
                                                "    <price>" + itemDetail.optString("EHR_000177") + "</price>\n" +
                                                "    <total>" + itemDetail.optString("EHR_000179") + "</total>\n" +
                                                "    <notes>" + itemDetail.optString("EHR_000176") + "</notes>\n" +
                                                "</item>\n";
                                    }
                                }
                            }
                        }
                        costString += " </group>\n";
                    }
                }
            }
@ -874,8 +1526,8 @@ public class EhrService extends BaseService {
            String re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.1\" date=\"2011-06-01\">根据卫生部标准第2次修订</version>\n" +
                    "  <ehr code=\"0201\" codeSystem=\"STD_EHR\">住院诊疗基本信息</ehr>\n" +
                    "  <title>住院诊疗基本信息</title>\n" +
                    "  <ehr code=\"0202\" codeSystem=\"STD_EHR\">住院费用明细</ehr>\n" +
                    "  <title>住院费用明细</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
@ -883,61 +1535,13 @@ public class EhrService extends BaseService {
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "      <sex code=\"" + info.optString("EHR_000019") + "\" codeSystem=\"GB/T2261.1-2003\">" + info.optString("EHR_000019_VALUE") + "</sex>\n" +
                    "      <birthDate>" + info.optString("EHR_000007") + "</birthDate>\n" +
                    "      <marriage code=\"" + info.optString("EHR_000014") + "\" codeSystem=\"GB/T 2261.2-2003\">" + info.optString("EHR_000014_VALUE") + "</marriage>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"住院诊疗基本信息\"/>\n" +
                    "      <code code=\"common\" codeSystem=\"\" displayName=\"住院费用明细\"/>\n" +
                    "      <entry>\n" +
                    "        <residence>\n" +
                    "          <serial>"+info.optString("EHR_000234") +"</serial>\n" +
                    "          <code>"+info.optString("EHR_000236")+"</code>\n" +
                    "        </residence>\n" +
                    "        <sec>\n" +
                    "          <type code=\"【保险类别(字典STD_SEC_TYPE)】\" codeSystem=\"STD_SEC_TYPE\">【保险类别名称】</type>\n" +
                    "          <value>"+info.optString("EHR_000232")+"</value>\n" +
                    "        </sec>\n" +
                    "        <in>\n" +
                    "          <time>"+info.optString("EHR_000230")+"</time>\n" +
                    "          <dept code=\""+info.optString("EHR_000228")+"\" codeSystem=\"GB/T 17538-1998\">"+info.optString("EHR_000229")+"</dept>\n" +
                    "          <bed>"+info.optString("EHR_000227")+"</bed>\n" +
                    "        </in>\n" +
                    "        <move>\n" +
                    //EHR转诊业务有问题
                    /*"          <item>\n" +
                    "            <time>转科时间</time>\n" +
                    "            <dept code=\"转科科室代码(字典STD_DEPT)\" codeSystem=\"GB/T 17538-1998\">转科后科室名称</dept>\n" +
                    "            <bed>转科后床号</bed>\n" +
                    "          </item>\n" +*/
                    "        </move>\n" +
                    "        <out>\n" +
                    "          <time>"+info.optString("EHR_000224")+"</time>\n" +
                    "          <dept code=\""+info.optString("EHR_000222")+"\" codeSystem=\"GB/T 17538-1998\">"+info.optString("EHR_000223")+"</dept>\n" +
                    "          <bed>"+info.optString("EHR_000221")+"</bed>\n" +
                    "        </out>\n" +
                    "        <onsetTime>"+info.optString("EHR_000230")+"</onsetTime>\n" +
                    "        <diagnosisDate>"+info.optString("EHR_000230")+"</diagnosisDate>\n" +
                    "        <cause code=\""+info.optString("EHR_000237")+"\" codeSystem=\"CV5401.04\">"+info.optString("EHR_000237_VALUE")+"</cause>\n" +
                    "       <symptom>\n" +
                    symptomString +
                    "        </symptom>\n" +
                    "        <illStatus code=\""+info.optString("EHR_000239")+"\" codeSystem=\"CV5502.18\">"+info.optString("EHR_000239_VALUE")+"</illStatus>\n" +
                    "        <infectiousStatus code=\""+info.optString("EHR_000238")+"\" codeSystem=\"STD_JUDGE\">"+info.optString("EHR_000238_VALUE")+"</infectiousStatus>\n" +
                    "        <inDiagnosis>\n" +
                    diagnosisString+
                    "        </inDiagnosis>\n" +
                    "        <outDiagnosis>\n" +
                    "          <item>\n" +
                    "            <icd code=\""+info.optString("EHR_000158")+"\" codeSystem=\"ICD-10\">"+info.optString("EHR_000159")+"</icd>\n" +
                    "            <result code=\""+info.optString("EHR_000166")+"\" codeSystem=\"CV5501.11\">"+info.optString("EHR_000166_VALUE")+"</result>\n" +
                    "            <prop code=\"【诊断性质代码(字典STD_DIAGNOSIS_PROP)】\" codeSystem=\"STD_DIAGNOSIS_PROP\">【诊断性质名称】</prop>\n" +
                    "          </item>\n" +
                    "        </outDiagnosis>\n" +
                    "        <deathTime>"+info.optString("EHR_000255")+"</deathTime>\n" +
                    "        <causeOfDeath code=\""+info.optString("EHR_000258")+"\" codeSystem=\"ICD-10\">"+info.optString("EHR_000258_VALUE")+"</causeOfDeath>\n" +
                    costString +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
@ -950,4 +1554,129 @@ public class EhrService extends BaseService {
            return "";
        }
    }
    /************************************ 未完成 ******************************************************************/
    //获取药品
    public String getDrug(String ssid,String profileId,String catalog)
    {
        String re = "";
        //事件主要信息
        JSONObject info = getEventBaseInfo(profileId);
        String catalogName = "";
        if(catalog.equals("0141"))
        {
            catalogName = "门诊用药记录";
        }
        else if(catalog.equals("0241"))
        {
            catalogName = "住院用药记录";
        }
        if(info!=null) {
            String medicineString = "";
            //处方主表
            String url = ehrUrl + URLEncoder.encode("{demographic_id}")+"/profile/medication/master?profile_id=" + profileId;
            String response = HttpClientUtil.get(url, "UTF-8");
            JSONObject json = new JSONObject(response);
            if (json.getBoolean("successFlg") && json.getInt("totalCount") > 0) {
                JSONArray array = json.getJSONArray("detailModelList");
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject item = array.getJSONObject(i);
                        String prescriptionNo = item.optString("EHR_000086");
                        String type = item.optString("EHR_001203");
                        medicineString += "<group>\n" +
                                "    <method code=\"【用药途径代码(字典STD_MEDICINE_ROUTE)】\" codeSystem=\"CV5201.22\">【用药使用方法和途径名称】</method>\n" +
                                "    <freq>【用药频率】</freq>\n" +
                                "    <startDate>【用药开始日期时间】</startDate>\n" +
                                "    <endDate>【用药停止日期时间】</endDate>\n" +
                                "    <days>【用药天数】</days>\n";
                        //处方细表
                        String urlDetail = ehrUrl + "profile/medication/detail/"+prescriptionNo+"?prescription_no=" + prescriptionNo+"&type="+type;
                        String responseDetail = HttpClientUtil.get(urlDetail, "UTF-8");
                        JSONObject jsonDetail = new JSONObject(responseDetail);
                        if (jsonDetail.getBoolean("successFlg") && jsonDetail.getInt("totalCount") > 0) {
                            JSONArray arrayDetail = jsonDetail.getJSONArray("detailModelList");
                            if (arrayDetail != null && arrayDetail.length() > 0) {
                                for (int j = 0; j < arrayDetail.length(); j++) {
                                    JSONObject itemDetail = arrayDetail.getJSONObject(j);
                                    //中药
                                    if(type.equals("1"))
                                    {
                                        medicineString +=   "<medicine>\n" +
                                                "    <offerTime>【发药日期时间】</offerTime>\n" +
                                                "    <value code=\"【市药品标准编码(以医保为蓝本的厦门编码)】\" >【市药品标准名称】</value>\n" +
                                                "    <DiaCode>【诊疗代码】</DiaCode>\n" +
                                                "    <custome code=\"【院内药品编码】\">"+itemDetail.optString("EHR_000131")+"</custome>\n" +
                                                "    <cnType code=\"【中药类别代码(字典STD_CN_MEDICINE)】\" codeSystem=\"CV5301.05\">【中药类别名称】</cnType>\n" +
                                                "    <type code=\"【药物类型代码(字典STD_MEDICINE_TYPE)】\" codeSystem=\"CV5301.06\">【药物类型名称】</type>\n" +
                                                "    <form code=\""+itemDetail.optString("EHR_000130")+"\" codeSystem=\"CV5301.01\">"+itemDetail.optString("EHR_000130_VALUE")+"</form>\n" +
                                                "    <spec>"+itemDetail.optString("EHR_000129")+"</spec>\n" +
                                                "    <doseQuantity>"+itemDetail.optString("EHR_000132")+"</doseQuantity>\n" +
                                                "    <doseUnit>"+itemDetail.optString("EHR_000133")+"</doseUnit>\n" +
                                                "    <totalQuantity>"+itemDetail.optString("EHR_000135")+"</totalQuantity>\n" +
                                                "    <totalUnit>"+itemDetail.optString("EHR_000133")+"</totalUnit>\n" +
                                                "    <notes>"+itemDetail.optString("EHR_000141")+"</notes>\n" +
                                                "</medicine>\n";
                                    }
                                    //西药
                                    {
                                        medicineString +=   "<medicine>\n" +
                                                "    <offerTime>【发药日期时间】</offerTime>\n" +
                                                "    <value code=\"【市药品标准编码(以医保为蓝本的厦门编码)】\" >【市药品标准名称】</value>\n" +
                                                "    <DiaCode>【诊疗代码】</DiaCode>\n" +
                                                "    <custome code=\"【院内药品编码】\">"+itemDetail.optString("EHR_000100")+"</custome>\n" +
                                                "    <cnType code=\"【中药类别代码(字典STD_CN_MEDICINE)】\" codeSystem=\"CV5301.05\">【中药类别名称】</cnType>\n" +
                                                "    <type code=\"【药物类型代码(字典STD_MEDICINE_TYPE)】\" codeSystem=\"CV5301.06\">【药物类型名称】</type>\n" +
                                                "    <form code=\""+itemDetail.optString("EHR_000099")+"\" codeSystem=\"CV5301.01\">"+itemDetail.optString("EHR_000099_VALUE")+"</form>\n" +
                                                "    <spec>"+itemDetail.optString("EHR_000098")+"</spec>\n" +
                                                "    <doseQuantity>"+itemDetail.optString("EHR_000101")+"</doseQuantity>\n" +
                                                "    <doseUnit>"+itemDetail.optString("EHR_000102")+"</doseUnit>\n" +
                                                "    <totalQuantity>"+itemDetail.optString("EHR_000104")+"</totalQuantity>\n" +
                                                "    <totalUnit>"+itemDetail.optString("EHR_000102")+"</totalUnit>\n" +
                                                "    <notes>【备注】</notes>\n" +
                                                "</medicine>\n";
                                    }
                                }
                            }
                        }
                        medicineString += "</group>\n";
                    }
                }
            }
            re = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<ClinicalDocument>\n" +
                    "  <version code=\"2.0.0.1\" date=\"2011-06-01\">根据卫生部标准第2次修订</version>\n" +
                    "  <ehr code=\""+catalog+"\" codeSystem=\"STD_EHR\">"+catalogName+"</ehr>\n" +
                    "  <title>"+catalogName+"</title>\n" +
                    "  <org code=\""+info.optString("org_code") +"\" codeSystem=\"STD_HEALTH_ORG\">"+info.optString("org_name") +"</org>\n" +
                    "  <id extension=\"" + profileId + "\" eventno=\"" + info.optString("event_no") + "\"></id>\n" +
                    "  <effectiveTime value=\"" + info.optString("create_date") + "\"/>\n" +
                    "  <recordTarget>\n" +
                    "    <patient>\n" +
                    "      <id extension=\""+ssid+"\"></id>\n" +
                    "      <name>"+info.optString("EHR_000004")+"</name>\n" +
                    "    </patient>\n" +
                    "  </recordTarget>\n" +
                    "  <component>\n" +
                    "    <section>\n" +
                    "      <code code=\"common\" codeSystem=\"\"  displayName=\""+catalogName+"\"/>\n" +
                    "      <entry>\n" +
                    medicineString +
                    "      </entry>\n" +
                    "    </section>\n" +
                    "  </component>\n" +
                    "</ClinicalDocument>";
        }
        return re;
    }
}

+ 50 - 17
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/ExpensesRemindService.java

@ -103,7 +103,12 @@ public class ExpensesRemindService extends BaseService {
                    Patient p = patientDao.findByCode(String.valueOf(map.get("patient")));
                    if (p != null) {
                        remindPatientExpenses(p, doc, hos);
                        String epTime = redisTemplate.opsForValue().get("expenses:remind:" + p.getCode());
                        if(StringUtils.isNotEmpty(epTime) &&
                                new SimpleDateFormat("yyyy-MM-dd").format(new Date()).equals(epTime)) {
                            continue;
                        }
                        remindPatientExpenses(p, doc, hos, true);
                    }
                }
            }
@ -119,7 +124,7 @@ public class ExpensesRemindService extends BaseService {
     * @param doctor  医生
     * @return
     */
    public int remindPatientExpenses(String patient, String doctor) {
    public JSONObject remindPatientExpenses(String patient, String doctor) {
        try {
            Doctor doc = doctorDao.findByCode(doctor);
            if (doc == null) {
@ -137,10 +142,13 @@ public class ExpensesRemindService extends BaseService {
                throw new Exception("patient info can not find");
            }
            return remindPatientExpenses(p, doc, hos);
            return remindPatientExpenses(p, doc, hos, false);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
            JSONObject reObj = new JSONObject();
            reObj.put("status",-1);
            reObj.put("msg",e.getMessage());
            return reObj;
        }
    }
@ -152,9 +160,11 @@ public class ExpensesRemindService extends BaseService {
     * @param hos 医院
     * @return
     */
    public int remindPatientExpenses(Patient p, Doctor doc, Hospital hos) throws Exception {
    public JSONObject remindPatientExpenses(Patient p, Doctor doc, Hospital hos, boolean ignore) throws Exception {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject reObj = new JSONObject();
            String mDesc = "";
            boolean mFlag = false;
            boolean wFlag = false;
            boolean isMobileExist = false;
@ -162,11 +172,14 @@ public class ExpensesRemindService extends BaseService {
            if (StringUtils.isNotEmpty(p.getMobile())) {
                isMobileExist = true;
                int result = smsService.sendMsg(p.getMobile(), "厦门市民健康系统】" + doc.getName() + "医生提醒您:为完成家庭医生签约," +
                JSONObject result = smsService.sendMsg(p.getMobile(), doc.getName() + "医生提醒您:为完成家庭医生签约," +
                        "尽早为您提供家庭医生服务,请尽快到" + hos.getName() + "(地址:" + hos.getAddress() + ")缴费");
                if (result == 1) {
                if (result != null && result.getInt("result") == 1) {
                    mFlag = true;
                }
                if (result != null) {
                    mDesc = result.getString("description");
                }
            }
            if (StringUtils.isNotEmpty(p.getOpenid())) {
                isOpenIdExist = true;
@ -185,25 +198,45 @@ public class ExpensesRemindService extends BaseService {
                wFlag = true;
            }
            if (ignore) {
                redisTemplate.opsForValue().set("expenses:remind:" + p.getCode(), df.format(new Date()));
                redisTemplate.expire("expenses:remind:" + p.getCode(), 1, TimeUnit.DAYS);
            }
            if (wFlag || mFlag) {
                reObj.put("status", 200);
                redisTemplate.opsForValue().set("expenses:remind:" + p.getCode(), df.format(new Date()));
                redisTemplate.expire("expenses:remind:" + p.getCode(),1, TimeUnit.DAYS);
                if (!isMobileExist) {
                    return 2;
                }
                if (!isOpenIdExist) {
                    return 3;
                redisTemplate.expire("expenses:remind:" + p.getCode(), 1, TimeUnit.DAYS);
                if (wFlag && mFlag) {
                    reObj.put("msg", "提醒成功");
                } else if (mFlag && !wFlag) {
                    reObj.put("msg", "已短信提醒,居民未绑定微信,无法微信提醒");
                } else {
                    if (!isMobileExist) {
                        reObj.put("msg", "已微信提醒,居民未绑定手机,无法短信提醒");
                    } else {
                        reObj.put("msg", "已微信提醒,短信提醒失败,失败原因:" + mDesc);
                    }
                }
                return 1;
            } else {
                reObj.put("status", -1);
                if (!isMobileExist && !isOpenIdExist) {
                    return -1;
                    reObj.put("msg", "居民未绑定手机及微信,无法提醒");
                } else if (isMobileExist && !isOpenIdExist) {
                    reObj.put("msg", "居民未绑定微信,且短信提醒失败,无法提醒居民。短信失败原因:" + mDesc);
                } else {
                    reObj.put("msg", "提醒失败");
                }
                return 0;
            }
            return reObj;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
            JSONObject reObj = new JSONObject();
            reObj.put("status",-1);
            reObj.put("msg",e.getMessage());
            return reObj;
        }
    }
}

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

@ -2,6 +2,7 @@ package com.yihu.wlyy.service.app.sign;
import java.util.*;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.entity.organization.Hospital;
@ -975,7 +976,7 @@ public class FamilyContractService extends BaseService {
            SignFamily sssignFamily = signFamilyDao.findSSByIdcard(p.getIdcard());
            if (sssignFamily != null) {
                if(StringUtils.isNotEmpty(doctor)) {
                if (StringUtils.isNotEmpty(doctor)) {
                    if (!doctor.equals(sssignFamily.getDoctor())) {
                        result.put("status", -2);
                        result.put("msg", "居民已签约三师,故全科医生只可为" + sssignFamily.getDoctorName() + "医生,请重新选择全科医生");
@ -1617,6 +1618,7 @@ public class FamilyContractService extends BaseService {
        if (signFamily == null) {
            result.put("status", -1);
            result.put("msg", "居民不存在家庭签约");
            return result;
        }
        if (StringUtils.isNotEmpty(healthDoctor)) {
@ -1624,8 +1626,17 @@ public class FamilyContractService extends BaseService {
            if (docHealth == null) {
                result.put("status", -2);
                result.put("msg", "医生不存在");
                return result;
            }
            if (StringUtils.isNotEmpty(signFamily.getDoctorHealth())) {
                //判断患者对旧的健管师是否存在健康咨询
                ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patient, signFamily.getDoctorHealth(), 2);
                if (consultTeam != null) {
                    result.put("status", -1);
                    result.put("msg", "与当前健管师有未结束的咨询");
                    return result;
                }
                DoctorTeamMember teamMember = doctorTeamDoctor.findMemberByTeamAndCode(signFamily.getTeamCode(), signFamily.getDoctorHealth());
                if (teamMember != null) {
@ -1660,6 +1671,7 @@ public class FamilyContractService extends BaseService {
            if (docQk == null) {
                result.put("status", -2);
                result.put("msg", "医生不存在");
                return result;
            }
            if (StringUtils.isNotEmpty(signFamily.getDoctor())) {
                DoctorTeamMember teamMember = doctorTeamDoctor.findMemberByTeamAndCode(signFamily.getTeamCode(), signFamily.getDoctor());
@ -1695,6 +1707,7 @@ public class FamilyContractService extends BaseService {
            if (StringUtils.isNotEmpty(signFamily.getMedicalInsuranceNum())) {
                result.put("status", -3);
                result.put("msg", "数据已上传社保,不能修改补贴类型");
                return result;
            } else {
                signFamily.setExpensesType(expensesType);
            }
@ -1780,7 +1793,99 @@ public class FamilyContractService extends BaseService {
    public List<SignFamily> findAllSignByPatient(String patient) {
        return signFamilyDao.findAllSignByPatient(patient);
    }
    public List<SignFamily> findNoHealthSignFamilyNum(String doctor) {
        return signFamilyDao.findNoHealthSignFamilyNum(doctor);
    }
    /**
     * 判断居民与医生是否存在签约关系
     *
     * @param patient
     * @param doctor
     * @return
     */
    public JSONObject isPatientAndDoctorExistSign(String patient, String doctor) {
        JSONObject result = new JSONObject();
        SignFamily familySign = signFamilyDao.findFamilySignByPatient(patient);
        SignFamily sanshiSign = signFamilyDao.findSanshiSignByPatient(patient);
        if (familySign != null) {
            if (doctor.equals(StringUtils.isEmpty(familySign.getDoctor()) ? "" : familySign.getDoctor()) ||
                    doctor.equals(StringUtils.isEmpty(familySign.getDoctorHealth()) ? "" : familySign.getDoctorHealth())) {
                if (familySign.getStatus() == 0) {
                    result.put("status", "0");
                    result.put("msg", "已申请家庭签约");
                } else {
                    result.put("status", "1");
                    result.put("msg", "已有家庭签约");
                }
                return result;
            }
        }
        if (sanshiSign != null) {
            if (doctor.equals(StringUtils.isEmpty(sanshiSign.getDoctor()) ? "" : sanshiSign.getDoctor()) ||
                    doctor.equals(StringUtils.isEmpty(sanshiSign.getDoctorHealth()) ? "" : sanshiSign.getDoctorHealth())) {
                result.put("status", "2");
                result.put("msg", "已有三师签约");
                return result;
            }
        }
        result.put("status", "-1");
        result.put("msg", "无签约关系");
        return result;
    }
    /**
     * 判断医生与居民是否可签约
     *
     * @param patient
     * @param doctor
     * @return
     */
    public JSONObject isPatientAndDoctorCanSign(String patient, String doctor) {
        JSONObject result = new JSONObject();
        Doctor doc = doctorDao.findByCode(doctor);
        SignFamily familySign = signFamilyDao.findFamilySignByPatient(patient);
        SignFamily sanshiSign = signFamilyDao.findSanshiSignByPatient(patient);
        if (familySign != null) {
            if (familySign.getStatus() == 0) {
                result.put("status", "0");
                result.put("msg", "已申请签约,不可签约");
            } else {
                result.put("status", "-1");
                result.put("msg", "因已签约家庭医生,不可签约");
            }
            return result;
        }
        if (sanshiSign != null) {
            if (doc.getLevel() == 2) {
                if (!doctor.equals(StringUtils.isEmpty(sanshiSign.getDoctor()) ? "" : sanshiSign.getDoctor())) {
                    result.put("status", "-2");
                    result.put("msg", "因签约对象不含签约三师中全科,不可签约");
                    return result;
                }
            } else {
                List<AdminTeam> teams = adminTeamService.findDoctorsTeams(doctor, sanshiSign.getDoctor());
                if (teams == null || teams.size() < 1) {
                    result.put("status", "-3");
                    result.put("msg", "因签约对象不与签约三师中全科在同一团队,不可签约");
                } else {
                    result.put("status", "1");
                    result.put("msg", "可签约");
                    result.put("team", teams);
                }
                return result;
            }
        }
        result.put("status", "1");
        result.put("msg", "可签约");
        return result;
    }
}

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

@ -72,7 +72,12 @@ public class StatisticsAllService extends BaseService {
        String preDate = endDate;
        if (endDate.compareTo(dateFormat.format(new Date())) >= 0) {
            String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            } catch (Exception e) {
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
@ -136,7 +141,12 @@ public class StatisticsAllService extends BaseService {
        String preDate = endDate;
        if (endDate.compareTo(dateFormat.format(new Date())) >= 0) {
            String val = redisTemplate.opsForValue().get("quota:16:" + level + ":" + area + ":0:" + getQuotaTimeStamp());
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:16:" + level + ":" + area + ":0:" + getQuotaTimeStamp());
            } catch (Exception e) {
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
@ -241,6 +251,239 @@ public class StatisticsAllService extends BaseService {
    }
    /**
     * 获取签约分组信息
     *
     * @param endDate
     * @param lowCode
     * @param area
     * @param level
     * @return
     */
    public JSONObject getGroupInfo(String endDate, String lowCode, String area, int level) {
        JSONObject json = new JSONObject();
        long total = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        boolean preFlag = false;
        String preDate = endDate;
        if (endDate.compareTo(dateFormat.format(new Date())) >= 0) {
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:17:" + level + ":" + area + ":" + lowCode + ":" + getQuotaTimeStamp());
            } catch (Exception e) {
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
                    total = valJson.getInt("num");
                }
            } else {
                preFlag = true;
                Calendar today = Calendar.getInstance();
                today.add(Calendar.DATE, -1);
                preDate = dateFormat.format(today.getTime());
            }
        } else {
            preFlag = true;
        }
        if (preFlag) {
            // 查询语句
            String sql = " select " +
                    "     ifnull(result,'0') amount" +
                    " from  " +
                    "     wlyy_quota_result " +
                    " where " +
                    "     quato_code = '17' " +
                    "   and level1_type = ? and del = '1'" +
                    "   and quota_date = ? " +
                    "   and level2_type = ? ";
            if (level == 4) {
                // 市级别
                sql += " and city = ? ";
            } else if (level == 3) {
                // 区、城镇级别
                sql += " and town = ? ";
            } else if (level == 2) {
                // 机构级别
                sql += " and org_code = ? ";
            } else if (level == 1) {
                sql += " and qkdoctor_code = ? ";
            }
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{level, preDate, lowCode, area});
            if (result != null && result.size() > 0) {
                total = (result.get(0).get("amount") != null ? Long.valueOf(result.get(0).get("amount").toString()) : 0L);
            }
        }
        int num = 0;
        int taskNum = 0;
        String redisNum = "";
        try {
            redisNum = redisTemplate.opsForValue().get("people:num:" + area);
        }catch (Exception e){
            redisNum = "";
        }
        if (StringUtils.isEmpty(redisNum)) {
            PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(area, Calendar.getInstance().get(Calendar.YEAR));
            if (peopleNum != null) {
                if (lowCode.equals("3")) {
                    num = peopleNum.getSixFiveNum();
                    taskNum = peopleNum.getSixFiveTaskNum();
                } else if (lowCode.equals("1")) {
                    num = peopleNum.getGxyNum();
                    taskNum = peopleNum.getGxyTaskNum();
                } else if (lowCode.equals("2")) {
                    num = peopleNum.getTnbNum();
                    taskNum = peopleNum.getTnbTaskNum();
                }
            }
        } else {
            JSONObject peopleNum = new JSONObject(redisNum);
            if (peopleNum != null) {
                if (lowCode.equals("3")) {
                    num = peopleNum.getInt("sixFiveNum");
                    taskNum = peopleNum.getInt("sixFiveTaskNum");
                } else if (lowCode.equals("1")) {
                    num = peopleNum.getInt("gxyNum");
                    taskNum = peopleNum.getInt("gxyTaskNum");
                } else if (lowCode.equals("2")) {
                    num = peopleNum.getInt("tnbNum");
                    taskNum = peopleNum.getInt("tnbTaskNum");
                }
            }
        }
        DecimalFormat df = new DecimalFormat("0.0000");
        json.put("sign", total);
        JSONObject signRate = new JSONObject();
        signRate.put("sign", total);
        signRate.put("people", num);
        signRate.put("rate", df.format((total * 1.0000) / num));
        json.put("signRate",signRate);
        JSONObject signTaskRate = new JSONObject();
        signTaskRate.put("sign", total);
        signTaskRate.put("people", taskNum);
        signTaskRate.put("rate", df.format((total * 1.0000) / taskNum));
        json.put("signTaskRate",signTaskRate);
        return json;
    }
    /**
     * 查询某个级别的某个指标到达量
     *
     * @param date
     * @param area
     * @param level
     * @param index
     * @param sort
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public JSONArray getLevelTwoLowLevelTotal(String date, String area, int level, String index, int sort, String lowLevel, String lowCode) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (date.compareTo(dateFormat.format(new Date())) >= 0) {
            resultList = getLevelTwoTodayLowLevelTotal(area, level, index, sort, lowLevel, lowCode);
        } else {
            resultList = getLevelTwoTodayBeforeLowLevelTotal(date, area, level, index, sort, lowLevel, lowCode);
        }
        // 结果为空时,自建结果集
        if (resultList == null || resultList.size() < 1) {
            resultList = getLowLevelMapKey(level, low_level, area);
        }
        if (resultList != null) {
            DecimalFormat df = new DecimalFormat("0.0000");
            for (Map<String, Object> map : resultList) {
                map.put("amount", map.get("amount") != null ? Long.valueOf(map.get("amount").toString()) : 0L);
                if (!low_level.equals("1")) {
                    String redisNum = "";
                    try {
                        redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    }catch (Exception e){
                        redisNum = "";
                    }
                    if (StringUtils.isEmpty(redisNum)) {
                        PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(map.get("code").toString(), Calendar.getInstance().get(Calendar.YEAR));
                        if (peopleNum != null) {
                            int num = 0;
                            int taskNum = 0;
                            if (lowCode.equals("3")) {
                                num = peopleNum.getSixFiveNum();
                                taskNum = peopleNum.getSixFiveTaskNum();
                            } else if (lowCode.equals("1")) {
                                num = peopleNum.getGxyNum();
                                taskNum = peopleNum.getGxyTaskNum();
                            } else if (lowCode.equals("2")) {
                                num = peopleNum.getTnbNum();
                                taskNum = peopleNum.getTnbTaskNum();
                            }
                            map.put("rate", df.format(((long) map.get("amount") * 1.0000) / num * 100));
                            map.put("taskRate", df.format(((long) map.get("amount") * 1.0000) / taskNum * 100));
                            map.put("targetRate", df.format(taskNum * 1.0000 / num * 100));
                            map.put("num", num);
                            map.put("task", taskNum);
                        }
                    } else {
                        JSONObject peopleNum = new JSONObject(redisNum);
                        if (peopleNum != null) {
                            int num = 0;
                            int taskNum = 0;
                            if (lowCode.equals("3")) {
                                num = peopleNum.getInt("sixFiveNum");
                                taskNum = peopleNum.getInt("sixFiveTaskNum");
                            } else if (lowCode.equals("1")) {
                                num = peopleNum.getInt("gxyNum");
                                taskNum = peopleNum.getInt("gxyTaskNum");
                            } else if (lowCode.equals("2")) {
                                num = peopleNum.getInt("tnbNum");
                                taskNum = peopleNum.getInt("tnbTaskNum");
                            }
                            map.put("rate", df.format(((long) map.get("amount") * 1.0000) / num * 100));
                            map.put("taskRate", df.format(((long) map.get("amount") * 1.0000) / taskNum * 100));
                            map.put("targetRate", df.format(taskNum * 1.0000 / num * 100));
                            map.put("num", num);
                            map.put("task", taskNum);
                        }
                    }
                }
            }
            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    long map1value = (long) o1.get("amount");
                    long map2value = (long) o2.get("amount");
                    if (map1value - map2value > 0) {
                        return sort == 1 ? -1 : 1;
                    } else if (map1value - map2value < 0) {
                        return sort == 1 ? 1 : -1;
                    } else {
                        return 0;
                    }
                }
            });
            return new JSONArray(resultList);
        } else {
            return new JSONArray();
        }
    }
    /**
     * 查询某个级别的某个指标到达量
     *
@ -275,8 +518,12 @@ public class StatisticsAllService extends BaseService {
                map.put("amount", map.get("amount") != null ? Long.valueOf(map.get("amount").toString()) : 0L);
                if (!low_level.equals("1")) {
                    String redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    String redisNum = "";
                    try {
                        redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    }catch (Exception e){
                        redisNum = "";
                    }
                    if (StringUtils.isEmpty(redisNum)) {
                        PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(map.get("code").toString(), Calendar.getInstance().get(Calendar.YEAR));
                        if (peopleNum != null) {
@ -320,6 +567,74 @@ public class StatisticsAllService extends BaseService {
        }
    }
    /**
     * 获取过去某个日期某个区域一级指标的下级统计
     *
     * @param date
     * @param area
     * @param level
     * @param index
     * @param lowLevel
     * @return
     */
    public List<Map<String, Object>> getLevelTwoTodayBeforeLowLevelTotal(String date, String area, int level, String index, int sort, String lowLevel, String lowCode) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
        String areaField = "";
        String lowLevelField = "";
        String lowLevelName = "";
        if (level == 4) {
            // 市级别
            areaField = "city";
        } else if (level == 3) {
            // 区、城镇级别
            areaField = "town";
        } else if (level == 2) {
            // 机构级别
            areaField = "org_code";
        } else if (level == 1) {
            throw new Exception("param level error");
        }
        if (low_level.equals("3")) {
            lowLevelField = "town";
            lowLevelName = "town_name";
        } else if (low_level.equals("2")) {
            lowLevelField = "org_code";
            lowLevelName = "org_name";
        } else if (low_level.equals("1")) {
            lowLevelField = "qkdoctor_code";
            lowLevelName = "qkdoctor_name";
        } else {
            throw new Exception("param lowLevel error");
        }
        // 查询语句
        String sql = " select " +
                "     ifnull(" + lowLevelField + ",'') code " +
                "     ,ifnull(" + lowLevelName + ",'') 'name' " +
                "     ,ifnull(result,'0') amount" +
                " from  " +
                "     wlyy_quota_result " +
                " where " +
                "     quato_code = '" + index + "' " +
                "   and level1_type = ? and del = '1'" +
                "   and quota_date = ? " +
                "   and " + areaField + " = ? " +
                "   and level2_type = ? ";
        if (sort == 1) {
            sql += " order by amount desc ";
        } else {
            sql += " order by amount asc ";
        }
        resultList = jdbcTemplate.queryForList(sql, new Object[]{low_level, date, area, lowCode});
        return resultList;
    }
    /**
     * 获取过去某个日期某个区域一级指标的下级统计
     *
@ -397,11 +712,58 @@ public class StatisticsAllService extends BaseService {
     * @param lowLevel
     * @return
     */
    public List<Map<String, Object>> getTodayLowLevelTotal(String area, int level, String index, int sort, String lowLevel) throws Exception {
    public List<Map<String, Object>> getLevelTwoTodayLowLevelTotal(String area, int level, String index, int sort, String lowLevel, String lowCode) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
        String redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + low_level + ":" + getQuotaTimeStamp());
        resultList = getLowLevelMapKey(level, low_level, area);
        boolean flag = false;
        for (Map<String, Object> map : resultList) {
            //String redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + String.valueOf(map.get("code")) + ":" + lowCode + ":" + getQuotaTimeStamp());
            String redisData = "";
            try {
                redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + String.valueOf(map.get("code")) + ":" + lowCode + ":" + getQuotaTimeStamp());
            } catch (Exception e) {
                redisData = "";
            }
            if (!StringUtils.isEmpty(redisData)) {
                JSONObject json = new JSONObject(redisData);
                map.put("amount", Long.valueOf(String.valueOf(json.get("num"))));
            } else {
                flag = true;
                resultList = new ArrayList<>();
                break;
            }
        }
        if (flag) {
            Calendar today = Calendar.getInstance();
            today.add(Calendar.DATE, -1);
            String preDate = new SimpleDateFormat("yyyy-MM-dd").format(today.getTime());
            resultList = getLevelTwoTodayBeforeLowLevelTotal(preDate, area, level, index, sort, lowLevel, lowCode);
        }
        return resultList;
    }
    /**
     * 获取今天某个区域一级指标的下级统计
     *
     * @param area
     * @param level
     * @param index
     * @param lowLevel
     * @return
     */
    public List<Map<String, Object>> getTodayLowLevelTotal(String area, int level, String index, int sort, String lowLevel) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
        String redisData = "";
        try {
            redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + low_level + ":" + getQuotaTimeStamp());
        } catch (Exception e) {
            redisData = "";
        }
        if (!StringUtils.isEmpty(redisData)) {
            JSONArray jsonArray = new JSONArray(redisData);
@ -429,6 +791,7 @@ public class StatisticsAllService extends BaseService {
        return resultList;
    }
    /**
     * 获取下级统计key
     *
@ -536,18 +899,6 @@ public class StatisticsAllService extends BaseService {
            for (Map<String, Object> map : resultList) {
                map.put("amount", map.get("amount") == null ? 0 : Math.round(Double.valueOf(map.get("amount").toString())));
                // 当天数据统计
                if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) == 0) {
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
                    String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + code + ":" + area + ":" + getQuotaTimeStamp());
                    if (!StringUtils.isEmpty(val)) {
                        JSONObject valJson = new JSONObject(val);
                        if (valJson.has("num")) {
                            map.put("amount", (long) map.get("amount") + valJson.getInt("num"));
                        }
                    }
                }
                if (index.equals("7")) {
                    // 分组指标总数算法
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
@ -656,8 +1007,12 @@ public class StatisticsAllService extends BaseService {
     */
    public List<Map<String, Object>> getTodayLevelTwoTotal(String area, int level, String index) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
        String redisData = "";
        try {
            redisData = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
        } catch (Exception e) {
            redisData = "";
        }
        if (!StringUtils.isEmpty(redisData)) {
            JSONArray jsonArray = new JSONArray(redisData);
@ -865,8 +1220,12 @@ public class StatisticsAllService extends BaseService {
        String preDate = endDate;
        if (endDate.compareTo(datef.format(new Date())) >= 0) {
            String redisData = redisTemplate.opsForValue().get("quota:12:" + level + ":" + area + ":6:" + getQuotaTimeStamp());
            String redisData = "";
            try {
                redisData = redisTemplate.opsForValue().get("quota:12:" + level + ":" + area + ":6:" + getQuotaTimeStamp());
            } catch (Exception e) {
                redisData = "";
            }
            if (!StringUtils.isEmpty(redisData)) {
                JSONArray jsonArray = new JSONArray(redisData);
@ -990,7 +1349,12 @@ public class StatisticsAllService extends BaseService {
        if (endDate.compareTo(datef.format(new Date())) >= 0) {
            String code = "6";
            String val = redisTemplate.opsForValue().get("quota:8:" + level + ":" + area + ":" + code + ":" + getQuotaTimeStamp());
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:8:" + level + ":" + area + ":" + code + ":" + getQuotaTimeStamp());
            } catch (Exception e) {
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
@ -1058,12 +1422,17 @@ public class StatisticsAllService extends BaseService {
     * @param index
     * @return
     */
    public JSONObject getDateTotal(String startDate, String endDate, int interval, String area, int level, String index) throws Exception {
    public JSONObject getDateTotal(String startDate, String endDate, int interval, String area, int level, String index, String lowCode) throws Exception {
        int taskNum = 0;
        JSONObject json = new JSONObject();
        if (level > 1) {
            String redisNum = redisTemplate.opsForValue().get("people:num:" + area);
        if (level > 1 && StringUtils.isEmpty(lowCode)) {
            String redisNum = "";
            try {
                redisNum = redisTemplate.opsForValue().get("people:num:" + area);
            }catch (Exception e){
                redisNum = "";
            }
            if (StringUtils.isEmpty(redisNum)) {
                PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(area, Calendar.getInstance().get(Calendar.YEAR));
@ -1077,19 +1446,50 @@ public class StatisticsAllService extends BaseService {
                }
            }
        }
        if (!StringUtils.isEmpty(lowCode)) {
            String redisNum = "";
            try {
                redisNum = redisTemplate.opsForValue().get("people:num:" + area);
            }catch (Exception e){
                redisNum = "";
            }
            if (StringUtils.isEmpty(redisNum)) {
                PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(area, Calendar.getInstance().get(Calendar.YEAR));
                if (peopleNum != null) {
                    if (lowCode.equals("3")) {
                        taskNum = peopleNum.getSixFiveTaskNum();
                    } else if (lowCode.equals("1")) {
                        taskNum = peopleNum.getGxyTaskNum();
                    } else if (lowCode.equals("2")) {
                        taskNum = peopleNum.getTnbTaskNum();
                    }
                }
            } else {
                JSONObject peopleNum = new JSONObject(redisNum);
                if (peopleNum != null) {
                    if (lowCode.equals("3")) {
                        taskNum = peopleNum.getInt("sixFiveTaskNum");
                    } else if (lowCode.equals("1")) {
                        taskNum = peopleNum.getInt("gxyTaskNum");
                    } else if (lowCode.equals("2")) {
                        taskNum = peopleNum.getInt("tnbTaskNum");
                    }
                }
            }
        }
        json.put("taskNum", taskNum);
        if (interval == 1) {
            JSONArray jsonArray = dateTotalStatistics(startDate, endDate, area, level, index);
            JSONArray jsonArray = dateTotalStatistics(startDate, endDate, area, level, index, lowCode);
            json.put("data", jsonArray);
            return json;
        } else if (interval == 2) {
            JSONArray jsonArray = weekTotalStatistics(startDate, endDate, area, level, index);
            JSONArray jsonArray = weekTotalStatistics(startDate, endDate, area, level, index, lowCode);
            json.put("data", jsonArray);
            return json;
        } else if (interval == 3) {
            JSONArray jsonArray = monthTotalStatistics(startDate, endDate, area, level, index);
            JSONArray jsonArray = monthTotalStatistics(startDate, endDate, area, level, index, lowCode);
            json.put("data", jsonArray);
            return json;
        }
@ -1105,7 +1505,7 @@ public class StatisticsAllService extends BaseService {
     * @param index
     * @return
     */
    public JSONArray dateTotalStatistics(String startDate, String endDate, String area, int level, String index) throws ParseException {
    public JSONArray dateTotalStatistics(String startDate, String endDate, String area, int level, String index, String lowCode) throws ParseException {
        String areaField = "";
        String sql = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@ -1170,7 +1570,12 @@ public class StatisticsAllService extends BaseService {
            // 当前范围包含当天,则需添加当天的统计数据
            if (startStr.compareTo(df.format(new Date())) == 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + (!StringUtils.isEmpty(lowCode) ? (lowCode + ":") : "") + getQuotaTimeStamp());
                } catch (Exception e) {
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
@ -1205,6 +1610,10 @@ public class StatisticsAllService extends BaseService {
                "   and quota_date <= '" + dateCon + "' " +
                "   and " + areaField + " = '" + area + "' ";
        if (!StringUtils.isEmpty(lowCode)) {
            sql += "  and level2_type = '" + lowCode + "' ";
        }
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
        if (resultList != null) {
@ -1248,7 +1657,7 @@ public class StatisticsAllService extends BaseService {
     * @param index
     * @return
     */
    private JSONArray weekTotalStatistics(String startDate, String endDate, String area, int level, String index) throws Exception {
    private JSONArray weekTotalStatistics(String startDate, String endDate, String area, int level, String index, String lowCode) throws Exception {
        String areaField = "";
        String sql = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@ -1347,7 +1756,12 @@ public class StatisticsAllService extends BaseService {
            // 当前范围包含当天,则需添加当天的统计数据
            if (startStr.compareTo(df.format(new Date())) <= 0 && endStr.compareTo(df.format(new Date())) >= 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + (!StringUtils.isEmpty(lowCode) ? (lowCode + ":") : "") + getQuotaTimeStamp());
                } catch (Exception e) {
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
@ -1385,6 +1799,10 @@ public class StatisticsAllService extends BaseService {
                "   and quota_date <= '" + dateCon + "' " +
                "   and " + areaField + " = '" + area + "' ";
        if (!StringUtils.isEmpty(lowCode)) {
            sql += "  and level2_type = '" + lowCode + "' ";
        }
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
        if (resultList != null) {
@ -1432,7 +1850,7 @@ public class StatisticsAllService extends BaseService {
     * @return
     * @throws Exception
     */
    private JSONArray monthTotalStatistics(String startDate, String endDate, String area, int level, String index) throws Exception {
    private JSONArray monthTotalStatistics(String startDate, String endDate, String area, int level, String index, String lowCode) throws Exception {
        String areaField = "";
        String sql = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@ -1521,7 +1939,12 @@ public class StatisticsAllService extends BaseService {
            // 当天数据计算
            if (startStr.compareTo(df.format(new Date())) <= 0 && endStr.compareTo(df.format(new Date())) >= 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + (!StringUtils.isEmpty(lowCode) ? (lowCode + ":") : "") + getQuotaTimeStamp());
                } catch (Exception e) {
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
@ -1559,6 +1982,10 @@ public class StatisticsAllService extends BaseService {
                "   and quota_date <= '" + dateCon + "' " +
                "   and " + areaField + " = '" + area + "' ";
        if (!StringUtils.isEmpty(lowCode)) {
            sql += "  and level2_type = '" + lowCode + "' ";
        }
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql);
        if (resultList != null) {

+ 62 - 10
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statistics/StatisticsService.java

@ -56,7 +56,13 @@ public class StatisticsService extends BaseService {
     * @return
     */
    public String getStatisticsTime() {
        String date = redisTemplate.opsForValue().get("quota:date");
        String date = DateUtil.dateToStrLong(new Date());
        try {
            date = redisTemplate.opsForValue().get("quota:date");
        }catch (Exception e){
            e.printStackTrace();
        }
        return date;
    }
@ -124,7 +130,13 @@ public class StatisticsService extends BaseService {
        // 截止日期包含当天,则从redis查询当天统计数据
        if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
            String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            }catch (Exception e){
                e.printStackTrace();
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
@ -180,7 +192,13 @@ public class StatisticsService extends BaseService {
        // 截止日期包含当天,则从redis查询当天统计数据
        if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
            String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            String val = "";
            try {
                val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
            }catch (Exception e){
                e.printStackTrace();
                val = "";
            }
            if (!StringUtils.isEmpty(val)) {
                JSONObject valJson = new JSONObject(val);
                if (valJson.has("num")) {
@ -340,7 +358,13 @@ public class StatisticsService extends BaseService {
                // 截止日期包含当天,则从redis查询当天统计数据
                if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
                    String val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    String val = "";
                    try {
                        val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    }catch (Exception e){
                        e.printStackTrace();
                        val = "";
                    }
                    if (!StringUtils.isEmpty(val)) {
                        JSONObject valJson = new JSONObject(val);
                        if (valJson.has("num")) {
@ -350,8 +374,12 @@ public class StatisticsService extends BaseService {
                }
                if (!low_level.equals("1")) {
                    String redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    String redisNum = "";
                    try {
                        redisNum = redisTemplate.opsForValue().get("people:num:" + map.get("code").toString());
                    }catch (Exception e){
                        redisNum = "";
                    }
                    if (StringUtils.isEmpty(redisNum)) {
                        PopulationBase peopleNum = peopleNumDao.findByCodeAndYear(map.get("code").toString(), Calendar.getInstance().get(Calendar.YEAR));
                        if (peopleNum != null) {
@ -533,7 +561,13 @@ public class StatisticsService extends BaseService {
                // 截止日期包含当天,则从redis查询当天统计数据
                if (endDate.compareTo(new SimpleDateFormat("yyyy-MM-dd").format(new Date())) >= 0) {
                    String code = map.get("code") != null ? String.valueOf(map.get("code")) : "";
                    String val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    String val = "";
                    try {
                        val = redisTemplate.opsForValue().get("quota:" + index + ":" + low_level + ":" + code + ":" + getQuotaTimeStamp());
                    }catch (Exception e){
                        e.printStackTrace();
                        val = "";
                    }
                    if (!StringUtils.isEmpty(val)) {
                        JSONObject valJson = new JSONObject(val);
                        if (valJson.has("num")) {
@ -656,7 +690,13 @@ public class StatisticsService extends BaseService {
            // 当前范围包含当天,则需添加当天的统计数据
            if (startStr.compareTo(today) == 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
@ -820,7 +860,13 @@ public class StatisticsService extends BaseService {
            // 当前范围包含当天,则需添加当天的统计数据
            if (startStr.compareTo(today) <= 0 && endStr.compareTo(today) >= 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {
@ -1016,7 +1062,13 @@ public class StatisticsService extends BaseService {
            // 当天数据计算
            if (startStr.compareTo(today) <= 0 && endStr.compareTo(today) >= 0) {
                String val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                String val = "";
                try {
                    val = redisTemplate.opsForValue().get("quota:" + index + ":" + level + ":" + area + ":" + getQuotaTimeStamp());
                }catch (Exception e){
                    e.printStackTrace();
                    val = "";
                }
                if (!StringUtils.isEmpty(val)) {
                    JSONObject valJson = new JSONObject(val);
                    if (valJson.has("num")) {

+ 651 - 20
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/talk/TalkGroupService.java

@ -6,16 +6,25 @@ import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.print.Doc;
import javax.transaction.Transactional;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeamMember;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.util.SystemConf;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@ -31,16 +40,18 @@ import org.springframework.util.StringUtils;
@Transactional
public class TalkGroupService extends BaseService {
    // 讨论组DAO
    @Autowired
    DiscussionGroupDao discussionGroupDao;
    @Autowired
    // 讨论组成员DAO
    DiscussionGroupMemberDao discussionGroupMemberDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DoctorDao doctorDao;
    @Autowired
    AdminTeamService teamService;
    @Autowired
    PatientDao patientDao;
    /**
     * 讨论组保存
@ -71,6 +82,23 @@ public class TalkGroupService extends BaseService {
        discussionGroupMemberDao.save(member);
    }
    /**
     * 判断成员是否已在讨论组内
     *
     * @param group
     * @param member
     * @return
     */
    public boolean isMemberExists(String group, String member) {
        WlyyTalkGroupMember m = discussionGroupMemberDao.findByGroupCodeAndMemberCode(group, member);
        if (m != null) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 移除讨论组成员
     *
@ -137,7 +165,6 @@ public class TalkGroupService extends BaseService {
        saveTalkGroup(talkGroup, members);
    }
    /**
     * 获取医生讨论组列表
     *
@ -329,7 +356,6 @@ public class TalkGroupService extends BaseService {
        return discussionGroupMemberDao.countByMemberCode(doctor);
    }
    /**
     * 获取以上一对一聊天
     *
@ -337,13 +363,13 @@ public class TalkGroupService extends BaseService {
     * @param doctorName
     * @return
     */
    public JSONArray getOneToOneIm(String doctor,String doctorName) throws UnsupportedEncodingException {
    public JSONArray getOneToOneIm(String doctor, String doctorName) throws UnsupportedEncodingException {
        JSONArray result = null;
        JSONArray resultArray = new JSONArray();
        String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                + "statistic/getchatlist.im";
        String json = HttpUtil.sendGet(url, "uid=" + doctor);
        if(!StringUtils.isEmpty(json) && json.trim().startsWith("[") && json.trim().endsWith("]")) {
        if (!StringUtils.isEmpty(json) && json.trim().startsWith("[") && json.trim().endsWith("]")) {
            System.out.println("one-to-one:" + json);
            result = new JSONArray(json);
        }
@ -355,27 +381,27 @@ public class TalkGroupService extends BaseService {
                    JSONObject objRe = new JSONObject();
                    Doctor fromDoctor = doctorDao.findByCode(obj.get("peer_uid").toString());
                    if(fromDoctor == null){
                    if (fromDoctor == null) {
                        continue;
                    }
                    if(!StringUtils.isEmpty(doctorName)){
                        if(!fromDoctor.getName().contains(doctorName)){
                    if (!StringUtils.isEmpty(doctorName)) {
                        if (!fromDoctor.getName().contains(doctorName)) {
                            continue;
                        }
                    }
                    objRe.put("uid",obj.get("uid") != null ? obj.getString("uid") :"");
                    objRe.put("fromUid",obj.get("peer_uid") != null ? obj.get("peer_uid").toString() : "");
                    objRe.put("fromName",fromDoctor.getName());
                    objRe.put("fromLevel",fromDoctor.getLevel());
                    objRe.put("photo",StringUtils.isEmpty(fromDoctor.getPhoto())?"":fromDoctor.getPhoto());
                    objRe.put("sex",fromDoctor.getSex());
                    objRe.put("lastContentType",obj.getInt("last_content_type"));
                    objRe.put("lastContent",obj.get("last_content") != null?new String(obj.getString("last_content").getBytes(),"utf-8"):"");
                    objRe.put("newMsgCount",obj.getInt("new_msg_count"));
                    objRe.put("lastMsgTime",obj.get("timestamp") != null ? DateUtil.dateToStr(new Date(obj.getLong("timestamp")),DateUtil.YYYY_MM_DD_HH_MM):"");
                    objRe.put("lastMsgTimeLong",obj.getLong("timestamp"));
                    objRe.put("uid", obj.get("uid") != null ? obj.getString("uid") : "");
                    objRe.put("fromUid", obj.get("peer_uid") != null ? obj.get("peer_uid").toString() : "");
                    objRe.put("fromName", fromDoctor.getName());
                    objRe.put("fromLevel", fromDoctor.getLevel());
                    objRe.put("photo", StringUtils.isEmpty(fromDoctor.getPhoto()) ? "" : fromDoctor.getPhoto());
                    objRe.put("sex", fromDoctor.getSex());
                    objRe.put("lastContentType", obj.getInt("last_content_type"));
                    objRe.put("lastContent", obj.get("last_content") != null ? new String(obj.getString("last_content").getBytes(), "utf-8") : "");
                    objRe.put("newMsgCount", obj.getInt("new_msg_count"));
                    objRe.put("lastMsgTime", obj.get("timestamp") != null ? DateUtil.dateToStr(new Date(obj.getLong("timestamp")), DateUtil.YYYY_MM_DD_HH_MM) : "");
                    objRe.put("lastMsgTimeLong", obj.getLong("timestamp"));
                    resultArray.put(objRe);
                }
@ -385,5 +411,610 @@ public class TalkGroupService extends BaseService {
        return resultArray;
    }
    /**
     * 搜索转发医生
     *
     * @param doctor
     * @param filter
     * @return
     */
    public JSONObject searchImDoctor(String doctor, String filter) {
        JSONObject result = new JSONObject();
        String sqlDoc = "select * from wlyy_doctor where name like ? ";
        String sqlTalkGroup = "select DISTINCT g.* from " +
                " (select " +
                "   gi.* " +
                " from" +
                "  wlyy_talk_group_member mi " +
                "  ,wlyy_talk_group gi " +
                " where mi.group_code = gi.code and mi.member_code = ?) g " +
                " left join wlyy_talk_group_member m on g.code = m.group_code where g.type = 2 and g.name like ? or m.member_name like ? ";
        String sqlTeam = "select DISTINCT t.* from " +
                " (select " +
                "   ti.* " +
                " from" +
                "  wlyy_admin_team_member mi " +
                "  ,wlyy_admin_team ti " +
                " where mi.team_id = ti.id and mi.doctor_code = ?) t " +
                " left join wlyy_admin_team_member m on t.id = m.team_id join wlyy_doctor d on m.doctor_code = d.code where t.name like ? or d.name like ? ";
        List<Doctor> doctors = jdbcTemplate.query(sqlDoc, new Object[]{"%" + filter + "%"}, new BeanPropertyRowMapper(Doctor.class));
        List<WlyyTalkGroup> groups = jdbcTemplate.query(sqlTalkGroup, new Object[]{doctor, "%" + filter + "%", "%" + filter + "%"}, new BeanPropertyRowMapper(WlyyTalkGroup.class));
        List<AdminTeam> teams = jdbcTemplate.query(sqlTeam, new Object[]{doctor, "%" + filter + "%", "%" + filter + "%"}, new BeanPropertyRowMapper(AdminTeam.class));
        if (doctors != null && doctors.size() > 0) {
            JSONArray docArray = new JSONArray();
            for (Doctor doc : doctors) {
                JSONObject json = new JSONObject(doc);
                if (json.has("password")) {
                    json.remove("password");
                }
                if (json.has("salt")) {
                    json.remove("salt");
                }
                docArray.put(json);
            }
            result.put("doctor", docArray);
        }
        if (groups != null && groups.size() > 0) {
            JSONArray groupsArray = new JSONArray();
            for (WlyyTalkGroup group : groups) {
                JSONObject json = new JSONObject(group);
                List<WlyyTalkGroupMember> members = findTalkGroupMembers(group.getCode());
                json.put("members", members);
                groupsArray.put(json);
            }
            result.put("groupChat", groupsArray);
        }
        if (teams != null && teams.size() > 0) {
            JSONArray teamArray = new JSONArray();
            for (AdminTeam team : teams) {
                JSONObject json = new JSONObject(team);
                List<Doctor> members = teamService.getMembers(team.getId());
                if (members != null && members.size() > 0) {
                    JSONArray memberArray = new JSONArray();
                    for (Doctor doc : members) {
                        JSONObject dJson = new JSONObject(doc);
                        if (dJson.has("password")) {
                            dJson.remove("password");
                        }
                        if (dJson.has("salt")) {
                            dJson.remove("salt");
                        }
                        memberArray.put(dJson);
                    }
                    json.put("members", memberArray);
                } else {
                    json.put("members", new JSONArray());
                }
                teamArray.put(json);
            }
            result.put("teamChat", teamArray);
        }
        return result;
    }
    /**
     * 查询医生IM列表
     *
     * @param doctor 医生
     * @param type   聊天对象类型 1:居民 2:医生
     * @return
     */
    public JSONObject getImList(String doctor, int type, int page, int pagesize) {
        JSONObject result = new JSONObject();
        result.put("oneChat", getOneImList(doctor, type, page, pagesize));
        result.put("groupChat", getTalkgroupList(doctor, type, page, pagesize));
        if (type == 2) {
            result.put("teamChat", getTeamChatList(doctor, page, pagesize));
        }
        return result;
    }
    /**
     * 查询医生一对一IM列表
     *
     * @param doctor 医生
     * @param type   聊天对象类型 1:居民 2:医生
     * @return
     */
    public JSONArray getOneImList(String doctor, int type, int page, int pagesize) {
        JSONArray list = new JSONArray();
        JSONArray imList = new JSONArray();
        String sqlP = "";
        if (type == 1) {
            sqlP = "select code,name,photo,sex,idcard,mobile from wlyy_patient where code = ? ";
        } else {
            sqlP = "select code,name,photo,sex,idcard,mobile,level from wlyy_doctor where code = ? ";
        }
        for (int i = 0; i < imList.length(); i++) {
            JSONObject im = imList.getJSONObject(i);
            JSONObject json = new JSONObject();
            Map<String, Object> map = jdbcTemplate.queryForMap(sqlP, new Object[]{im.get("")});
            if (map != null) {
                json.put("name", map.get("name"));
                json.put("sex", map.get("sex"));
                json.put("idcard", map.get("idcard"));
                json.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard") != null ? String.valueOf(map.get("idcard")) : ""));
                json.put("photo", map.get("photo"));
                json.put("mobile", map.get("mobile"));
                if (type == 2) {
                    json.put("level", map.get("level"));
                }
            }
            list.put(json);
        }
        return list;
    }
    /**
     * 查询医生讨论组列表
     *
     * @param doctor   医生
     * @param type     聊天对象类型 1:咨询 2:其他
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    public JSONArray getTalkgroupList(String doctor, int type, int page, int pagesize) {
        JSONArray list = new JSONArray();
        String sqlGroup = "select * " +
                " from" +
                "     wlyy_talk_group g" +
                " join" +
                "     wlyy_talk_group_member m" +
                "  on g.code = m.group_code" +
                " where" +
                "     m.member_code = ? and g.type = " + (type == 1 ? "1" : "2") + " limit " + page * pagesize + "," + pagesize;
        List<WlyyTalkGroup> talkGroups = jdbcTemplate.query(sqlGroup,
                new Object[]{doctor}, new BeanPropertyRowMapper(WlyyTalkGroup.class));
        for (WlyyTalkGroup group : talkGroups) {
            JSONObject obj = new JSONObject(group);
            List<WlyyTalkGroupMember> members = findTalkGroupMembers(group.getCode());
            JSONArray mArray = new JSONArray();
            for (WlyyTalkGroupMember member : members) {
                JSONObject mJson = new JSONObject();
                mJson.put("memberCode", member.getMemberCode());
                mJson.put("memberName", member.getMemberName());
                mJson.put("type", member.getType());
                Map<String, Object> mObj = null;
                if (member.getType() == 4) {
                    String sqlP = "select code,name,photo,sex,idcard,mobile from wlyy_patient where code = ? ";
                    mObj = jdbcTemplate.queryForMap(sqlP, new Object[]{member.getMemberCode()});
                } else {
                    String sqlP = "select code,name,photo,sex,idcard,mobile,level from wlyy_doctor where code = ? ";
                    mObj = jdbcTemplate.queryForMap(sqlP, new Object[]{member.getMemberCode()});
                }
                if (mObj != null) {
                    mJson.put("memberName", mObj.get("name"));
                    mJson.put("sex", mObj.get("sex"));
                    mJson.put("idcard", mObj.get("idcard"));
                    mJson.put("age", IdCardUtil.getAgeForIdcard(mObj.get("idcard") != null ? String.valueOf(mObj.get("idcard")) : ""));
                    mJson.put("photo", mObj.get("photo"));
                    if (member.getType() != 4) {
                        mJson.put("level", mObj.get("level"));
                    }
                }
                mArray.put(mJson);
            }
            obj.put("members", mArray);
            list.put(obj);
        }
        return list;
    }
    /**
     * 查询团队聊天
     *
     * @param doctor
     * @param page
     * @param pagesize
     * @return
     */
    public JSONArray getTeamChatList(String doctor, int page, int pagesize) {
        String sql = "select t.* from wlyy_admin_team t" +
                " join wlyy_admin_team_member m" +
                " on t.id = m.team_id" +
                " where m.doctor_code = ? limit " + page * pagesize + "," + pagesize;
        List<AdminTeam> teams = jdbcTemplate.query(sql, new Object[]{doctor}, new BeanPropertyRowMapper(AdminTeam.class));
        JSONArray teamArray = new JSONArray();
        if (teams != null) {
            for (AdminTeam team : teams) {
                JSONObject json = new JSONObject(team);
                List<Doctor> members = teamService.getMembers(team.getId());
                if (members != null && members.size() > 0) {
                    JSONArray memberArray = new JSONArray();
                    for (Doctor doc : members) {
                        JSONObject dJson = new JSONObject();
                        dJson.put("memberCode", doc.getCode());
                        dJson.put("memberName", doc.getName());
                        dJson.put("sex", doc.getSex());
                        dJson.put("idcard", doc.getIdcard());
                        dJson.put("age", IdCardUtil.getAgeForIdcard(doc.getIdcard()));
                        dJson.put("photo", doc.getPhoto());
                        dJson.put("level", doc.getLevel());
                        memberArray.put(dJson);
                    }
                    json.put("members", memberArray);
                } else {
                    json.put("members", new JSONArray());
                }
                teamArray.put(json);
            }
        }
        return teamArray;
    }
    /**
     * 查询医生最近联系IM列表
     *
     * @param doctor 医生
     * @param type   聊天对象类型 1:居民 2:医生
     * @return
     */
    public JSONObject getRecentImList(String doctor, int type) {
        JSONObject result = new JSONObject();
        if (type == 1) {
            result.put("oneChat", getRecentOneImList(doctor, type));
        } else {
            result.put("oneChat", getRecentOneImList(doctor, type));
            result.put("groupChat", getRecentGroupImList(doctor));
        }
        return result;
    }
    /**
     * 获取最近联系一对一IM列表
     *
     * @param doctor 医生
     * @return
     */
    public JSONArray getRecentOneImList(String doctor, int type) {
        JSONArray list = new JSONArray();
        JSONArray imList = new JSONArray();
        String sqlP = "";
        if (type == 1) {
            sqlP = "select code,name,photo,sex,idcard,mobile from wlyy_patient where code = ? ";
        } else {
            sqlP = "select code,name,photo,sex,idcard,mobile,level from wlyy_doctor where code = ? ";
        }
        for (int i = 0; i < imList.length(); i++) {
            JSONObject im = imList.getJSONObject(i);
            JSONObject json = new JSONObject();
            Map<String, Object> map = jdbcTemplate.queryForMap(sqlP, new Object[]{im.get("")});
            if (map != null) {
                json.put("code", map.get("code"));
                json.put("name", map.get("name"));
                json.put("sex", map.get("sex"));
                json.put("idcard", map.get("idcard"));
                json.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard") != null ? String.valueOf(map.get("idcard")) : ""));
                json.put("photo", map.get("photo"));
                json.put("mobile", map.get("mobile"));
                if (type == 2) {
                    json.put("level", map.get("level"));
                }
            }
            list.put(json);
        }
        return list;
    }
    /**
     * 获取最近联系的讨论组或团队群聊
     *
     * @param doctor 医生
     * @return
     */
    public JSONArray getRecentGroupImList(String doctor) {
        JSONArray list = new JSONArray();
        JSONArray imList = new JSONArray();
        for (int i = 0; i < imList.length(); i++) {
            JSONObject im = imList.getJSONObject(i);
            JSONObject json = new JSONObject();
            String sqlG = "";
            String sqlP = "select code,name,photo,sex,idcard,mobile,level from wlyy_doctor where code = ? ";
            Map<String, Object> map = jdbcTemplate.queryForMap(sqlP, new Object[]{im.get("")});
            if (map != null) {
                json.put("code", map.get("code"));
                json.put("name", map.get("name"));
                json.put("sex", map.get("sex"));
                json.put("idcard", map.get("idcard"));
                json.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard") != null ? String.valueOf(map.get("idcard")) : ""));
                json.put("photo", map.get("photo"));
                json.put("mobile", map.get("mobile"));
                json.put("level", map.get("level"));
            }
            list.put(json);
        }
        return list;
    }
    /**
     * IM搜索
     *
     * @param doctor     医生
     * @param type       搜索类型 1:居民 2: 医生
     * @param searchType 搜索类型 1:居民 2:居民聊天记录 3:医生 4:群聊 5:医生聊天记录
     * @param page       第几页
     * @param pagesize   页大小
     * @return
     */
    public JSONObject searchIm(String doctor, String filter, int type, int searchType, int page, int pagesize) {
        JSONObject result = new JSONObject();
        if (type == 1) {
            if (searchType == -1 || searchType == 1) {
                result.put("patient", searchPatients(filter, doctor, page, pagesize));
            }
            if (searchType == -1 || searchType == 2) {
                //result.put("patientChatRecord", searchPatients(filter, doctor, page, pagesize));
            }
        } else {
            if (searchType == -1 || searchType == 3) {
                result.put("doctor", searchDoctors(filter, page, pagesize));
            }
            if (searchType == -1 || searchType == 4) {
                result.put("groupChat", searchDoctorGroupChat(filter, doctor, page, pagesize));
            }
            if (searchType == -1 || searchType == 5) {
                //result.put("doctorChatRecord", searchPatients(filter, doctor, page, pagesize));
            }
        }
        return result;
    }
    /**
     * 搜索医生签约患者
     *
     * @param filter 搜索关键字
     * @param doctor 医生
     * @return
     */
    public JSONArray searchPatients(String filter, String doctor, int page, int pagesize) {
        JSONArray reArray = new JSONArray();
        int start = page * pagesize;
        int size = pagesize;
        String sql = "select distinct t.* from (" +
                " select " +
                "     f.patient " +
                "     ,f.name " +
                "     ,f.openid " +
                "     ,f.admin_team_code " +
                "     ,p.sex " +
                "     ,p.idcard " +
                "     ,p.photo " +
                " from " +
                "     wlyy_sign_family f,wlyy_patient p " +
                " where " +
                "      f.patient = p.code and f.doctor = ? and f.status > 0 and f.name like ? " +
                " union all " +
                "select " +
                "     f1.patient " +
                "     ,f1.name " +
                "     ,f1.openid " +
                "     ,f1.admin_team_code " +
                "     ,p1.sex " +
                "     ,p1.idcard " +
                "     ,p1.photo " +
                " from " +
                "     wlyy_sign_family f1,wlyy_patient p1" +
                " where " +
                "     f1.patient = p1.code and f1.doctor_health = ? and f1.status > 0 and f1.name like ? " +
                ") t  limit " + start + "," + size;
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{doctor,
                "%" + filter + "%", doctor, "%" + filter + "%"});
        if (result != null && result.size() > 0) {
            for (Map<String, Object> p : result) {
                JSONObject pJson = new JSONObject();
                pJson.put("code", p.get("patient"));
                pJson.put("name", p.get("name") != null ? p.get("name") : "");
                pJson.put("openid", p.get("openid") != null ? p.get("openid") : "");
                pJson.put("adminTeamCode", p.get("admin_team_code") != null ? p.get("admin_team_code") : "");
                pJson.put("sex", p.get("sex") != null ? p.get("sex") : "");
                pJson.put("age", p.get("idcard") != null ? IdCardUtil.getAgeForIdcard(String.valueOf(p.get("idcard"))) : "");
                pJson.put("photo", p.get("photo") != null ? p.get("photo") : "");
                pJson.put("idcard", p.get("idcard") != null ? p.get("idcard") : "");
                reArray.put(pJson);
            }
        }
        return reArray;
    }
    /**
     * 搜索医生与居民聊天记录
     *
     * @param filter   搜索关键字
     * @param doctor   医生
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    public JSONArray searchPatientRecords(String filter, String doctor, int page, int pagesize) {
        return null;
    }
    /**
     * 搜索医生
     *
     * @param filter   搜索关键字
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    public JSONArray searchDoctors(String filter, int page, int pagesize) {
        String sql = "select * from wlyy_doctor where name like ? limit " + page * pagesize + "," + pagesize;
        List<Doctor> doctorList = jdbcTemplate.query(sql, new Object[]{"%" + filter + "%"},
                new BeanPropertyRowMapper(Doctor.class));
        JSONArray docArray = new JSONArray();
        if (doctorList != null) {
            for (Doctor doc : doctorList) {
                JSONObject docJson = new JSONObject();
                docJson.put("code", doc.getCode());
                docJson.put("name", doc.getName());
                docJson.put("sex", doc.getSex());
                docJson.put("age", IdCardUtil.getAgeForIdcard(doc.getIdcard()));
                docJson.put("idcard", doc.getIdcard());
                docJson.put("mobile", doc.getMobile());
                docJson.put("level", doc.getLevel());
                docJson.put("photo", doc.getPhoto());
                docJson.put("hospital", doc.getHospital());
                docJson.put("hospitalName", doc.getHosptialName());
                docArray.put(docJson);
            }
        }
        return docArray;
    }
    /**
     * 搜索医生群聊
     *
     * @param filter   搜索关键字
     * @param doctor   医生
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    public JSONArray searchDoctorGroupChat(String filter, String doctor, int page, int pagesize) {
        JSONArray result = new JSONArray();
        String sqlTalkGroup = "select g.code,'1' type from " +
                " (select " +
                "   gi.* " +
                " from" +
                "  wlyy_talk_group_member mi " +
                "  ,wlyy_talk_group gi " +
                " where mi.group_code = gi.code and mi.member_code = ?) g " +
                " left join wlyy_talk_group_member m on g.code = m.group_code" +
                " where g.type = 2 and (g.name like ? or m.member_name like ?) ";
        String sqlTeam = "select cast(t.id as CHAR) code,'2' type from " +
                " (select " +
                "   ti.* " +
                " from" +
                "  wlyy_admin_team_member mii " +
                "  ,wlyy_admin_team ti " +
                " where mii.team_id = ti.id and mii.doctor_code = ?) t " +
                " left join wlyy_admin_team_member mm on t.id = mm.team_id join wlyy_doctor d" +
                " on mm.doctor_code = d.code where t.name like ? or d.name like ? ";
        String sql = "select DISTINCT o.* from (" + sqlTalkGroup + " union all "
                + sqlTeam + ") o limit " + page * pagesize + "," + pagesize;
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, new Object[]{doctor, "%" + filter + "%",
                "%" + filter + "%", doctor, "%" + filter + "%", "%" + filter + "%"});
        if (mapList != null) {
            for (Map<String, Object> map : mapList) {
                JSONObject json = new JSONObject();
                List<Doctor> members = null;
                if (String.valueOf(map.get("type")).equals("1")) {
                    WlyyTalkGroup group = discussionGroupDao.findByCode(map.get("code").toString());
                    String sqlDoc = "select d.* from" +
                            " wlyy_talk_group_member m" +
                            " join wlyy_doctor d" +
                            " on m.memebr_code = d.code" +
                            " where m.group_code = ? ";
                    members = jdbcTemplate.query(sqlDoc, new Object[]{map.get("code").toString()},
                            new BeanPropertyRowMapper(Doctor.class));
                    json.put("code", group.getCode());
                    json.put("name", group.getName());
                    json.put("type", "1");
                } else {
                    AdminTeam team = teamService.getTeam(Long.valueOf(map.get("code").toString()));
                    members = teamService.getMembers(Long.valueOf(map.get("code").toString()));
                    json.put("code", String.valueOf(team.getId()));
                    json.put("name", team.getName());
                    json.put("type", "2");
                }
                JSONArray mArray = new JSONArray();
                if (members != null) {
                    for (Doctor doc : members) {
                        JSONObject docJson = new JSONObject();
                        docJson.put("code", doc.getCode());
                        docJson.put("name", doc.getName());
                        docJson.put("sex", doc.getSex());
                        docJson.put("age", IdCardUtil.getAgeForIdcard(doc.getIdcard()));
                        docJson.put("idcard", doc.getIdcard());
                        docJson.put("mobile", doc.getMobile());
                        docJson.put("level", doc.getLevel());
                        docJson.put("photo", doc.getPhoto());
                        docJson.put("hospital", doc.getHospital());
                        docJson.put("hospitalName", doc.getHosptialName());
                        mArray.put(docJson);
                    }
                }
                json.put("members", mArray);
                result.put(json);
            }
        }
        return result;
    }
    /**
     * 搜索医生聊天记录
     *
     * @param filter   搜索关键字
     * @param doctor   医生
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    public JSONArray searchDoctorRecords(String filter, String doctor, int page, int pagesize) {
        return null;
    }
}

+ 22 - 5
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/team/DrHealthTeamService.java

@ -6,12 +6,10 @@
package com.yihu.wlyy.service.app.team;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatient;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
@ -19,6 +17,7 @@ import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -40,7 +39,8 @@ public class DrHealthTeamService extends BaseService {
    private DoctorTeamMemberDao doctorTeamMemberDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    DoctorAdminTeamMemberDao memberDao;
    /**
     * 查询签约团队的其他医生
     *
@ -256,4 +256,21 @@ public class DrHealthTeamService extends BaseService {
            return null;
        }
    }
    public Map<String,List<Doctor>> getTeamDoctorsAndAdminTeamDoctors(String doctorCode,Long teamId) {
        Map<String,List<Doctor>> returnMap=new HashMap<>();
        //得到责任医生
        List<Doctor> zrDoctors=  doctorTeamMemberDao.getTeamZKByQK(doctorCode);
        for(Doctor doctor:zrDoctors){
            //判断是否求助
        }
        //得到医生所在的团队的除了自己的所有人
        List<Doctor> teamDoctors= memberDao.findAllHeathExcludeThis(teamId, doctorCode);
        for(Doctor doctor:teamDoctors){
            //判断是否求助
        }
        returnMap.put("zr",zrDoctors);
        returnMap.put("team",teamDoctors);
        return returnMap;
    }
}

+ 7 - 12
patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/SMSService.java

@ -84,26 +84,26 @@ public class SMSService extends BaseService {
            sms.setContent("您的注册验证码为:" + captcha);
        } else if (type == 2 || type == 3) {
            // 找回密码
            sms.setContent("【厦门市民健康系统】您的找回密码验证码为:" + captcha);
            sms.setContent("您找回密码验证码为:" + captcha);
        } else if (type == 4 || type == 5) {
            // 登录
            sms.setContent("您的登录验证码为:" + captcha);
        } else if (type == 7) {
            // 手机号变更验证
            sms.setContent("【厦门市民健康系统】您的更换手机号验证码为:" + captcha);
            sms.setContent("您更换手机号验证码为:" + captcha);
        } else if (type == 8) {
            // 新手机号绑定验证
            sms.setContent("【厦门市民健康系统】您的新手机号验证码为:" + captcha);
            sms.setContent("您新手机号验证码为:" + captcha);
        } else if (type == 9) {
            // 新手机号绑定验证
            sms.setContent("【厦门市民健康系统】您绑定手机号的验证码为:" + captcha);
            sms.setContent("您绑定手机号验证码为:" + captcha);
        } else if (type == 10) {
            Patient patient = patientDao.findByCode(code);
            if (patient == null) {
                throw new Exception("短信发送失败!");
            }
            // 新手机号绑定验证
            sms.setContent("【厦门市民健康系统】" + patient.getName() + "欲添加您为家人,添加成功后,对方可登录您的账号,为您处理各类健康服务。如同意添加,可告知其验证码(" + captcha + ")。");
            sms.setContent(patient.getName() + "欲添加您为家人,添加成功后,对方可登录您的账号,为您处理各类健康服务。如同意添加,可告知其验证码(" + captcha + ")。");
        } else {
            // 其他验证码
            sms.setContent("验证码:" + captcha);
@ -139,16 +139,11 @@ public class SMSService extends BaseService {
     * @param content
     * @return
     */
    public int sendMsg(String mobile,String content){
    public JSONObject sendMsg(String mobile, String content) {
        // 调用总部发送信息的接口
        String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(content, mobile), "GBK");
        JSONObject json = toJson(result);
        if (json == null) {
           return 0;
        } else if (json.getInt("result") != 0) {
            return 0;
        }
        return 1;
        return json;
    }
    /**

+ 51 - 3
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/BaseController.java

@ -1,8 +1,7 @@
package com.yihu.wlyy.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
@ -16,6 +15,7 @@ import org.springframework.data.domain.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.IdEntity;
import org.springframework.util.ReflectionUtils;
public class BaseController {
@ -42,6 +42,24 @@ public class BaseController {
		}
	}
	/**
	 * 獲取髮送請求用戶的uid
	 * @return
	 */
	public String getLastUid() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("lastUid");
		} catch (Exception e) {
			return null;
		}
	}
	public String getOpenid() {
		try {
			String userAgent = request.getHeader("userAgent");
@ -462,5 +480,35 @@ public class BaseController {
			return null;
		}
	}
	public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String...propertyNames){
		List<Map<String, Object>> result = new ArrayList<>();
		for (Object bean : beans){
			result.add(copyBeanProperties(bean, propertyNames));
		}
		return result;
	}
	/**
	 * 复制特定属性。
	 *
	 * @param bean
	 * @param propertyNames
	 * @return
	 */
	public Map<String, Object> copyBeanProperties(Object bean, String...propertyNames){
		Map<String, Object> simplifiedBean = new HashMap<>();
		for (String propertyName : propertyNames){
			Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
			if (field != null){
				field.setAccessible(true);
				Object value = ReflectionUtils.getField(field, bean);
				simplifiedBean.put(propertyName, value == null ? "" : value);
			} else {
				simplifiedBean.put(propertyName, "");
			}
		}
		return simplifiedBean;
	}
}

+ 20 - 4
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java

@ -349,12 +349,20 @@ public class WechatController extends WeixinBaseController {
                }
                loginLog.setLoginType("2");
                if (patient == null) {
                    errorMessage="该手机号暂未注册帐号,请确认后重新输入!";
                    if(mobile.length()==11){
                        errorMessage="该手机号暂未注册帐号,请确认后重新输入!";
                    }else{
                        errorMessage="该身份证号暂未注册帐号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (patient.getStatus() == 0) {
                    errorMessage="该手机号已被禁止使用!";
                    if(mobile.length()==11){
                      errorMessage="该手机号已被禁止使用!";
                    }else{
                      errorMessage="该身份证号已被禁止使用!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1,errorMessage );
@ -430,12 +438,20 @@ public class WechatController extends WeixinBaseController {
                Patient patient = patientService.findByMobile(mobile);
                loginLog.setLoginType("1");
                if (patient == null) {
                    errorMessage="该手机号暂未注册帐号,请确认后重新输入!";
                    if(mobile.length()==11){
                        errorMessage="该手机号暂未注册帐号,请确认后重新输入!";
                    }else{
                        errorMessage="该身份证号暂未注册帐号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (patient.getStatus() == 0) {
                    errorMessage="该手机号已被禁止使用!";
                    if(mobile.length()==11){
                        errorMessage="该手机号已被禁止使用!";
                    }else{
                        errorMessage="该身份证号已被禁止使用!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);

+ 17 - 7
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.service.third.guahao.GuahaoXMService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
@ -10,6 +11,7 @@ import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@ -25,7 +27,8 @@ import java.util.*;
@RequestMapping(value = "/wlyy_service")
@Api(description = "卫计委签约接口调试")
public class WlyySerivceController extends BaseController{
    @Autowired
    private GuahaoXMService guahaoXM;
    /**
     * 检查是否签约
     *
@ -202,13 +205,20 @@ public class WlyySerivceController extends BaseController{
            String strEnd = sm.format(tenDateAfter);
            String checkUrl = SystemConf.getInstance().getSystemProperties().getProperty("sign_check_upload");
            String param = "?OrgCode="+OrgCode+"&DeptCode="+DeptCode+"&strStart="+strStart+"&strEnd="+strEnd+"&DocCode="+DocCode;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/smjk/RegDeptSpeDoctorSectionList"+param,"" );
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"医生排班时间获取失败");
            }else{
                JSONObject myJsonObject = new JSONObject(jsonString);
                return write(200,"医生排班时间获取成功","data",parseXmlForSpe(myJsonObject.get("data").toString()));
            /*****modify by linz 暂时把号源转换成普通号源****/
            List<Map<String,Object>> list =  guahaoXM.GetDoctorArrange(OrgCode,DeptCode,DocCode);
            //String jsonString = HttpUtil.sendPost(checkUrl + "/third/smjk/RegDeptSpeDoctorSectionList"+param,"" );
            //if(StringUtils.isEmpty(jsonString)){
            //    return write(-1,"医生排班时间获取失败");
            //}else{
            //    JSONObject myJsonObject = new JSONObject(jsonString);
            //    return write(200,"医生排班时间获取成功","data",parseXmlForSpe(myJsonObject.get("data").toString()));
            //}
            for(Map map :list){
                String date = (String)map.get("date");
                map.put("date",date.replaceAll("-","/"));
            }
            return write(200, "获取医生排班成功!", "data", list);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"医生排班时间获取失败");

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

@ -74,14 +74,10 @@ public class DoctorController extends BaseController {
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private TblBasicDao tblBasicDao;
    @Autowired
    private HospitalDeptService hospitalDeptService;
    @Autowired
    private HospitalDeptService deptService;
    @Autowired
    private DoctorWorkTimeService workTimeService;
    /**
@ -240,6 +236,104 @@ public class DoctorController extends BaseController {
        }
    }
    /**
     * 查询存在医生的医院列表
     *
     * @param type     类型 1:医院 2社区
     * @param province 省份
     * @param city     城市
     * @param town     城镇
     * @param key      名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @RequestMapping(value = "hospitals_list")
    @ResponseBody
    public String hospitalL(@RequestParam(required = true) int type,
                            @RequestParam(required = false) String province,
                            @RequestParam(required = false) String city,
                            @RequestParam(required = false) String town,
                            @RequestParam(required = false) String key,
                            @RequestParam(required = true) int page,
                            @RequestParam(required = true) int pagesize) {
        try {
            if (type != 1 && type != 2) {
                return error(-1, "医院类型错误");
            }
            page = page > 1 ? page - 1 : 0;
            List<Hospital> hos = hospitalService.getHospitals(type, province, city, town, key, page, pagesize);
            return write(200, "查询成功", "data", hos);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询某个医院存在医生科室列表
     *
     * @param hospital 医院
     * @param key      科室名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @RequestMapping(value = "/dept_list")
    @ResponseBody
    public String deptList(@RequestParam(required = true) String hospital,
                           @RequestParam(required = false) String key,
                           @RequestParam(required = true) int page,
                           @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(hospital)) {
                return error(-1, "医院不能为空");
            }
            page = page > 1 ? page - 1 : 0;
            List<HospitalDept> dept = deptService.getHospitalDept(hospital, key, page, pagesize);
            return write(200, "查询成功", "data", dept);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据科室查询当前在工作医生
     *
     * @param dept
     * @param hospital
     * @param level
     * @param key
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/doctors_list")
    @ResponseBody
    public String findWorkingDoctorByDept(@RequestParam(required = false) String dept,
                                          @RequestParam(required = false) String hospital,
                                          @RequestParam(required = false, defaultValue = "") String level,
                                          @RequestParam(required = false, defaultValue = "") String key,
                                          @RequestParam(required = false, defaultValue = "-1") int page,
                                          @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (page > 1) {
                page = page - 1;
            }
            JSONArray doctors = doctorInfoService.findWorkingDoctorListByDept(dept, hospital, level, key, page, pagesize);
            return write(200, "查询成功", "data", doctors);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据机构查找科室
     *
@ -1472,9 +1566,23 @@ public class DoctorController extends BaseController {
    @ResponseBody
    public String updateTeamHealthDoctors(String newDoctorCode,
                                          @RequestParam(required = false) String oldDoctorCode,
                                          String patients) {
                                          @RequestParam(required = false) String patients,
                                          @RequestParam(required = false) String isAll) {
        try {
            doctorInfoService.updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients);
            if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")) {
                int result = doctorInfoService.updateTeamHealthDoctorsAll(newDoctorCode, getUID());
                if (result == 1) {
                    return write(200, "分配健管师成功");
                } else if (result == 2) {
                    return write(200, "部分居民因没有服务团队分配失败");
                }
            } else {
                if (StringUtils.isEmpty(patients)) {
                    return error(-1, "居民不能为空");
                }
                doctorInfoService.updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients);
            }
            return write(200, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();

+ 74 - 3
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultController.java

@ -6,6 +6,7 @@ import java.util.Map;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.util.MessageType;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
@ -88,12 +89,21 @@ public class DoctorConsultController extends WeixinBaseController {
                json.put("consult", consult.getConsult());
                // 设置患者标识
                json.put("patient", consult.getPatient());
                // 设置患者姓名
                json.put("name", consult.getName());
                // 设置醫生标识
                json.put("doctor", consult.getDoctor());
                Doctor doctor=doctorService.findDoctorByCode(consult.getDoctor());
                // 设置醫生标识
                json.put("doctorName", doctor.getName());
                // 设置医生photo
                json.put("doctorPhoto", doctor.getPhoto());
                // 设置医生sex
                json.put("doctorSex", doctor.getSex());
                // 设置患者头像
                json.put("photo", consult.getPhoto());
                // 设置咨询标识
                json.put("title", consult.getSymptoms());
                // 设置患者姓名
                json.put("name", consult.getName());
                // 设置患者年龄
                json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
                // 设置评价内容
@ -552,5 +562,66 @@ public class DoctorConsultController extends WeixinBaseController {
            return error(-1, "回复失败!");
        }
    }
    /**
     * 名医咨询添加接口
     * @param when 发病时间
     * @param symptoms 主要症状
     * @param images 图片URL地址,多图以逗号分隔
     * @param voice 语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "famousAdd")
    @ResponseBody
    public String famousAdd(
            @RequestParam(required = false)String when,
            String symptoms,
            @RequestParam(required = false) String doctorCode,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String voice) {
        try {
            //判断医生是否是在工作时间
            JSONObject jo=doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
            if(!jo.get("status").equals("1")){
                return error(-1, jo.get("msg").toString());
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
            }
            // 将临时图片拷贝到正式存储路径下
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
            if (StringUtils.isEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            //判断是否已经存在还没有关闭的名医咨询
//            if(consultTeamService.isExistFamousConsult(getUID())){
//                return error(-1, "已经存在名医咨询!");
//            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询
            consult.setType(7);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            consultTeamService.addFamousTeamConsult(consult, getUID(),"2");
            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
            return success("提交成功");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败!");
        }
    }
}

+ 759 - 656
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/discussion/DoctorDiscussionGroupController.java

@ -27,676 +27,779 @@ import com.yihu.wlyy.web.BaseController;
@RequestMapping(value = "/doctor/talkgroup", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-讨论组")
public class DoctorDiscussionGroupController extends BaseController {
	// 医生服务类
	@Autowired
	private DoctorService doctorService;
	@Autowired
	// 讨论组服务类
	private TalkGroupService talkGroupService;
    // 医生服务类
    @Autowired
	private PatientService patientService;
	/**
	 * 医生创建讨论组
	 * 
	 * @param name 讨论组名称
	 * @param type 讨论组类型
	 * @param talkDoctor 讨论组医生
	 * @param talkDoctorName 讨论组医生名称
	 * @param doctorType 成员医生类型
	 * @param patient 病人标识
	 * @param patientName 病人姓名
	 * @param patientInclude 病人是否加入讨论组
	 * @return
	 */
	@RequestMapping(value = "/create")
	@ResponseBody
	public String createTalkGroup(
			@RequestParam(required = true)String name,
			@RequestParam(required = true)int type,
			@RequestParam(required = true)String talkDoctor,
			@RequestParam(required = true)String talkDoctorName,
			@RequestParam(required = true)int doctorType,
			@RequestParam(required = false)String patient,
			@RequestParam(required = false)String patientName,
			@RequestParam(required = false)String patientInclude){
		try{
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			List<WlyyTalkGroupMember> members = new ArrayList<WlyyTalkGroupMember>();
			
			if(doctor != null){
				//讨论组建立
				WlyyTalkGroup talkGroup = new WlyyTalkGroup();
				
				if(StringUtils.isEmpty(name)){
					return error(-1,"请输入讨论组名称");
				}
				if(StringUtils.isEmpty(talkDoctor)){
					return error(-1,"请输入讨论组成员医生");
				}
				if(StringUtils.isEmpty(talkDoctorName)){
					return error(-1,"请输入讨论组成员医生姓名");
				}
				// 讨论组针对某一病人时
				if(type == 1){
					if(StringUtils.isEmpty(patient)){
						return error(-1,"请输入患者标识");
					}
					if(StringUtils.isEmpty(patientName)){
						return error(-1,"请输入患者姓名");
					}
					if(StringUtils.isEmpty(patientInclude)){
						return error(-1,"请输入患者是否加入讨论组");
					}
				}
				
				talkGroup.setCode(talkGroupService.getCode());
				talkGroup.setName(name);
				talkGroup.setType(type);
				talkGroup.setCreator(doctor.getCode());
				talkGroup.setCreatorName(doctor.getName());
				talkGroup.setHospitalCode(doctor.getHospital());
				talkGroup.setHospitalName(doctor.getHosptialName());
				talkGroup.setPatient(patient);
				talkGroup.setPatientName(patientName);
				talkGroup.setCzrq(new Date());
				
				//病人加入讨论组
				if(!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")){
					WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();
					
					patientMember.setMemberCode(patient);
					patientMember.setMemberName(patientName);
					patientMember.setGroupCode(talkGroup.getCode());
					patientMember.setGroupName(name);
					patientMember.setType(4);
					patientMember.setStatus(1);
					patientMember.setCzrq(new Date());
					
					members.add(patientMember);
				}
				
				//当前医生加入讨论组
				WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();
				
				doctorMember.setMemberCode(doctor.getCode());
				doctorMember.setMemberName(doctor.getName());
				doctorMember.setGroupCode(talkGroup.getCode());
				doctorMember.setGroupName(name);
				doctorMember.setType(doctor.getLevel());
				doctorMember.setStatus(1);
				doctorMember.setCzrq(new Date());	
				members.add(doctorMember);
				
				//指定的讨论组另一医生成员
				WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
				
				doctorTalkMember.setMemberCode(talkDoctor);
				doctorTalkMember.setMemberName(talkDoctorName);
				doctorTalkMember.setGroupCode(talkGroup.getCode());
				doctorTalkMember.setGroupName(name);
				doctorTalkMember.setType(doctorType);
				doctorTalkMember.setStatus(1);
				doctorTalkMember.setCzrq(new Date());	
				members.add(doctorTalkMember);
				
				talkGroupService.saveTalkGroup(talkGroup, members);
				
				JSONObject jsonObject = new JSONObject(talkGroup);
    private DoctorService doctorService;
    @Autowired
    // 讨论组服务类
    private TalkGroupService talkGroupService;
    @Autowired
    private PatientService patientService;
    /**
     * 医生创建讨论组
     *
     * @param name           讨论组名称
     * @param type           讨论组类型
     * @param talkDoctor     讨论组医生
     * @param talkDoctorName 讨论组医生名称
     * @param doctorType     成员医生类型
     * @param patient        病人标识
     * @param patientName    病人姓名
     * @param patientInclude 病人是否加入讨论组
     * @return
     */
    @RequestMapping(value = "/create",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String createTalkGroup(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) int type,
            @RequestParam(required = true) String talkDoctor,
            @RequestParam(required = true) String talkDoctorName,
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = false) String patient,
            @RequestParam(required = false) String patientName,
            @RequestParam(required = false) String patientInclude) {
        try {
            Doctor doctor = doctorService.findDoctorByCode(getUID());
            List<WlyyTalkGroupMember> members = new ArrayList<WlyyTalkGroupMember>();
            if (doctor != null) {
                //讨论组建立
                WlyyTalkGroup talkGroup = new WlyyTalkGroup();
                if (StringUtils.isEmpty(name)) {
                    return error(-1, "请输入讨论组名称");
                }
                if (StringUtils.isEmpty(talkDoctor)) {
                    return error(-1, "请输入讨论组成员医生");
                }
                if (StringUtils.isEmpty(talkDoctorName)) {
                    return error(-1, "请输入讨论组成员医生姓名");
                }
                // 讨论组针对某一病人时
                if (type == 1) {
                    if (StringUtils.isEmpty(patient)) {
                        return error(-1, "请输入患者标识");
                    }
                    if (StringUtils.isEmpty(patientName)) {
                        return error(-1, "请输入患者姓名");
                    }
                    if (StringUtils.isEmpty(patientInclude)) {
                        return error(-1, "请输入患者是否加入讨论组");
                    }
                }
                talkGroup.setCode(talkGroupService.getCode());
                talkGroup.setName(name);
                talkGroup.setType(type);
                talkGroup.setCreator(doctor.getCode());
                talkGroup.setCreatorName(doctor.getName());
                talkGroup.setHospitalCode(doctor.getHospital());
                talkGroup.setHospitalName(doctor.getHosptialName());
                talkGroup.setPatient(patient);
                talkGroup.setPatientName(patientName);
                talkGroup.setCzrq(new Date());
                //病人加入讨论组
                if (!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")) {
                    WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();
                    patientMember.setMemberCode(patient);
                    patientMember.setMemberName(patientName);
                    patientMember.setGroupCode(talkGroup.getCode());
                    patientMember.setGroupName(name);
                    patientMember.setType(4);
                    patientMember.setStatus(1);
                    patientMember.setCzrq(new Date());
                    members.add(patientMember);
                }
                //当前医生加入讨论组
                WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();
                doctorMember.setMemberCode(doctor.getCode());
                doctorMember.setMemberName(doctor.getName());
                doctorMember.setGroupCode(talkGroup.getCode());
                doctorMember.setGroupName(name);
                doctorMember.setType(doctor.getLevel());
                doctorMember.setStatus(1);
                doctorMember.setCzrq(new Date());
                members.add(doctorMember);
                //指定的讨论组另一医生成员
                WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
                doctorTalkMember.setMemberCode(talkDoctor);
                doctorTalkMember.setMemberName(talkDoctorName);
                doctorTalkMember.setGroupCode(talkGroup.getCode());
                doctorTalkMember.setGroupName(name);
                doctorTalkMember.setType(doctorType);
                doctorTalkMember.setStatus(1);
                doctorTalkMember.setCzrq(new Date());
                members.add(doctorTalkMember);
                talkGroupService.saveTalkGroup(talkGroup, members);
                JSONObject jsonObject = new JSONObject(talkGroup);
                JSONArray membersJson = new JSONArray();
				for(WlyyTalkGroupMember member : members){
					JSONObject memberJson = new JSONObject(member);
					if(member.getType() == 4){
						Patient p = patientService.findByCode(member.getMemberCode());
						if(p != null){
							memberJson.put("photo",p.getPhoto());
							memberJson.put("sex",p.getSex());
						}
					}else{
						Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
						if(d != null){
							memberJson.put("photo",d.getPhoto());
							memberJson.put("sex",d.getSex());
						}
					}
					membersJson.put(memberJson);
				}
				jsonObject.put("members", membersJson);
				
				return write(200, "创建讨论组成功!","data",jsonObject);
			}else{
				return error(-1, "创建讨论组失败!");
			}
		
		}catch(Exception e){
			return error(-1, "创建讨论组失败!");
		}
	}
	/**
	 * 创建讨论组
	 *
	 * @param name 讨论组名称
	 * @param type 讨论组类型
	 * @param members 讨论组成员 [{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
	 * @param patient 患者
	 * @param patientName 患者姓名
	 * @param patientInclude 患者是否加入
	 * @return
	 */
	@RequestMapping(value = "/create/members")
	@ResponseBody
	public String createTalkGroupMany(@RequestParam(required = true)String name,
									  @RequestParam(required = true)int type,
									  @RequestParam(required = true)String members,
									  @RequestParam(required = false)String patient,
									  @RequestParam(required = false)String patientName,
									  @RequestParam(required = false)String patientInclude){
		try{
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			List<WlyyTalkGroupMember> talkMembers = new ArrayList<WlyyTalkGroupMember>();
			if(doctor != null){
				//讨论组建立
				WlyyTalkGroup talkGroup = new WlyyTalkGroup();
				if(StringUtils.isEmpty(name)){
					return error(-1,"请输入讨论组名称");
				}
				if(StringUtils.isEmpty(members)){
					return error(-1,"讨论组成员不能为空");
				}
				// 讨论组针对某一病人时
				if(type == 1){
					if(StringUtils.isEmpty(patient)){
						return error(-1,"请输入患者标识");
					}
					if(StringUtils.isEmpty(patientName)){
						return error(-1,"请输入患者姓名");
					}
					if(StringUtils.isEmpty(patientInclude)){
						return error(-1,"请输入患者是否加入讨论组");
					}
				}
				talkGroup.setCode(talkGroupService.getCode());
				talkGroup.setName(name);
				talkGroup.setType(type);
				talkGroup.setCreator(doctor.getCode());
				talkGroup.setCreatorName(doctor.getName());
				talkGroup.setHospitalCode(doctor.getHospital());
				talkGroup.setHospitalName(doctor.getHosptialName());
				talkGroup.setPatient(patient);
				talkGroup.setPatientName(patientName);
				talkGroup.setCzrq(new Date());
				//病人加入讨论组
				if(!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")){
					WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();
					patientMember.setMemberCode(patient);
					patientMember.setMemberName(patientName);
					patientMember.setGroupCode(talkGroup.getCode());
					patientMember.setGroupName(name);
					patientMember.setType(4);
					patientMember.setStatus(1);
					patientMember.setCzrq(new Date());
					talkMembers.add(patientMember);
				}
				//当前医生加入讨论组
				WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();
				doctorMember.setMemberCode(doctor.getCode());
				doctorMember.setMemberName(doctor.getName());
				doctorMember.setGroupCode(talkGroup.getCode());
				doctorMember.setGroupName(name);
				doctorMember.setType(doctor.getLevel());
				doctorMember.setStatus(1);
				doctorMember.setCzrq(new Date());
				talkMembers.add(doctorMember);
				JSONArray membersJArray = new JSONArray(members);
				if(membersJArray != null){
					for(int i = 0; i < membersJArray.length(); i++){
						JSONObject object = membersJArray.getJSONObject(i);
						//指定的讨论组另一医生成员
						WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
						doctorTalkMember.setMemberCode(object.getString("doctor"));
						doctorTalkMember.setMemberName(object.getString("doctorName"));
						doctorTalkMember.setGroupCode(talkGroup.getCode());
						doctorTalkMember.setGroupName(name);
						doctorTalkMember.setType(object.getInt("doctorType"));
						doctorTalkMember.setStatus(1);
						doctorTalkMember.setCzrq(new Date());
						talkMembers.add(doctorTalkMember);
					}
				}
				talkGroupService.saveTalkGroup(talkGroup, talkMembers);
				JSONObject jsonObject = new JSONObject(talkGroup);
				JSONArray membersJson = new JSONArray();
				for(WlyyTalkGroupMember member : talkMembers){
					JSONObject memberJson = new JSONObject(member);
					if(member.getType() == 4){
						Patient p = patientService.findByCode(member.getMemberCode());
						if(p != null){
							memberJson.put("photo",p.getPhoto());
							memberJson.put("sex",p.getSex());
						}
					}else{
						Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
						if(d != null){
							memberJson.put("photo",d.getPhoto());
							memberJson.put("sex",d.getSex());
						}
					}
					membersJson.put(memberJson);
				}
				jsonObject.put("members", membersJson);
				return write(200, "创建讨论组成功!","data",jsonObject);
			}else{
				return error(-1, "创建讨论组失败!");
			}
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"创建讨论组失败");
		}
	}
	/**
	 * 添加讨论组成员
	 * 
	 * @param groupCode 讨论组标识
	 * @param groupName 讨论组名称
	 * @param doctor 添加医生
	 * @param doctorName 添加医生姓名
	 * @param doctorType 医生类型
	 * @return
	 */
	@RequestMapping(value = "addmember")
	@ResponseBody
	public String addTalkMember(
			@RequestParam(required = true)String groupCode,
			@RequestParam(required = true)String groupName,
			@RequestParam(required = true)String doctor,
			@RequestParam(required = true)String doctorName,int doctorType){
		try{
			WlyyTalkGroupMember member = new WlyyTalkGroupMember();
			
			member.setGroupCode(groupCode);
			member.setGroupName(groupName);
			member.setMemberCode(doctor);
			member.setMemberName(doctorName);
			member.setStatus(1);
			member.setCzrq(new Date());
			member.setType(doctorType);
			
			talkGroupService.saveTalkMember(member);
			JSONObject memberJson = new JSONObject(member);
			if(member.getType() == 4){
				Patient p = patientService.findByCode(member.getMemberCode());
				if(p != null){
					memberJson.put("photo",p.getPhoto());
					memberJson.put("sex",p.getSex());
				}
			}else{
				Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
				if(d != null){
					memberJson.put("photo",d.getPhoto());
					memberJson.put("sex",d.getSex());
				}
			}
			
			return write(200, "添加讨论组成员成功!","data",memberJson);
		}catch(Exception e){
			return error(-1, "添加讨论组成员失败!");
		}
	}
	/**
	 * 添加成员
	 *
	 * @param groupCode 分组code
	 * @param members 讨论组成员[{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
	 * @return
	 */
	@RequestMapping(value = "/addmembers")
	@ResponseBody
	public String addMembers(String groupCode,String groupName,String members){
		try{
			List<WlyyTalkGroupMember> talkMembers = new ArrayList<>();
			JSONArray membersJArray = new JSONArray(members);
			WlyyTalkGroup talkGroup = talkGroupService.findTalkGroup(groupCode);
			if(talkGroup == null){
				throw new Exception("讨论组不存在");
			}
			if(membersJArray != null){
				for(int i = 0; i < membersJArray.length(); i++){
					JSONObject object = membersJArray.getJSONObject(i);
					//指定的讨论组另一医生成员
					WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
					doctorTalkMember.setMemberCode(object.getString("doctor"));
					doctorTalkMember.setMemberName(object.getString("doctorName"));
					doctorTalkMember.setGroupCode(groupCode);
					doctorTalkMember.setGroupName(talkGroup.getName());
					doctorTalkMember.setType(object.getInt("doctorType"));
					doctorTalkMember.setStatus(1);
					doctorTalkMember.setCzrq(new Date());
					talkMembers.add(doctorTalkMember);
				}
			}
			talkGroupService.saveMembers(talkMembers);
			JSONObject jsonObject = new JSONObject(talkGroup);
			JSONArray membersJson = new JSONArray();
			for(WlyyTalkGroupMember member : talkMembers){
				JSONObject memberJson = new JSONObject(member);
				if(member.getType() == 4){
					Patient p = patientService.findByCode(member.getMemberCode());
					if(p != null){
						memberJson.put("photo",p.getPhoto());
						memberJson.put("sex",p.getSex());
					}
				}else{
					Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
					if(d != null){
						memberJson.put("photo",d.getPhoto());
						memberJson.put("sex",d.getSex());
					}
				}
				membersJson.put(memberJson);
			}
			jsonObject.put("members", membersJson);
			return write(200,"添加成员成功");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"添加成员失败!");
		}
	}
                for (WlyyTalkGroupMember member : members) {
                    JSONObject memberJson = new JSONObject(member);
                    if (member.getType() == 4) {
                        Patient p = patientService.findByCode(member.getMemberCode());
                        if (p != null) {
                            memberJson.put("photo", p.getPhoto());
                            memberJson.put("sex", p.getSex());
                        }
                    } else {
                        Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
                        if (d != null) {
                            memberJson.put("photo", d.getPhoto());
                            memberJson.put("sex", d.getSex());
                        }
                    }
                    membersJson.put(memberJson);
                }
                jsonObject.put("members", membersJson);
                return write(200, "创建讨论组成功!", "data", jsonObject);
            } else {
                return error(-1, "创建讨论组失败!");
            }
        } catch (Exception e) {
            return error(-1, "创建讨论组失败!");
        }
    }
    /**
     * 创建讨论组
     *
     * @param name           讨论组名称
     * @param type           讨论组类型
     * @param members        讨论组成员 [{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
     * @param patient        患者
     * @param patientName    患者姓名
     * @param patientInclude 患者是否加入
     * @return
     */
    @RequestMapping(value = "/create/members",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String createTalkGroupMany(@RequestParam(required = true) String name,
                                      @RequestParam(required = true) int type,
                                      @RequestParam(required = true) String members,
                                      @RequestParam(required = false) String patient,
                                      @RequestParam(required = false) String patientName,
                                      @RequestParam(required = false) String patientInclude) {
        try {
            Doctor doctor = doctorService.findDoctorByCode(getUID());
            List<WlyyTalkGroupMember> talkMembers = new ArrayList<WlyyTalkGroupMember>();
            if (doctor != null) {
                //讨论组建立
                WlyyTalkGroup talkGroup = new WlyyTalkGroup();
                if (StringUtils.isEmpty(name)) {
                    return error(-1, "请输入讨论组名称");
                }
                if (StringUtils.isEmpty(members)) {
                    return error(-1, "讨论组成员不能为空");
                }
                // 讨论组针对某一病人时
                if (type == 1) {
                    if (StringUtils.isEmpty(patient)) {
                        return error(-1, "请输入患者标识");
                    }
                    if (StringUtils.isEmpty(patientName)) {
                        return error(-1, "请输入患者姓名");
                    }
                    if (StringUtils.isEmpty(patientInclude)) {
                        return error(-1, "请输入患者是否加入讨论组");
                    }
                }
                talkGroup.setCode(talkGroupService.getCode());
                talkGroup.setName(name);
                talkGroup.setType(type);
                talkGroup.setCreator(doctor.getCode());
                talkGroup.setCreatorName(doctor.getName());
                talkGroup.setHospitalCode(doctor.getHospital());
                talkGroup.setHospitalName(doctor.getHosptialName());
                talkGroup.setPatient(patient);
                talkGroup.setPatientName(patientName);
                talkGroup.setCzrq(new Date());
                //病人加入讨论组
                if (!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")) {
                    WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();
                    patientMember.setMemberCode(patient);
                    patientMember.setMemberName(patientName);
                    patientMember.setGroupCode(talkGroup.getCode());
                    patientMember.setGroupName(name);
                    patientMember.setType(4);
                    patientMember.setStatus(1);
                    patientMember.setCzrq(new Date());
                    talkMembers.add(patientMember);
                }
                //当前医生加入讨论组
                WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();
                doctorMember.setMemberCode(doctor.getCode());
                doctorMember.setMemberName(doctor.getName());
                doctorMember.setGroupCode(talkGroup.getCode());
                doctorMember.setGroupName(name);
                doctorMember.setType(doctor.getLevel());
                doctorMember.setStatus(1);
                doctorMember.setCzrq(new Date());
                talkMembers.add(doctorMember);
                JSONArray membersJArray = new JSONArray(members);
                if (membersJArray != null) {
                    for (int i = 0; i < membersJArray.length(); i++) {
                        JSONObject object = membersJArray.getJSONObject(i);
                        //指定的讨论组另一医生成员
                        WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
                        doctorTalkMember.setMemberCode(object.getString("doctor"));
                        doctorTalkMember.setMemberName(object.getString("doctorName"));
                        doctorTalkMember.setGroupCode(talkGroup.getCode());
                        doctorTalkMember.setGroupName(name);
                        doctorTalkMember.setType(object.getInt("doctorType"));
                        doctorTalkMember.setStatus(1);
                        doctorTalkMember.setCzrq(new Date());
                        talkMembers.add(doctorTalkMember);
                    }
                }
                talkGroupService.saveTalkGroup(talkGroup, talkMembers);
                JSONObject jsonObject = new JSONObject(talkGroup);
                JSONArray membersJson = new JSONArray();
                for (WlyyTalkGroupMember member : talkMembers) {
                    JSONObject memberJson = new JSONObject(member);
                    if (member.getType() == 4) {
                        Patient p = patientService.findByCode(member.getMemberCode());
                        if (p != null) {
                            memberJson.put("photo", p.getPhoto());
                            memberJson.put("sex", p.getSex());
                        }
                    } else {
                        Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
                        if (d != null) {
                            memberJson.put("photo", d.getPhoto());
                            memberJson.put("sex", d.getSex());
                        }
                    }
                    membersJson.put(memberJson);
                }
                jsonObject.put("members", membersJson);
                return write(200, "创建讨论组成功!", "data", jsonObject);
            } else {
                return error(-1, "创建讨论组失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "创建讨论组失败");
        }
    }
    /**
     * 添加讨论组成员
     *
     * @param groupCode  讨论组标识
     * @param groupName  讨论组名称
     * @param doctor     添加医生
     * @param doctorName 添加医生姓名
     * @param doctorType 医生类型
     * @return
     */
    @RequestMapping(value = "addmember",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String addTalkMember(
            @RequestParam(required = true) String groupCode,
            @RequestParam(required = true) String groupName,
            @RequestParam(required = true) String doctor,
            @RequestParam(required = true) String doctorName, int doctorType) {
        try {
            if (talkGroupService.isMemberExists(groupCode, groupName)) {
                return error(-2, "成员已在该讨论组");
            }
            WlyyTalkGroupMember member = new WlyyTalkGroupMember();
            member.setGroupCode(groupCode);
            member.setGroupName(groupName);
            member.setMemberCode(doctor);
            member.setMemberName(doctorName);
            member.setStatus(1);
            member.setCzrq(new Date());
            member.setType(doctorType);
            talkGroupService.saveTalkMember(member);
            JSONObject memberJson = new JSONObject(member);
            if (member.getType() == 4) {
                Patient p = patientService.findByCode(member.getMemberCode());
                if (p != null) {
                    memberJson.put("photo", p.getPhoto());
                    memberJson.put("sex", p.getSex());
                }
            } else {
                Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
                if (d != null) {
                    memberJson.put("photo", d.getPhoto());
                    memberJson.put("sex", d.getSex());
                }
            }
            return write(200, "添加讨论组成员成功!", "data", memberJson);
        } catch (Exception e) {
            return error(-1, "添加讨论组成员失败!");
        }
    }
    /**
     * 添加成员
     *
     * @param groupCode 分组code
     * @param members   讨论组成员[{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
     * @return
     */
    @RequestMapping(value = "/addmembers",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String addMembers(String groupCode, String groupName, String members) {
        try {
            List<WlyyTalkGroupMember> talkMembers = new ArrayList<>();
            JSONArray membersJArray = new JSONArray(members);
            WlyyTalkGroup talkGroup = talkGroupService.findTalkGroup(groupCode);
            if (talkGroup == null) {
                throw new Exception("讨论组不存在");
            }
            if (membersJArray != null) {
                for (int i = 0; i < membersJArray.length(); i++) {
                    JSONObject object = membersJArray.getJSONObject(i);
                    if (talkGroupService.isMemberExists(groupCode, object.getString("doctor"))) {
                        return error(-2, "添加失败,有成员已在该讨论组");
                    }
                    //指定的讨论组另一医生成员
                    WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
                    doctorTalkMember.setMemberCode(object.getString("doctor"));
                    doctorTalkMember.setMemberName(object.getString("doctorName"));
                    doctorTalkMember.setGroupCode(groupCode);
                    doctorTalkMember.setGroupName(talkGroup.getName());
                    doctorTalkMember.setType(object.getInt("doctorType"));
                    doctorTalkMember.setStatus(1);
                    doctorTalkMember.setCzrq(new Date());
                    talkMembers.add(doctorTalkMember);
                }
            }
            talkGroupService.saveMembers(talkMembers);
            JSONObject jsonObject = new JSONObject(talkGroup);
            JSONArray membersJson = new JSONArray();
            for (WlyyTalkGroupMember member : talkMembers) {
                JSONObject memberJson = new JSONObject(member);
                if (member.getType() == 4) {
                    Patient p = patientService.findByCode(member.getMemberCode());
                    if (p != null) {
                        memberJson.put("photo", p.getPhoto());
                        memberJson.put("sex", p.getSex());
                    }
                } else {
                    Doctor d = doctorService.findDoctorByCode(member.getMemberCode());
                    if (d != null) {
                        memberJson.put("photo", d.getPhoto());
                        memberJson.put("sex", d.getSex());
                    }
                }
                membersJson.put(memberJson);
            }
            jsonObject.put("members", membersJson);
            return write(200, "添加成员成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "添加成员失败!");
        }
    }
    /**
     * 移除讨论组成员
     * 
     * @param groupCode 讨论组标识
     *
     * @param groupCode  讨论组标识
     * @param memberCode 讨论组成员标识
     * @return
     */
	@RequestMapping(value = "removemember")
	@ResponseBody
	public String removeTalkMember(
			@RequestParam(required = true)String groupCode,
			@RequestParam(required = true)String memberCode){
		try{
			talkGroupService.deleteTalkMember(groupCode, memberCode);
			return write(200, "移除成员成功!");
		}catch(Exception e){
			return error(-1, "移除讨论组成员失败!");
		}
	}
	/**
	 * 移除成员
	 *
	 * @param groupCode
	 * @param members
	 * @return
	 */
	@RequestMapping(value = "/removemembers")
	@ResponseBody
	public String removeMembers(String groupCode,String members){
		try{
			String[] memberArray = members.split(",");
			for(String member : memberArray){
				talkGroupService.deleteTalkMember(groupCode, member);
			}
			return write(200,"移除成员成功");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"移除成员失败!");
		}
	}
	/**
	 * 获取医生讨论组
	 * 
	 * @return
	 */
	@RequestMapping(value = "mytalkgroups")
	@ResponseBody
	public String getMyTalkGroup(
			@RequestParam(required = false)String doctorName,
			@RequestParam(required = false)String groupType){
		try{
			JSONArray jsonArray = new JSONArray();
			Set<String> typeSet = new HashSet<>();
			if(!StringUtils.isEmpty(groupType)) {
				for (String type : groupType.split(",")) {
					typeSet.add(type);
				}
			}
			List<WlyyTalkGroup> groups = new ArrayList<>();
			if(!StringUtils.isEmpty(doctorName)){
				groups = talkGroupService.searchTalkGroupsByDoctorName(getUID(),doctorName);
			}
			else{
				groups = talkGroupService.findDoctorTalkGroups(getUID());
			}
			if(typeSet.size() > 0 && groups != null){
				for(WlyyTalkGroup talk : groups){
					if(!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))){
						jsonArray.put(new JSONObject(talk));
					}
				}
			}else if(groups != null){
				jsonArray = new JSONArray(groups);
			}
			return write(200, "获取医生讨论组成功!","data",jsonArray);
		}catch(Exception ex){
			return error(-1, "获取医生讨论组列表失败!");
		}
	}
	/**
	 * 查询讨论组签约量
	 *
	 * @param groups
	 * @return
	 */
	@RequestMapping(value = "/group_sign")
	@ResponseBody
	public String getMyTalkGroupSign(String groups){
		try{
			List<Map<String,Object>> data = talkGroupService.getTalkGroupsSing(groups.split(","));
			return write(200,"查询成功","data",new JSONArray(data));
		}catch (Exception e){
			return error(-1,"查询失败");
		}
	}
	/**
	 * 获取讨论组成员列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "groupmembers")
	@ResponseBody
	public String getTalkGroupMembers(@RequestParam(required = true)String groupCode){
		try{
			JSONArray result = new JSONArray();
			List<WlyyTalkGroupMember> groupMembers = talkGroupService.findTalkGroupMembers(groupCode);
			if(groupMembers == null){
				groupMembers = new ArrayList<>();
			}
			for(WlyyTalkGroupMember member : groupMembers){
				JSONObject memberJson = new JSONObject(member);
				if(member.getType() == 4){
					Patient p = patientService.findByCode(member.getMemberCode());
					if(p != null){
						memberJson.put("photo",p.getPhoto());
						memberJson.put("sex",p.getSex());
					}
				}else{
    @RequestMapping(value = "removemember",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String removeTalkMember(
            @RequestParam(required = true) String groupCode,
            @RequestParam(required = true) String memberCode) {
        try {
            talkGroupService.deleteTalkMember(groupCode, memberCode);
            return write(200, "移除成员成功!");
        } catch (Exception e) {
            return error(-1, "移除讨论组成员失败!");
        }
    }
    /**
     * 移除成员
     *
     * @param groupCode
     * @param members
     * @return
     */
    @RequestMapping(value = "/removemembers",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String removeMembers(String groupCode, String members) {
        try {
            String[] memberArray = members.split(",");
            for (String member : memberArray) {
                talkGroupService.deleteTalkMember(groupCode, member);
            }
            return write(200, "移除成员成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "移除成员失败!");
        }
    }
    /**
     * 获取医生讨论组
     *
     * @return
     */
    @RequestMapping(value = "mytalkgroups",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroup(
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false) String groupType) {
        try {
            JSONArray jsonArray = new JSONArray();
            Set<String> typeSet = new HashSet<>();
            if (!StringUtils.isEmpty(groupType)) {
                for (String type : groupType.split(",")) {
                    typeSet.add(type);
                }
            }
            List<WlyyTalkGroup> groups = new ArrayList<>();
            if (!StringUtils.isEmpty(doctorName)) {
                groups = talkGroupService.searchTalkGroupsByDoctorName(getUID(), doctorName);
            } else {
                groups = talkGroupService.findDoctorTalkGroups(getUID());
            }
            if (typeSet.size() > 0 && groups != null) {
                for (WlyyTalkGroup talk : groups) {
                    if (!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))) {
                        jsonArray.put(new JSONObject(talk));
                    }
                }
            } else if (groups != null) {
                jsonArray = new JSONArray(groups);
            }
            return write(200, "获取医生讨论组成功!", "data", jsonArray);
        } catch (Exception ex) {
            return error(-1, "获取医生讨论组列表失败!");
        }
    }
    /**
     * 查询讨论组签约量
     *
     * @param groups
     * @return
     */
    @RequestMapping(value = "/group_sign",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroupSign(String groups) {
        try {
            List<Map<String, Object>> data = talkGroupService.getTalkGroupsSing(groups.split(","));
            return write(200, "查询成功", "data", new JSONArray(data));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取讨论组成员列表
     *
     * @return
     */
    @RequestMapping(value = "groupmembers",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupMembers(@RequestParam(required = true) String groupCode) {
        try {
            JSONArray result = new JSONArray();
            List<WlyyTalkGroupMember> groupMembers = talkGroupService.findTalkGroupMembers(groupCode);
            if (groupMembers == null) {
                groupMembers = new ArrayList<>();
            }
            for (WlyyTalkGroupMember member : groupMembers) {
                JSONObject memberJson = new JSONObject(member);
                if (member.getType() == 4) {
                    Patient p = patientService.findByCode(member.getMemberCode());
                    if (p != null) {
                        memberJson.put("photo", p.getPhoto());
                        memberJson.put("sex", p.getSex());
                    }
                } else {
                    Doctor doctor = doctorService.findDoctorByCode(member.getMemberCode());
					if(doctor != null){
						memberJson.put("photo",doctor.getPhoto());
						memberJson.put("sex",doctor.getSex());
					}
				}
				result.put(memberJson);
			}
			
			return write(200, "获取讨论组成员列表成功!","data",result);
		}catch(Exception ex){
			return error(-1, "获取讨论组成员列表失败!");
		}
	}
	/**
	 * 获取医生针对某个患者讨论组历史记录
	 * 
	 * @param patient
	 * @return
	 */
	@RequestMapping(value = "histories")
	@ResponseBody
    public String getTalkGroupHistory(@RequestParam(required = true)String patient){
    	try{
    		JSONArray groups = talkGroupService.getTalkGroupHistories(getUID(),patient);
    		return write(200, "获取讨论组历史记录成功!","data",groups);
    	}catch(Exception e){
    		return error(-1, "获取讨论组历史记录失败!");
    	}
                    if (doctor != null) {
                        memberJson.put("photo", doctor.getPhoto());
                        memberJson.put("sex", doctor.getSex());
                    }
                }
                result.put(memberJson);
            }
            return write(200, "获取讨论组成员列表成功!", "data", result);
        } catch (Exception ex) {
            return error(-1, "获取讨论组成员列表失败!");
        }
    }
	/**
	 * 查找与当前医生相关成员的讨论组
	 *
	 * @param member
	 * @return
    /**
     * 获取医生针对某个患者讨论组历史记录
     *
     * @param patient
     * @return
     */
	@RequestMapping(value = "related")
	@ResponseBody
    public String getTalkGroupRelated(@RequestParam(required = true)String member,@RequestParam(required = false)String groupType){
    	try{
			JSONArray jsonArray = new JSONArray();
			Set<String> typeSet = new HashSet<>();
			if(!StringUtils.isEmpty(groupType)) {
				for (String type : groupType.split(",")) {
					typeSet.add(type);
				}
			}
			List<WlyyTalkGroup> groups = talkGroupService.getTalkGroupRelated(getUID(),member);
			if(typeSet.size() > 0 && groups != null){
				for(WlyyTalkGroup talk : groups){
					if(!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))){
						jsonArray.put(new JSONObject(talk));
					}
				}
			}else if(groups != null){
				jsonArray.put(new JSONArray(groups));
			}
    		return write(200,"查询成功!","data",jsonArray);
		}catch (Exception e){
			return error(-1,"查询失败!");
		}
	}
	/**
	 * 查询医生讨论组数量
	 *
	 * @return
	 */
	@RequestMapping(value = "count")
	@ResponseBody
	public String getMyTalkGroupCount(){
		try{
			long  count = talkGroupService.getDoctorTalkGroupCount(getUID());
			return write(200,"查询成功!","data",count);
		}catch (Exception e){
			return error(-1,"查询失败!");
		}
	}
	/**
	 * 获取医生一对一聊天
	 *
	 * @param doctorName
	 * @return
	 */
	@RequestMapping(value = "/one_to_one_im")
	@ResponseBody
	public String getOneToOneIm(@RequestParam(required = false) String doctorName
			,@RequestParam(required = false) Integer page
			,@RequestParam(required = false) Integer pagesize){
		try{
			JSONArray result = talkGroupService.getOneToOneIm(getUID(),doctorName);
			if(page != null && pagesize != null){
				int from = (page - 1)*pagesize;
				int end = from + pagesize;
				JSONArray pageResult = new JSONArray();
				if(result != null){
					for(int i = from; i < result.length(); i++){
						if(i < end){
							pageResult.put(result.getJSONObject(i));
						}
					}
				}
				return write(200,"查询成功","data",pageResult);
			}else{
				return write(200,"查询成功","data",result);
			}
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败");
		}
	}
    @RequestMapping(value = "histories",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupHistory(@RequestParam(required = true) String patient) {
        try {
            JSONArray groups = talkGroupService.getTalkGroupHistories(getUID(), patient);
            return write(200, "获取讨论组历史记录成功!", "data", groups);
        } catch (Exception e) {
            return error(-1, "获取讨论组历史记录失败!");
        }
    }
    /**
     * 查找与当前医生相关成员的讨论组
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "related",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupRelated(@RequestParam(required = true) String member, @RequestParam(required = false) String groupType) {
        try {
            JSONArray jsonArray = new JSONArray();
            Set<String> typeSet = new HashSet<>();
            if (!StringUtils.isEmpty(groupType)) {
                for (String type : groupType.split(",")) {
                    typeSet.add(type);
                }
            }
            List<WlyyTalkGroup> groups = talkGroupService.getTalkGroupRelated(getUID(), member);
            if (typeSet.size() > 0 && groups != null) {
                for (WlyyTalkGroup talk : groups) {
                    if (!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))) {
                        jsonArray.put(new JSONObject(talk));
                    }
                }
            } else if (groups != null) {
                jsonArray.put(new JSONArray(groups));
            }
            return write(200, "查询成功!", "data", jsonArray);
        } catch (Exception e) {
            return error(-1, "查询失败!");
        }
    }
    /**
     * 查询医生讨论组数量
     *
     * @return
     */
    @RequestMapping(value = "count",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroupCount() {
        try {
            long count = talkGroupService.getDoctorTalkGroupCount(getUID());
            return write(200, "查询成功!", "data", count);
        } catch (Exception e) {
            return error(-1, "查询失败!");
        }
    }
    /**
     * 获取医生一对一聊天
     *
     * @param doctorName
     * @return
     */
    @RequestMapping(value = "/one_to_one_im",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getOneToOneIm(@RequestParam(required = false) String doctorName
            , @RequestParam(required = false) Integer page
            , @RequestParam(required = false) Integer pagesize) {
        try {
            JSONArray result = talkGroupService.getOneToOneIm(getUID(), doctorName);
            if (page != null && pagesize != null) {
                int from = (page - 1) * pagesize;
                int end = from + pagesize;
                JSONArray pageResult = new JSONArray();
                if (result != null) {
                    for (int i = from; i < result.length(); i++) {
                        if (i < end) {
                            pageResult.put(result.getJSONObject(i));
                        }
                    }
                }
                return write(200, "查询成功", "data", pageResult);
            } else {
                return write(200, "查询成功", "data", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 医生转发对象搜索
     *
     * @param filter 搜索字段
     * @return
     */
    @RequestMapping(value = "/doctor_im_search",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String imSearch(@RequestParam(required = true) String filter) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
            }
            JSONObject result = talkGroupService.searchImDoctor(getUID(), filter);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询医生与居民、医生聊天列表
     *
     * @param type 类型: 1居民  2医生
     * @return
     */
    @RequestMapping(value = "/im_list",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getImList(@RequestParam(required = true) int type,
                            @RequestParam(required = true) int page,
                            @RequestParam(required = true) int pagesize) {
        try {
            if (type != 1 && type != 2) {
                return error(-1, "类型错误");
            }
            page = page > 0 ? page - 1 : 0;
            JSONObject result = talkGroupService.getImList(getUID(), type, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询医生最近的联系人
     *
     * @param type 类型: 1居民  2医生
     * @return
     */
    @RequestMapping(value = "/recent_im_list" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getRecentImList(@RequestParam(required = true) int type) {
        try {
            if (type != 1 && type != 2) {
                return error(-1, "类型错误");
            }
            JSONObject result = talkGroupService.getRecentImList(getUID(), type);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 搜索IM
     *
     * @param filter     搜索条件
     * @param type       类型  1:居民 2:医生
     * @param searchType 搜索类型 1:居民 2:居民聊天记录 3:医生 4:求助 5:医生聊天记录
     * @param page       第几页
     * @param pagesize   页大小
     * @return
     */
    @RequestMapping(value = "/search_im", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String searchIm(@RequestParam(required = true) String filter,
                           @RequestParam(required = true) int type,
                           @RequestParam(required = false, defaultValue = "-1") int searchType,
                           @RequestParam(required = true) int page,
                           @RequestParam(required = true) int pagesize) {
        try {
            page = page > 0 ? page - 1 : 0;
            JSONObject result = talkGroupService.searchIm(getUID(), filter,
                    type, searchType, page, pagesize);
            return write(200, "搜索成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "搜索失败");
        }
    }
}

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

@ -1,27 +1,28 @@
package com.yihu.wlyy.web.doctor.health;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import com.yihu.wlyy.entity.education.*;
import com.yihu.wlyy.service.app.health.*;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.TextExtractingVisitor;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
@ -42,7 +43,20 @@ public class DoctorHealthEduArticleController extends BaseController {
	private HealthEduArticleService healthEduArticleService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
	@Autowired
	private SignPatientLabelInfoService signPatientLabelInfoService;
	@Autowired
	private HealthEduArticlePatientService healthEduArticlePatientService;
	@Autowired
	private HealthEduArticleDoctorService healthEduArticleDoctorService;
	@Autowired
	private HealthEduArticleLabelService healthEduArticleLabelService;
	/**
	 * 查询
	 * @param pagesize 分页大小
@ -50,24 +64,37 @@ public class DoctorHealthEduArticleController extends BaseController {
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(long id, int pagesize) {
	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) {
		try {
			Page<HealthEduArticle> list = healthEduArticleService.findAll(id, pagesize);
			List<Map<String, Object>> list = healthEduArticleService.findAll(page, pagesize,filter,getUID(),patient);
			JSONArray jsonArray = new JSONArray();
			if (list != null) {
				for (HealthEduArticle article : list) {
				for (Map<String, Object> map : list) {
					JSONObject json = new JSONObject();
					json.put("id", article.getId());
					json.put("id", map.get("id"));
					// 文章标识
					json.put("code", article.getCode());
					json.put("code", map.get("code"));
					// 文章标题
					json.put("title", article.getTitle());
					json.put("title", map.get("title"));
					// 文章查看URL
					json.put("url", article.getUrl());
					json.put("url", map.get("url"));
					// 文章简介
					json.put("content", article.getContent());
					json.put("content", parsrHtml(map.get("content").toString()));
					// 添加日期
					json.put("czrq", DateUtil.dateToStrLong(article.getCzrq()));
					json.put("czrq", DateUtil.dateToStrLong((Date)map.get("czrq")));
					json.put("keyword", map.get("keyword")==null?"":map.get("keyword"));
					json.put("send", map.get("send"));
					//阅读量
					json.put("readAmount", map.get("readAmount"));
					//收藏量
					json.put("collectionAmount", map.get("collectionAmount"));
					//转发量
					json.put("repeatAmount", map.get("repeatAmount"));
					json.put("collection",map.get("collection"));
					jsonArray.put(json);
				}
			}
@ -78,36 +105,166 @@ public class DoctorHealthEduArticleController extends BaseController {
		}
	}
	/**
	 * 查询医生收藏列表
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@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) {
		try {
			List<Map<String, Object>> list = healthEduArticleDoctorService.list(page, pagesize,filter,getUID(),patient);
			JSONArray jsonArray = new JSONArray();
			for(Map<String, Object> map:list){
				JSONObject json = new JSONObject();
				json.put("id", map.get("id"));
				// 文章标识
				json.put("code", map.get("article"));
				// 文章标题
				json.put("title", map.get("title"));
				// 文章查看URL
				json.put("url", map.get("url"));
				// 文章简介
				json.put("content", parsrHtml(map.get("content").toString()));
				// 添加日期
				json.put("czrq", DateUtil.dateToStrLong((Date)map.get("czrq")));
				json.put("keyword", map.get("keyword"));
				json.put("send", map.get("send"));
				//阅读量
				json.put("readAmount", map.get("readAmount"));
				//收藏量
				json.put("collectionAmount", map.get("collectionAmount"));
				//转发量
				json.put("repeatAmount", map.get("repeatAmount"));
				//是否收藏(医生收藏的列表肯定是收藏的无需额外校验)
				json.put("collection",1);
				jsonArray.put(json);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询标签列表
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@RequestMapping(value = "listLabel")
	@ResponseBody
	public String listLabel(@RequestParam(value = "page",required = true)int page, @RequestParam(value = "pagesize",required = true)int pagesize,@RequestParam(value = "type",required = false,defaultValue = "0")int type) {
		try {
			Page<HealthEduArticleLabel> list = healthEduArticleLabelService.findAll(page,pagesize,type,getUID());
			return write(200, "查询成功", "list", list);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询文章列表
	 * @param code 数据文章唯一标示code
	 * @return 列表
	 */
	@RequestMapping(value = "article")
	@ResponseBody
	public String article(@RequestParam(value = "code",required = true) String code) {
		try {
			//获取单条文章记录
			HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(code);
			int isRead  = healthEduArticleOpHistoryService.countByUserStatus(getUID(), HealthEduArticleOpHistory.READ_STATUS);
			//插入文章读取状态第一次阅读记录浏览数量
			if(isRead==0){
				//更新浏览量
				healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS,healthEduArticle.getCode(),healthEduArticle.getTitle(),getUID());
			}
			JSONObject json = new JSONObject();
			json.put("id", healthEduArticle.getId());
			// 文章标识
			json.put("code", healthEduArticle.getCode());
			// 文章标题
			json.put("title", healthEduArticle.getTitle());
			json.put("url", healthEduArticle.getUrl()==null?"":healthEduArticle.getUrl());
			// 文章内容
			json.put("content", healthEduArticle.getContent());
			// 添加日期
			json.put("czrq", DateUtil.dateToStrLong(healthEduArticle.getCzrq()));
			int readAmount = healthEduArticleOpHistoryService.countReadAmount(code);
			json.put("readAmount",readAmount);
			HealthEduArticleDoctor healthEduArticleDoctor = healthEduArticleDoctorService.findByArticle(healthEduArticle.getCode(), getUID());
			if(healthEduArticleDoctor==null){
				json.put("collection",0);
			}else{
				json.put("collection",1);
			}
			return write(200, "查询成功", "data", json);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 发送文章给患者
	 * @param article 文章标识,多个以逗号分隔
	 * @param code 文章标识,多个以逗号分隔
	 * @param patient 患者标识,多个以逗号分隔
	 * @param  group 所选群组,多个用逗号分隔
	 * @return
	 */
	@RequestMapping(value = "send")
	@ResponseBody
	public String send(String article, String patient) {
	public String send(@RequestParam(value = "code")String code,
					   @RequestParam(value = "patient",required = false)String patient,
					   @RequestParam(value = "group",required = false,defaultValue = "")String group,
					   @RequestParam(value = "labelType",required = false)String labelType,
					   @RequestParam(value = "teamCode",required = false)long teamCode) {
		try {
			List<HealthEduArticlePatient> list = new ArrayList<HealthEduArticlePatient>();
			if (StringUtils.isEmpty(article)) {
			if (StringUtils.isEmpty(code)) {
				return error(-1, "请至少选择一篇文章!");
			}
			if (StringUtils.isEmpty(patient)) {
			if (StringUtils.isEmpty(patient)&&StringUtils.isEmpty(group)) {
				return error(-1, "请至少选择一个患者!");
			}
			String[] articles = article.split(",");
			String[] articles = code.split(",");
			String[] patients = patient.split(",");
			String[] groups = group.split(",");
			if (articles.length == 0) {
				return error(-1, "请至少选择一篇文章!");
			}
			if (patients.length == 0) {
			if (patients.length == 0&&groups.length==0) {
				return error(-1, "请至少选择一个患者!");
			}
			Map<String, HealthEduArticle> maps = new HashMap<String, HealthEduArticle>();
			Set<String> patientSet = new HashSet<>();
			if(StringUtils.isNotBlank(group)&&groups.length>0){
				//递归患者数据
				for(String g :groups){
					getPatientByGroup(g,labelType,teamCode,patientSet,0,100);
				}
			}
			//去重操作
			for (String p : patients) {
				if(StringUtils.isNotBlank(p)){
					patientSet.add(p);
				}
			}
			if(patientSet.size()==0){
				return error(-1, "请至少选择一个患者!");
			}
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			JSONArray messages = new JSONArray();
			for (String p : patients) {
			for (String p : patientSet) {
				for (String a : articles) {
					// 查询文章信息
					HealthEduArticle temp = maps.get(a);
@ -116,6 +273,7 @@ public class DoctorHealthEduArticleController extends BaseController {
						// 添加到缓存
						maps.put(a, temp);
					}
					HealthEduArticlePatient heap = new HealthEduArticlePatient();
					// 设置文章标识
					heap.setArticle(a);
@ -159,5 +317,73 @@ public class DoctorHealthEduArticleController extends BaseController {
			return error(-1, "发送失败!");
		}
	}
	private void getPatientByGroup(String labelCode, String labelType, Long teamCode,Set<String> patientSet,int page,int pagesize) throws Exception{
		JSONArray result = signPatientLabelInfoService.getPatientByLabel(getUID(), labelCode, labelType, teamCode, page, pagesize);
		for(Object o : result){
			JSONObject json  = (JSONObject)o;
			String patient  = (String)json.get("code");
			patientSet.add(patient);
		}
		if(result.length()==100){
			getPatientByGroup(labelCode,labelType,teamCode,patientSet,page+1,pagesize);
		}
	}
	/**
	 * 文章收藏
	 * @param article 文章CODE
	 * @return
	 */
	@RequestMapping(value = "collectionArticle")
	@ResponseBody
	public String collectionArticle(@RequestParam(value = "article",required = true)String article){
		HealthEduArticleDoctor healthEduArticleDoctor = healthEduArticleDoctorService.findByArticle(article,getUID());
		if(healthEduArticleDoctor!=null){
			return error(-1, "收藏失败,该文章已经收藏!");
		}
		HealthEduArticle healthEduArticle =	healthEduArticleService.findArticleByCode(article);
		healthEduArticleDoctor = new HealthEduArticleDoctor();
		try{
			BeanUtils.copyProperties(healthEduArticle,healthEduArticleDoctor);
			healthEduArticleDoctor.setDoctor(getUID());
			healthEduArticleDoctor.setArticle(healthEduArticle.getCode());
			healthEduArticleDoctorService.save(healthEduArticleDoctor);
			//更新收藏量
			healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.COLLECTION_STATUS,healthEduArticle.getCode(),healthEduArticle.getTitle(),getUID());
			return success("收藏成功!");
		}catch (Exception e){
			error(e);
			return error(-1, "收藏失败!");
		}
	}
	/**
	 * 文章收藏
	 * @param article 文章CODE
	 * @return
	 */
	@RequestMapping(value = "uncollectionArticle")
	@ResponseBody
	public String uncollectionArticle(@RequestParam(value = "article",required = true)String article){
		try{
			healthEduArticleDoctorService.delete(article,getUID());
			return success("取消收藏成功!");
		}catch (Exception e){
			error(e);
			return error(-1, "取消收藏失败!");
		}
	}
	private String parsrHtml(String html) {
		Parser parser = null;
		try{
			parser = new Parser(html);
			TextExtractingVisitor visitor = new TextExtractingVisitor();
			parser.visitAllNodesWith(visitor);
			return StringUtils.isNotBlank(visitor.getExtractedText())?visitor.getExtractedText():"内容为图集,请点击查看";
		}catch (ParserException e){
			return html;//纯文本内容会转换失败,直接返回文本内容
		}
	}
}

+ 8 - 2
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/DoctorPatientGroupController.java

@ -631,7 +631,12 @@ public class DoctorPatientGroupController extends BaseController {
                //设置患者医保号
                json.put("ssc", temp.getSsc());
                String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                String diseases = "";
                try {
                    diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(!StringUtils.isEmpty(diseases)){
                    json.put("diseases",new JSONArray(diseases));
                }else{
@ -643,8 +648,9 @@ public class DoctorPatientGroupController extends BaseController {
                    List<SignFamily> ls = signFamilyDao.findLastJySignByPatient(code, 2);
                    jtSign = ls.size()>0? ls.get(0) : null;
                }
                else
                else{
                    jtSign = signFamilyDao.findSignByPatient(code,2);
                }
                SignFamily ssSign = signFamilyDao.findSignByPatient(code,1);

+ 34 - 42
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java

@ -3,14 +3,13 @@ package com.yihu.wlyy.web.doctor.patient;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.web.BaseController;
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.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 org.springframework.web.bind.annotation.*;
import java.util.List;
@ -21,6 +20,7 @@ import java.util.List;
 */
@RestController
@RequestMapping(value = "/doctor/patient_label_info")
@Api("居民管理")
public class SignPatientLabelInfoController extends BaseController {
    @Autowired
@ -33,17 +33,16 @@ public class SignPatientLabelInfoController extends BaseController {
     * @return
     */
    @RequestMapping(value = "/patient")
    @ResponseBody
    public String getPatient(String patient){
        try{
            if(StringUtils.isEmpty(patient)){
                return error(-1,"居民不能为空");
    public String getPatient(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }
            JSONObject p = labelInfoService.getPatient(patient);
            return write(200,"查询成功","data",p);
        }catch (Exception e){
            return write(200, "查询成功", "data", p);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
@ -102,7 +101,7 @@ public class SignPatientLabelInfoController extends BaseController {
            }
            page = page - 1;
            JSONArray result = labelInfoService.getPatientByTeamCode(getUID(), teamCode, exLabelCode,exLabelType,page, pagesize);
            JSONArray result = labelInfoService.getPatientByTeamCode(getUID(), teamCode, exLabelCode, exLabelType, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
@ -207,13 +206,13 @@ public class SignPatientLabelInfoController extends BaseController {
     * @return
     */
    @RequestMapping(value = "/patient_search")
    public String searchPatientByNameOrLabel(String filter,
    public String searchPatientByNameOrLabel(@RequestParam(required = true) String filter,
                                             @RequestParam(required = false) String labelCode,
                                             @RequestParam(required = false) String labelType,
                                             @RequestParam(required = false) Long teamCode,
                                             @RequestParam(required = false) String exLabelCode,
                                             @RequestParam(required = false) String exLabelType,
                                             int page, int pagesize) {
                                             @RequestParam(required = true) int page, @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
@ -242,6 +241,26 @@ public class SignPatientLabelInfoController extends BaseController {
        }
    }
    @RequestMapping(value = "/patient_search_all", method = RequestMethod.GET)
    @ApiOperation("根据姓名搜索所有团队下居民")
    public String searchPatients(@RequestParam(required = true) String filter,
                                 @RequestParam(required = false, defaultValue = "0") long teamCode,
                                 @RequestParam(required = false, defaultValue = "0") int page,
                                 @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "查询参数不能为空");
            }
            JSONArray result = labelInfoService.searchTeamsPatients(filter, getUID(), teamCode, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 添加居民到某个标签
     *
@ -353,31 +372,4 @@ public class SignPatientLabelInfoController extends BaseController {
        }
    }
    @RequestMapping(value = "/disease_to_label")
    public String diseaseToLabel() {
        try {
            if (labelInfoService.diseaseToLabel()) {
                return write(200, "转换成功");
            } else {
                return error(-1, "转换失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "转换失败");
        }
    }
    @RequestMapping(value = "/group_to_label")
    public String groupToLabel() {
        try {
            if (labelInfoService.groupToLabel()) {
                return write(200, "转换成功");
            } else {
                return error(-1, "转换失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "转换失败");
        }
    }
}

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

@ -765,8 +765,6 @@ public class DoctorFamilyContractController extends WeixinBaseController {
        }
    }
    /**
     * 获取没有健康管理师的患者列表
     *
@ -874,18 +872,8 @@ public class DoctorFamilyContractController extends WeixinBaseController {
            }
            if (StringUtils.isNotEmpty(patient)) {
                int result = expensesRemindService.remindPatientExpenses(patient, getUID());
                if (result == 1) {
                    return error(200, "提醒成功");
                } if (result == 2) {
                    return error(200, "居民未绑定手机号,无法短信提醒,已发送微信提醒");
                } if (result == 3) {
                    return error(200, "居民未绑定微信,无法微信提醒,已发送短信提醒");
                } if (result == -1) {
                    return error(-1, "居民未绑定手机号和微信,无法提醒");
                } else {
                    return error(-1, "提醒失败");
                }
                JSONObject result = expensesRemindService.remindPatientExpenses(patient, getUID());
                return write(result.getInt("status"), result.getString("msg"));
            } else if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")) {
                expensesRemindService.remindPatientExpensesAll(getUID());
                return error(200, "提醒操作成功");
@ -925,4 +913,54 @@ public class DoctorFamilyContractController extends WeixinBaseController {
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询居民是否与某个医生存在签约关系
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_patient_sign_exist",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorExistSign(@RequestParam(required = true) String doctor,
                                              @RequestParam(required = true) String patient){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            if(StringUtils.isEmpty(patient)){
                return error(-1,"居民不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorExistSign(patient,doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
    /**
     * 查询居民与某个医生是否可签约
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_patient_can_sign",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorCanSign(@RequestParam(required = true) String doctor,
                                            @RequestParam(required = true) String patient){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            if(StringUtils.isEmpty(patient)){
                return error(-1,"居民不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorCanSign(patient,doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
}

+ 7 - 34
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/team/AdminTeamController.java

@ -3,10 +3,12 @@ package com.yihu.wlyy.web.doctor.team;
import com.yihu.wlyy.entity.dict.Disease;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientDisease;
import com.yihu.wlyy.repository.patient.PatientDiseaseDao;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.util.IdCardUtil;
import com.yihu.wlyy.web.BaseController;
@ -31,11 +33,12 @@ import java.util.stream.Collectors;
public class AdminTeamController extends BaseController {
    @Autowired
    private PatientDiseaseDao patientDiseaseDao;
    @Autowired
    private AdminTeamService teamService;
    @Autowired
    private AdminTeamService memberService;
    @Autowired
    private SignPatientLabelInfoService signPatientLabelInfoService;
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ApiOperation(value = "团队数量")
@ -277,8 +280,9 @@ public class AdminTeamController extends BaseController {
                simplified.put("photo", patient.getPhoto());
                simplified.put("age", IdCardUtil.getAgeForIdcard(patient.getIdcard()));
                List<PatientDisease> diseases = patientDiseaseDao.findByPatient(patient.getCode());
                List<String> simplifiedDisease = diseases.stream().map(PatientDisease::getDiseaseName).collect(Collectors.toList());
                List<SignPatientLabelInfo>  diseases = signPatientLabelInfoService.getPatientLabelByLabelType(patient.getCode(),"3");
                List<String> simplifiedDisease = diseases.stream().map(SignPatientLabelInfo::getLabelName).collect(Collectors.toList());
                simplified.put("disease", simplifiedDisease);
@ -292,35 +296,4 @@ public class AdminTeamController extends BaseController {
        }
    }
    private List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String...propertyNames){
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans){
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    private Map<String, Object> copyBeanProperties(Object bean, String...propertyNames){
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames){
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null){
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
}

+ 53 - 0
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/team/SignTeamController.java

@ -1,8 +1,10 @@
package com.yihu.wlyy.web.doctor.team;
import java.util.List;
import java.util.Map;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -159,4 +161,55 @@ public class SignTeamController extends BaseController {
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 求助页面需要的医生查找
     * @return
     */
    @RequestMapping(value = "teamDoctorsAndAdminTeamDoctors", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamDoctorsAndAdminTeamDoctors(Long teamId) {
        try {
            Map<String,List<Doctor>> doctors = drHealthTeamService.getTeamDoctorsAndAdminTeamDoctors("64de930c-5b15-11e6-8344-fa163e8aee56",teamId);
            JSONObject jo=new JSONObject();
            jo.put("zr", addDoctor(doctors.get("zr")));
            jo.put("team", addDoctor(doctors.get("team")));
            return write(200, "查询成功!", "data",jo );
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    private JSONArray addDoctor(List<Doctor> zr) {
        JSONArray array=new JSONArray();
        for (Doctor doctor : zr) {
            if (doctor == null) {
                continue;
            }
            JSONObject json = new JSONObject();
            json.put("id", doctor.getId());
            // 医生标识
            json.put("code", doctor.getCode());
            // 医生姓名
            json.put("name", doctor.getName());
            // 所在医院名称
            json.put("hospital_name", doctor.getHosptialName());
            // 科室名称
            json.put("dept_name", StringUtils.isEmpty(doctor.getDeptName()) ? " " : doctor.getDeptName());
            // 职称名称
            json.put("job_name", StringUtils.isEmpty(doctor.getJobName()) ? " " : doctor.getJobName());
            // 头像
            json.put("photo", doctor.getPhoto());
            // 简介
            json.put("introduce", doctor.getIntroduce());
            // 专长
            json.put("expertise", doctor.getExpertise());
            // 是否求出
            json.put("isHelp", doctor.getIsHelp());
            array.put(json);
        }
        return array;
    }
}

+ 29 - 13
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/account/PatientController.java

@ -1,5 +1,6 @@
package com.yihu.wlyy.web.patient.account;
import com.sun.org.apache.regexp.internal.RE;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
@ -125,9 +126,11 @@ public class PatientController extends WeixinBaseController {
            return invalidUserException(e, -1, "患者信息查询失败!");
        }
    }
    /**
     * 患者微信圖片信息保存
     * @param mediaIds    頭像
     *
     * @param mediaIds 頭像
     * @return
     */
    @RequestMapping(value = "saveWXPhote")
@ -142,6 +145,7 @@ public class PatientController extends WeixinBaseController {
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 患者基本信息保存
     *
@ -171,12 +175,12 @@ public class PatientController extends WeixinBaseController {
                       @RequestParam(required = false) String street) {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
//            if (StringUtils.isEmpty(photo)) {
//                photo = fetchWxImages();
//            }
//            if (StringUtils.isNotEmpty(photo)) {
//                photo = CommonUtil.copyTempImage(photo);
//            }
            if (StringUtils.isEmpty(photo)) {
                photo = fetchWxImages();
            }
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
            }
            if (StringUtils.isNotEmpty(photo)) {
                patient.setPhoto(photo);
            }
@ -355,7 +359,7 @@ public class PatientController extends WeixinBaseController {
     */
    @RequestMapping(value = "teachers")
    @ResponseBody
    public String teachers(@RequestParam(required = false,defaultValue = "") String signDoctor) {
    public String teachers(@RequestParam(required = false, defaultValue = "") String signDoctor) {
        try {
            String code = getUID();//getUID();
            // 查询签约信息
@ -399,9 +403,9 @@ public class PatientController extends WeixinBaseController {
                }
            }
            if(StringUtils.isNotEmpty(signDoctor)){
                List<AdminTeam> teams = teamService.findDoctorsTeams(signDoctor,qkDoctor);
                doctorJson.put("team",teams != null ? new JSONArray(teams) : new ArrayList<AdminTeam>());
            if (StringUtils.isNotEmpty(signDoctor)) {
                List<AdminTeam> teams = teamService.findDoctorsTeams(signDoctor, qkDoctor);
                doctorJson.put("team", teams != null ? new JSONArray(teams) : new ArrayList<AdminTeam>());
            }
            doctorJson.put("list", jsonArray);
@ -787,7 +791,13 @@ public class PatientController extends WeixinBaseController {
                return error(-1, "openid不能为空");
            }
            JSONObject result = patientInfoService.switchFamilyAccount(getUID(), family, openid);
            String lastUid = getLastUid();
            if (StringUtils.isEmpty(lastUid)) {
                lastUid = getUID();
            }
            JSONObject result = patientInfoService.switchFamilyAccount(lastUid, family, openid);
            int status = result.getInt("status");
@ -796,7 +806,13 @@ public class PatientController extends WeixinBaseController {
            } else if (status == -2) {
                return error(-2, "家庭成员不存在该人");
            } else {
                return write(200, "切换账号成功", "data", result.getJSONObject("data"));
                JSONObject json = result.getJSONObject("data");
                if (StringUtils.isNotEmpty(lastUid)) {
                    json.put("lastUid", lastUid);
                }
                return write(200, "切换账号成功", "data", json);
            }
        } catch (Exception e) {
            e.printStackTrace();

+ 683 - 645
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java

@ -35,111 +35,112 @@ import com.yihu.wlyy.web.WeixinBaseController;
/**
 * 患者端:三师咨询控制类
 * @author George
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-患者咨询")
public class ConsultController extends WeixinBaseController {
	@Autowired
	private ConsultTeamService consultTeamService;
	@Autowired
	private DoctorCommentService doctorCommentService;
	@Autowired
	private DoctorStatisticsService doctorStatisticsService;
    @Autowired
	private DoctorService doctorService;
	@Autowired
	private TalkGroupService talkGroupService;
	@Autowired
	private DoctorWorkTimeService doctorWorkTimeService;
	/**
	 * 患者咨询记录查询
	 * @param title 咨询标题
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "records")
	@ResponseBody
	public String consultRecords(
			@RequestParam(required = false) String  title,
			long id,
			int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<Object> data = consultTeamService.findConsultRecordByPatient(getUID(), id, pagesize,title);
			if (data != null) {
				for (Object consult : data.getContent()) {
					if (consult == null) {
						continue;
					}
					Object[] result = (Object[])consult;
					JSONObject json = new JSONObject();
					json.put("id", result[0]);
					// 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
					json.put("type", result[1]);
					// 设置咨询标识
					json.put("code", result[2]);
					// 设置显示标题
					json.put("title", result[3]);
					// 设置主诉
					json.put("symptoms", result[4]);
					// 咨询状态
					json.put("status", result[6]);
					// 设置咨询日期
					json.put("czrq", DateUtil.dateToStrLong((Date)result[5]));
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 获取医生的排班时间
	 *
	 * @param doctor
	 * @param week
	 * @return
	 */
	@RequestMapping(value = "/doctor_worktime/week")
	@ResponseBody
	public String getDoctorWeekWorkTime(String doctor,String week){
		try{
			JSONObject result = doctorWorkTimeService.findDoctorWeekWorkTime(doctor,week);
			return write(200,"查询成功!","data",result);
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败!");
		}
	}
	/**
	 * 获取医生某天的排班时间
	 *
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/doctor_worktime")
	@ResponseBody
	public String getDoctorWorkTime(String doctor){
		try{
			JSONObject result = doctorWorkTimeService.findDoctorWorkTime(doctor);
			return write(200,"查询成功!","data",result);
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败!");
		}
	}
    private ConsultTeamService consultTeamService;
    @Autowired
    private DoctorCommentService doctorCommentService;
    @Autowired
    private DoctorStatisticsService doctorStatisticsService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private TalkGroupService talkGroupService;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    /**
     * 患者咨询记录查询
     *
     * @param title    咨询标题
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    @RequestMapping(value = "records")
    @ResponseBody
    public String consultRecords(
            @RequestParam(required = false) String title,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Object> data = consultTeamService.findConsultRecordByPatient(getUID(), id, pagesize, title);
            if (data != null) {
                for (Object consult : data.getContent()) {
                    if (consult == null) {
                        continue;
                    }
                    Object[] result = (Object[]) consult;
                    JSONObject json = new JSONObject();
                    json.put("id", result[0]);
                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
                    json.put("type", result[1]);
                    // 设置咨询标识
                    json.put("code", result[2]);
                    // 设置显示标题
                    json.put("title", result[3]);
                    // 设置主诉
                    json.put("symptoms", result[4]);
                    // 咨询状态
                    json.put("status", result[6]);
                    // 设置咨询日期
                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 获取医生的排班时间
     *
     * @param doctor
     * @param week
     * @return
     */
    @RequestMapping(value = "/doctor_worktime/week")
    @ResponseBody
    public String getDoctorWeekWorkTime(String doctor, String week) {
        try {
            JSONObject result = doctorWorkTimeService.findDoctorWeekWorkTime(doctor, week);
            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 获取医生某天的排班时间
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_worktime")
    @ResponseBody
    public String getDoctorWorkTime(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.findDoctorWorkTime(doctor);
            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 医生是否在工作
@ -149,558 +150,595 @@ public class ConsultController extends WeixinBaseController {
     */
    @RequestMapping(value = "is_doctor_working")
    @ResponseBody
	public String isDoctorAtWorking(String doctor){
		try{
    public String isDoctorAtWorking(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.isDoctorWorking(doctor);
            return write(200,result.getString("msg"),"data",result.getString("status"));
		}catch (Exception e){
            return write(200, result.getString("msg"), "data", result.getString("status"));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 名医是否在工作
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "is_famous_doctor_working")
    @ResponseBody
    public String isFamousDoctorAtWorking(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.isFamousDoctorWorking(doctor);
            return write(200, result.getString("msg"), "data", result.getString("status"));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 名医咨询剩余次数查询
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/consult_times_remain")
    @ResponseBody
    public String famousDoctorTimesRemain(String doctor) {
        try {
            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
			return error(-1,"查询失败");
		}
	}
	/**
	 * 名医是否在工作
	 *
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "is_famous_doctor_working")
	@ResponseBody
	public String isFamousDoctorAtWorking(String doctor){
		try{
			JSONObject result = doctorWorkTimeService.isFamousDoctorWorking(doctor);
			return write(200,result.getString("msg"),"data",result.getString("status"));
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败");
		}
	}
	/**
	 * 名医咨询剩余次数查询
	 *
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/consult_times_remain")
	@ResponseBody
	public String famousDoctorTimesRemain(String doctor){
		try{
			int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor);
			return write(200,"查询成功","data",result);
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败");
		}
	}
	/**
	 * 获取未完成咨询
	 *
	 * @return
	 */
	@RequestMapping(value = "/unfinished")
	@ResponseBody
	public String getUnFinishedConsult(){
		try{
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取未完成咨询
     *
     * @return
     */
    @RequestMapping(value = "/unfinished")
    @ResponseBody
    public String getUnFinishedConsult() {
        try {
            List<ConsultTeam> unfinishedConsult = consultTeamService.getUnfinishedConsult(getUID());
			JSONArray result = new JSONArray(unfinishedConsult);
            return write(200,"查询成功!","data",result);
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败!");
		}
	}
	/**
	 * 三师咨询添加接口
	 * @param type 咨询类型:1三师咨询,2家庭医生咨询
	 * @param when 发病时间
	 * @param symptoms 主要症状
	 * @param images 图片URL地址,多图以逗号分隔
	 * @param voice 语音URL地址
	 * @return
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	public String add(@RequestParam(required = false) Integer type,
            JSONArray result = new JSONArray(unfinishedConsult);
            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 查询居民与某个医生是否存在未结束的咨询
     *
     * @param doctor 医生
     * @return
     */
    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isExistsUnfinishedConsult(@RequestParam(required = true) String doctor) {
        try {
            JSONObject result = new JSONObject();
            List<ConsultTeam> consults = consultTeamService.getUnfinishedConsult(getUID(), doctor);
            if (consults != null && consults.size() > 0) {
                return write(200, "查询成功", "data", consults.get(0).getConsult());
            } else {
                return write(200, "查询成功", "data", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 三师咨询添加接口
     *
     * @param type     咨询类型:1三师咨询,2家庭医生咨询
     * @param when     发病时间
     * @param symptoms 主要症状
     * @param images   图片URL地址,多图以逗号分隔
     * @param voice    语音URL地址
     * @return
     */
    @RequestMapping(value = "add")
    @ResponseBody
    public String add(@RequestParam(required = false) Integer type,
                      @RequestParam(required = false) String when,
                      @RequestParam String symptoms,
					  @RequestParam(required = false) String images,
					  @RequestParam(required = false) String voice,
					  @RequestParam(required = false) Long guidance) {
		try {
			if (type == null) {
				type = 1;
			}
			if (type != 1 && type != 2) {
				return error(-1, "无效请求!");
			}
			if (consultTeamService.exist(getUID(),type)) {
				return error(-1, "还有咨询未结束,不允许再次提交咨询!");
			}
			if (StringUtils.isEmpty(images)) {
				images = fetchWxImages();
			}
			// 将临时图片拷贝到正式存储路径下
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			if (StringUtils.isEmpty(voice)) {
				voice = fetchWxVoices();
			}
			if (StringUtils.isNotEmpty(voice)) {
				voice = CommonUtil.copyTempVoice(voice);
			}
			ConsultTeam consult = new ConsultTeam();
			// 设置咨询类型:1三师咨询,2家庭医生咨询  6.名医咨询
			consult.setType(type);
			// 设置发病时间
			consult.setWhen(when);
			// 设置主要症状
			consult.setSymptoms(symptoms);
			// 设置咨询图片URL
			consult.setImages(images);
			// 设置咨询语音URL
			consult.setVoice(voice);
			// 设置关联咨询
			if(guidance != null && guidance > 0) {
				consult.setGuidance(guidance);
			}
			// 保存到数据库
			int res = consultTeamService.addTeamConsult(consult, getUID());
			if (res == -1) {
				return error(-1, "家庭签约信息不存在或已过期,无法进行家庭医生咨询!");
			} else if (res == -2) {
				return error(-1, "家庭签约信息不存在或已过期,无法进行三师医生咨询!");
			}
			Doctor doctor = doctorService.findDoctorByCode(consult.getDoctor());
			//创建咨询讨论组
			talkGroupService.createConsultTalkGroup(consult.getDoctor(), doctor.getName(), doctor.getHospital(), doctor.getHosptialName(),
					consult.getPatient(), consult.getName(),consult.getConsult());
			// 添加到统计队列
			if (consult.getType() == 2) {
				DoctorStatisticsTask.getInstance(doctorStatisticsService).put(consult.getDoctor(), 1, 1, 0);
			}
			// 推送消息给医生
			PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
			return success("提交成功");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "提交失败!");
		}
	}
	/**
	 * 名医咨询添加接口
	 * @param when 发病时间
	 * @param symptoms 主要症状
	 * @param images 图片URL地址,多图以逗号分隔
	 * @param voice 语音URL地址
	 * @param doctorCode 名医的code
	 * @return
	 */
	@RequestMapping(value = "famousAdd")
	@ResponseBody
	public String famousAdd(
					  @RequestParam(required = false)String when,
					  String symptoms,
					  @RequestParam(required = false) String doctorCode,
					  @RequestParam(required = false) String images,
					  @RequestParam(required = false) String voice) {
		try {
			//判断医生是否是在工作时间
			JSONObject jo=doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
			if(!jo.get("status").equals("1")){
				return error(-1, jo.get("msg").toString());
			}
			//判断医生是否剩下咨询次数
			int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctorCode);
			if(result==0){
				return error(-1, "没有次数");
			}
			if (StringUtils.isEmpty(images)) {
				images = fetchWxImages();
			}
			// 将临时图片拷贝到正式存储路径下
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			if (StringUtils.isEmpty(voice)) {
				voice = fetchWxVoices();
			}
			if (StringUtils.isNotEmpty(voice)) {
				voice = CommonUtil.copyTempVoice(voice);
			}
			//判断是否已经存在还没有关闭的名医咨询
			if(consultTeamService.isExistFamousConsult(getUID())){
				return error(-1, "已经存在名医咨询!");
			}
			ConsultTeam consult = new ConsultTeam();
			// 设置咨询类型:1三师咨询,2家庭医生咨询 6.名医咨询
			consult.setType(6);
			// 设置发病时间
			consult.setWhen(when);
			// 设置主要症状
			consult.setSymptoms(symptoms);
			// 设置咨询图片URL
			consult.setImages(images);
			// 设置咨询语音URL
			consult.setVoice(voice);
			consult.setDoctor(doctorCode);//设置专科医生
			// 保存到数据库
			consultTeamService.addFamousTeamConsult(consult, getUID());
			//名医咨询次数减一
			doctorWorkTimeService.setDoctorCurrentConsultTimesRemain(doctorCode);
			// 推送消息给医生
			PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
			return success("提交成功");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "提交失败!");
		}
	}
	/**
	 * 名医列表
	 * @return
                      @RequestParam(required = false) String images,
                      @RequestParam(required = false) String voice,
                      @RequestParam(required = false) Long guidance) {
        try {
            if (type == null) {
                type = 1;
            }
            if (type != 1 && type != 2) {
                return error(-1, "无效请求!");
            }
            try {
                if (consultTeamService.exist(getUID(), type)) {
                    return error(-1, "还有咨询未结束,不允许再次提交咨询!");
                }
            } catch (Exception e) {
                return error(-1, e.getMessage());
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
            }
            // 将临时图片拷贝到正式存储路径下
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
            if (StringUtils.isEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型:1三师咨询,2家庭医生咨询  6.名医咨询
            consult.setType(type);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            // 设置关联咨询
            if (guidance != null && guidance > 0) {
                consult.setGuidance(guidance);
            }
            // 保存到数据库
            int res = consultTeamService.addTeamConsult(consult, getUID());
            if (res == -1) {
                return error(-1, "家庭签约信息不存在或已过期,无法进行家庭医生咨询!");
            } else if (res == -2) {
                return error(-1, "家庭签约信息不存在或已过期,无法进行三师医生咨询!");
            }
            Doctor doctor = doctorService.findDoctorByCode(consult.getDoctor());
            //创建咨询讨论组
            talkGroupService.createConsultTalkGroup(consult.getDoctor(), doctor.getName(), doctor.getHospital(), doctor.getHosptialName(),
                    consult.getPatient(), consult.getName(), consult.getConsult());
            // 添加到统计队列
            if (consult.getType() == 2) {
                DoctorStatisticsTask.getInstance(doctorStatisticsService).put(consult.getDoctor(), 1, 1, 0);
            }
            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
            return success("提交成功");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败!");
        }
    }
    /**
     * 名医咨询添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param images     图片URL地址,多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "famousAdd")
    @ResponseBody
    public String famousAdd(
            @RequestParam(required = false) String when,
            String symptoms,
            @RequestParam(required = false) String doctorCode,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String voice) {
        try {
            //判断医生是否是在工作时间
            JSONObject jo = doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
            if (!jo.get("status").equals("1")) {
                return error(-1, jo.get("msg").toString());
            }
            //判断医生是否剩下咨询次数
            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctorCode);
            if (result == 0) {
                return error(-1, "没有次数");
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
            }
            // 将临时图片拷贝到正式存储路径下
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
            if (StringUtils.isEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            //判断是否已经存在还没有关闭的咨询
            if (consultTeamService.isExistConsult(getUID(), doctorCode)) {
                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.名医咨询
            consult.setType(6);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            consultTeamService.addFamousTeamConsult(consult, getUID(), "1");
            //名医咨询次数减一
            doctorWorkTimeService.setDoctorCurrentConsultTimesRemain(doctorCode);
            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
            return success("提交成功");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败!");
        }
    }
    /**
     * 名医列表
     *
     * @return
     */
    @RequestMapping(value = "famousDoctorList")
    @ResponseBody
    public String famousDoctorList(
            @RequestParam(required = false) String name,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = doctorService.famousDoctorList(name, page, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    // 判断名医是否在工作
                    JSONObject isWorking = doctorWorkTimeService.isFamousDoctorWorking(doctor.getCode());
                    if (isWorking == null || !isWorking.getString("status").equals("1")) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生性别
                    json.put("sex", doctor.getSex());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital", doctor.getHospital());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHosptialName());
                    // 科室名称
                    json.put("dept_name", (doctor.getDeptName() == null ||
                            StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", (doctor.getJobName() == null ||
                            StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    // 剩余咨询次数
                    json.put("num", doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode()));
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    @RequestMapping(value = "status")
    @ResponseBody
    public String status(String consult) {
        try {
            ConsultTeam ct = consultTeamService.findByCode(consult);
            if (ct == null) {
                return error(-1, "获取状态失败!");
            } else {
                return write(200, "获取状态成功!", "data", ct.getStatus());
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "获取状态失败!");
        }
    }
    /**
     * 查询患者三师咨询咨询列表
     *
     * @param status   咨询状态(0未结束,1已结束,-1 已取消)
     * @param pagesize 页数
     * @return 查询结果
     */
	@RequestMapping(value = "famousDoctorList")
	@ResponseBody
	public String famousDoctorList(
									@RequestParam(required = false) String name,
									int page,
									int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<Doctor>list = doctorService.famousDoctorList(name, page, pagesize);
			if (list != null) {
				for (Doctor doctor : list) {
					if (doctor == null) {
						continue;
					}
					// 判断名医是否在工作
					JSONObject isWorking = doctorWorkTimeService.isFamousDoctorWorking(doctor.getCode());
					if(isWorking == null || !isWorking.getString("status").equals("1")){
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", doctor.getId());
					// 医生标识
					json.put("code", doctor.getCode());
					// 医生性别
					json.put("sex", doctor.getSex());
					// 医生姓名
					json.put("name", doctor.getName());
					// 所在医院名称
					json.put("hospital", doctor.getHospital());
					// 所在医院名称
					json.put("hospital_name", doctor.getHosptialName());
					// 科室名称
					json.put("dept_name", (doctor.getDeptName() == null ||
							StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
					// 职称名称
					json.put("job_name", (doctor.getJobName() == null ||
							StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
					// 头像
					json.put("photo", doctor.getPhoto());
					// 简介
					json.put("introduce", doctor.getIntroduce());
					// 专长
					json.put("expertise", doctor.getExpertise());
					// 剩余咨询次数
					json.put("num", doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode()));
					array.put(json);
				}
			}
			return write(200, "获取医院医生列表成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取医院医生列表失败!");
		}
	}
	@RequestMapping(value = "status")
	@ResponseBody
	public String status(String consult) {
		try {
			ConsultTeam ct = consultTeamService.findByCode(consult);
			if (ct == null) {
				return error(-1, "获取状态失败!");
			} else {
				return write(200, "获取状态成功!", "data", ct.getStatus());
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "获取状态失败!");
		}
	}
	/**
	 * 查询患者三师咨询咨询列表
	 * @param status  咨询状态(0未结束,1已结束,-1 已取消)
	 * @param pagesize 页数
	 * @return 查询结果
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(int status, long id, int pagesize) {
		try {
			Page<ConsultTeam> consults = consultTeamService.findByPatient(getUID(), status, id, pagesize);
			JSONArray jsonArray = new JSONArray();
			if (consults != null) {
				for (ConsultTeam consult : consults) {
					if (consult == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", consult.getId());
					// 设置咨询标志
					json.put("code", consult.getConsult());
					// 设置咨询类型:0公共咨询,1指定医生,2三师咨询
					json.put("type", consult.getType());
					// 设置标题
					json.put("title", consult.getSymptoms());
					// 设置发病时间
					json.put("when", consult.getWhen());
					// 设置患者未读数量
					json.put("patientRead", consult.getPatientRead());
					// 设置状态
					json.put("status", consult.getStatus());
					// 设置患者评价标识
					json.put("comment", consult.getComment());
					// 设置关联指导
					json.put("guidance", consult.getGuidance());
					// 设置咨询或回复时间
					json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					jsonArray.put(json);
				}
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 患者取消三师咨询
	 * @param consult
	 * @return
	 */
	@RequestMapping(value = "cancel")
	@ResponseBody
	public String cancel(String consult) {
		try {
			int row = consultTeamService.cancel(consult);
			if (row > 0) {
				return success("咨询已取消!");
			} else {
				return error(-1, "咨询不能取消!");
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "操作失败!");
		}
	}
	/**
	 * 修改状态为1的咨询记录为结束
	 * @param code 咨询标识
	 * @return
	 */
	@RequestMapping(value = "finish")
	@ResponseBody
	public String finish(String code) {
		try {
			int row = consultTeamService.finish(code);
			if (row > 0) {
				return success("操作成功!");
			} else {
				return error(-1, "操作失败!");
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "操作失败!");
		}
	}
	/**
	 * 三师咨询追问接口
	 * @param consult 咨询标识
	 * @param content 追问内容
	 * @param type 追问内容类型:1文字,2图片,3语音
	 * @return
	 */
	@RequestMapping(value = "append")
	@ResponseBody
	public String append(String consult, String content, int type) {
		try {
			List<ConsultTeamLog> logs = new ArrayList<ConsultTeamLog>();
			if (type == 2) {
				// 图片消息
				if (StringUtils.isEmpty(content)) {
					content = fetchWxImages();
				}
				// 将临时图片拷贝到正式存储路径下
				if (StringUtils.isNotEmpty(content)) {
					content = CommonUtil.copyTempImage(content);
				}
				if (StringUtils.isEmpty(content)) {
					return error(-1, "图片上传失败!");
				}
				String[] images = content.split(",");
				for (String image : images) {
					ConsultTeamLog log = new ConsultTeamLog();
					log.setConsult(consult);
					log.setContent(image);
					log.setDel("1");
					log.setChatType(type);
					log.setType(2);
					logs.add(log);
				}
			} else {
				ConsultTeamLog log = new ConsultTeamLog();
				log.setConsult(consult);
				log.setContent(content);
				log.setDel("1");
				log.setChatType(type);
				log.setType(2);
				logs.add(log);
			}
			consultTeamService.reply(logs, getUID());
			return write(200, "追问成功!", "data", content);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "追问失败!");
		}
	}
	/**
	 * 网络咨询咨询日志查询
	 * @param consult 咨询标识
	 * @param pagesize 每页显示数,默认为10
	 * @return
	 */
	@RequestMapping(value = "loglist")
	@ResponseBody
	public String loglist(String consult, long id, int pagesize) {
		try {
			ConsultTeam consultModel = consultTeamService.findByCode(consult);
			if (consultModel == null) {
				return error(-1, "咨询记录不存在!");
			}
			if (id <= 0) {
				// 更新患者未读数量为0
				consultTeamService.clearPatientRead(consult);
			}
			// 查询日志列表
			JSONArray jsonArray = new JSONArray();
			Page<ConsultTeamLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
			if (list != null) {
				for (ConsultTeamLog log : list) {
					if (consult == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", log.getId());
					// 设置回复医生姓名
					json.put("doctorName", log.getDoctorName());
					// 设置回复内容
					json.put("content", log.getContent());
					// 设置咨询或回复时间
					json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					// 设置记录类型:1文字,2图片,3语音
					json.put("msgType", log.getChatType());
					// 设置类型:0患者问,1医生回复,2患者追问,3患者评价
					json.put("type", log.getType());
					jsonArray.put(json);
				}
			}
			// 返回结果
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	/**
	 * 查找单个咨询记录
	 * @param consult 咨询标识
	 * @param logId 记录标识
	 *
	 * @return
	 */
	@RequestMapping(value = "oneLog")
	@ResponseBody
	public String oneLog(String consult,Long logId) {
		try {
			ConsultTeam consultModel = consultTeamService.findByCode(consult);
			if (consultModel == null) {
				return error(-1, "咨询记录不存在!");
			}
			// 查询日志列表
			JSONObject json = new JSONObject();
			ConsultTeamLog log = consultTeamService.oneLog(logId);
			if (log != null) {
					json.put("id", log.getId());
					// 设置回复医生姓名
					json.put("doctorName", log.getDoctorName());
					// 设置回复内容
					json.put("content", log.getContent());
					// 设置咨询或回复时间
					json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					// 设置记录类型:1文字,2图片,3语音
					json.put("msgType", log.getChatType());
					// 设置类型:0患者问,1医生回复,2患者追问,3患者评价
					json.put("type", log.getType());
			}
			// 返回结果
			return write(200, "查询成功", "consult", json);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	/**
	 * 三师咨询评论
	 * @param consult 咨询标识
	 * @param content 评价内容
	 * @param star 星级
	 * @return 操作结果
	 */
	@RequestMapping(value = "comment")
	@ResponseBody
	public String comment(String consult, String content, int star) {
		try {
			// 保存评价
			JSONArray array = doctorCommentService.consultComment(getUID(), consult, content, star, 2);
			// 添加到统计队列
			if (array != null) {
				DoctorStatisticsTask.getInstance(doctorStatisticsService).put(array);
			}
			// 添加评价记录
			ConsultTeamLog log = new ConsultTeamLog();
			log.setConsult(consult);
			log.setContent(content);
			log.setChatType(1);
			log.setDel("1");
			log.setType(3);
			log = consultTeamService.reply(log, getUID(), null, log.getType());
			return success("感谢您的评价!");
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "评价失败!");
		}
	}
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(int status, long id, int pagesize) {
        try {
            Page<ConsultTeam> consults = consultTeamService.findByPatient(getUID(), status, id, pagesize);
            JSONArray jsonArray = new JSONArray();
            if (consults != null) {
                for (ConsultTeam consult : consults) {
                    if (consult == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", consult.getId());
                    // 设置咨询标志
                    json.put("code", consult.getConsult());
                    // 设置咨询类型:0公共咨询,1指定医生,2三师咨询
                    json.put("type", consult.getType());
                    // 设置标题
                    json.put("title", consult.getSymptoms());
                    // 设置发病时间
                    json.put("when", consult.getWhen());
                    // 设置患者未读数量
                    json.put("patientRead", consult.getPatientRead());
                    // 设置状态
                    json.put("status", consult.getStatus());
                    // 设置患者评价标识
                    json.put("comment", consult.getComment());
                    // 设置关联指导
                    json.put("guidance", consult.getGuidance());
                    // 设置咨询或回复时间
                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jsonArray.put(json);
                }
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 患者取消三师咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "cancel")
    @ResponseBody
    public String cancel(String consult) {
        try {
            int row = consultTeamService.cancel(consult);
            if (row > 0) {
                return success("咨询已取消!");
            } else {
                return error(-1, "咨询不能取消!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    /**
     * 修改状态为1的咨询记录为结束
     *
     * @param code 咨询标识
     * @return
     */
    @RequestMapping(value = "finish")
    @ResponseBody
    public String finish(String code) {
        try {
            int row = consultTeamService.finish(code);
            if (row > 0) {
                return success("操作成功!");
            } else {
                return error(-1, "操作失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    /**
     * 三师咨询追问接口
     *
     * @param consult 咨询标识
     * @param content 追问内容
     * @param type    追问内容类型:1文字,2图片,3语音
     * @return
     */
    @RequestMapping(value = "append")
    @ResponseBody
    public String append(String consult, String content, int type) {
        try {
            List<ConsultTeamLog> logs = new ArrayList<ConsultTeamLog>();
            if (type == 2) {
                // 图片消息
                if (StringUtils.isEmpty(content)) {
                    content = fetchWxImages();
                }
                // 将临时图片拷贝到正式存储路径下
                if (StringUtils.isNotEmpty(content)) {
                    content = CommonUtil.copyTempImage(content);
                }
                if (StringUtils.isEmpty(content)) {
                    return error(-1, "图片上传失败!");
                }
                String[] images = content.split(",");
                for (String image : images) {
                    ConsultTeamLog log = new ConsultTeamLog();
                    log.setConsult(consult);
                    log.setContent(image);
                    log.setDel("1");
                    log.setChatType(type);
                    log.setType(2);
                    logs.add(log);
                }
            } else {
                ConsultTeamLog log = new ConsultTeamLog();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(2);
                logs.add(log);
            }
            consultTeamService.reply(logs, getUID());
            return write(200, "追问成功!", "data", content);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "追问失败!");
        }
    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    @RequestMapping(value = "loglist")
    @ResponseBody
    public String loglist(String consult, long id, int pagesize) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在!");
            }
            if (id <= 0) {
                // 更新患者未读数量为0
                consultTeamService.clearPatientRead(consult);
            }
            // 查询日志列表
            JSONArray jsonArray = new JSONArray();
            Page<ConsultTeamLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
            if (list != null) {
                for (ConsultTeamLog log : list) {
                    if (consult == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", log.getId());
                    // 设置回复医生姓名
                    json.put("doctorName", log.getDoctorName());
                    // 设置回复内容
                    json.put("content", log.getContent());
                    // 设置咨询或回复时间
                    json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    // 设置记录类型:1文字,2图片,3语音
                    json.put("msgType", log.getChatType());
                    // 设置类型:0患者问,1医生回复,2患者追问,3患者评价
                    json.put("type", log.getType());
                    jsonArray.put(json);
                }
            }
            // 返回结果
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 查找单个咨询记录
     *
     * @param consult 咨询标识
     * @param logId   记录标识
     * @return
     */
    @RequestMapping(value = "oneLog")
    @ResponseBody
    public String oneLog(String consult, Long logId) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在!");
            }
            // 查询日志列表
            JSONObject json = new JSONObject();
            ConsultTeamLog log = consultTeamService.oneLog(logId);
            if (log != null) {
                json.put("id", log.getId());
                // 设置回复医生姓名
                json.put("doctorName", log.getDoctorName());
                // 设置回复内容
                json.put("content", log.getContent());
                // 设置咨询或回复时间
                json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                // 设置记录类型:1文字,2图片,3语音
                json.put("msgType", log.getChatType());
                // 设置类型:0患者问,1医生回复,2患者追问,3患者评价
                json.put("type", log.getType());
            }
            // 返回结果
            return write(200, "查询成功", "consult", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 三师咨询评论
     *
     * @param consult 咨询标识
     * @param content 评价内容
     * @param star    星级
     * @return 操作结果
     */
    @RequestMapping(value = "comment")
    @ResponseBody
    public String comment(String consult, String content, int star) {
        try {
            // 保存评价
            JSONArray array = doctorCommentService.consultComment(getUID(), consult, content, star, 2);
            // 添加到统计队列
            if (array != null) {
                DoctorStatisticsTask.getInstance(doctorStatisticsService).put(array);
            }
            // 添加评价记录
            ConsultTeamLog log = new ConsultTeamLog();
            log.setConsult(consult);
            log.setContent(content);
            log.setChatType(1);
            log.setDel("1");
            log.setType(3);
            log = consultTeamService.reply(log, getUID(), null, log.getType());
            return success("感谢您的评价!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "评价失败!");
        }
    }
}

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

@ -146,10 +146,14 @@ public class FamilyMemberController extends BaseController {
     */
    @RequestMapping(value = "/members", method = RequestMethod.GET)
    @ApiOperation(value = "家庭成员查询")
    public String getPatientFamilyMembers() {
    public String getPatientFamilyMembers(@RequestParam(required = false) String patient) {
        try {
            JSONArray result = familyMemberService.getPatientFamilyMembers(getUID(), "");
            JSONArray result = new JSONArray();
            if (StringUtils.isNotEmpty(patient)) {
                result = familyMemberService.getPatientMembers(patient, "", true, getUID());
            } else {
                result = familyMemberService.getPatientFamilyMembers(getUID(), "");
            }
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();

+ 93 - 6
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/HealthEduArticleController.java

@ -1,6 +1,15 @@
package com.yihu.wlyy.web.patient.health;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.service.app.health.HealthEduArticleOpHistoryService;
import com.yihu.wlyy.service.app.health.HealthEduArticlePatientService;
import com.yihu.wlyy.service.common.account.DoctorService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.TextExtractingVisitor;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -9,6 +18,7 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
@ -16,6 +26,9 @@ import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import java.util.HashMap;
import java.util.Map;
/**
 * 患者端:健康教育控制类
 * @author George
@ -27,7 +40,12 @@ import com.yihu.wlyy.web.BaseController;
public class HealthEduArticleController extends BaseController {
	@Autowired
	private HealthEduArticleService healthEduArticleService;
	private HealthEduArticlePatientService healthEduArticlePatientService;
	@Autowired
	private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
	@Autowired
	private DoctorService doctorService;
	/**
	 * 查询文章列表
@ -36,10 +54,11 @@ public class HealthEduArticleController extends BaseController {
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(long id, int pagesize) {
	public String list(@RequestParam("id")long id, @RequestParam("pagesize") int pagesize) {
		try {
			Page<HealthEduArticlePatient> list = healthEduArticleService.findByPatient(getUID(), id, pagesize);
			Page<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();
@ -53,11 +72,28 @@ public class HealthEduArticleController extends BaseController {
					// 文章查看URL
					json.put("url", article.getUrl());
					// 文章简介
					json.put("content", article.getContent());
					json.put("content", parsrHtml(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);
				}
			}
@ -67,7 +103,46 @@ public class HealthEduArticleController extends BaseController {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询文章列表
	 * @param id 数据文章唯一标示article
	 * @return 列表
	 */
	@RequestMapping(value = "article")
	@ResponseBody
	public String article(@RequestParam(value = "article",required = true) long id) {
		try {
			//获取单条文章记录
			HealthEduArticlePatient healthEduArticlePatient = healthEduArticlePatientService.findById(id);
			int isRead  = healthEduArticleOpHistoryService.countByUserStatus(getUID(),HealthEduArticleOpHistory.READ_STATUS);
			//插入文章读取状态第一次阅读记录浏览数量//暂时更新每次都算一次浏览量
			healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS,healthEduArticlePatient.getArticle(),healthEduArticlePatient.getTitle(),getUID());
			if(isRead==0){
				//将文章更新为已读
				healthEduArticlePatientService.updateRead(getUID(), healthEduArticlePatient.getArticle());
			}
			JSONObject json = new JSONObject();
			json.put("id", healthEduArticlePatient.getId());
			// 文章标识
			json.put("article", healthEduArticlePatient.getArticle());
			// 医生姓名
			json.put("doctorName", healthEduArticlePatient.getDoctorName());
			// 文章标题
			json.put("title", healthEduArticlePatient.getTitle());
			// 文章内容
			json.put("content", healthEduArticlePatient.getContent());
			json.put("url", healthEduArticlePatient.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 文章标识
@ -75,13 +150,25 @@ public class HealthEduArticleController extends BaseController {
	 */
	@RequestMapping(value = "read")
	@ResponseBody
	public String read(String article) {
	public String read(@RequestParam("article") String article) {
		try {
			healthEduArticleService.updateRead(getUID(), article);
			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;
		try{
			parser = new Parser(html);
		}catch (ParserException e){
			return html;//纯文本内容会转换失败,直接返回文本内容
		}
		TextExtractingVisitor visitor = new TextExtractingVisitor();
		parser.visitAllNodesWith(visitor);
		return StringUtils.isNotBlank(visitor.getExtractedText())?visitor.getExtractedText():"内容为图集,请点击查看";
	}
}

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

@ -577,4 +577,45 @@ public class FamilyContractController extends BaseController {
        }
    }
    /**
     * 查询居民是否与某个医生存在签约关系
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_sign_exist",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorExistSign(@RequestParam(required = true) String doctor){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorExistSign(getUID(),doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
    /**
     * 查询居民与某个医生是否可签约
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_can_sign",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatientAndDoctorCanSign(@RequestParam(required = true) String doctor){
        try{
            if(StringUtils.isEmpty(doctor)){
                return error(-1,"医生不能为空");
            }
            JSONObject result = familyContractService.isPatientAndDoctorCanSign(getUID(),doctor);
            return write(200,"查询成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
}

+ 87 - 24
patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java

@ -5,6 +5,7 @@ import com.yihu.wlyy.service.app.statistics.StatisticsAllService;
import com.yihu.wlyy.service.app.statistics.StatisticsService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -13,8 +14,11 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Set;
/**
 * Created by lyr on 2016/08/16.
 */
@ -57,7 +61,12 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping(value = "/interval")
    @ResponseBody
    public String indexInterval(String startDate, String endDate, int interval, String area, int level, String index) {
    public String indexInterval(@RequestParam(required = true) String startDate,
                                @RequestParam(required = true)String endDate,
                                @RequestParam(required = true)int interval,
                                @RequestParam(required = true)String area,
                                @RequestParam(required = true)int level,
                                @RequestParam(required = true)String index) {
        String tag = "";
        try {
            String[] indexes = index.split(",");
@ -88,7 +97,11 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/increment")
    @ResponseBody
    public String getIndexIncrement(String startDate, String endDate, String area, int level, String index) {
    public String getIndexIncrement(@RequestParam(required = true)String startDate,
                                    @RequestParam(required = true)String endDate,
                                    @RequestParam(required = true)String area,
                                    @RequestParam(required = true) int level,
                                    @RequestParam(required = true)String index) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -115,7 +128,10 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/total")
    @ResponseBody
    public String getIndexTotal(String endDate, String area, int level, String index) {
    public String getIndexTotal(@RequestParam(required = true)String endDate,
                                @RequestParam(required = true) String area,
                                @RequestParam(required = true) int level,
                                @RequestParam(required = true) String index) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -143,7 +159,13 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/lowlevel_increment")
    @ResponseBody
    public String getIndexLowLevelIncrement(String startDate, String endDate, String area, int level, String index, int sort, String lowLevel) {
    public String getIndexLowLevelIncrement(@RequestParam(required = true)String startDate,
                                            @RequestParam(required = true)String endDate,
                                            @RequestParam(required = true) String area,
                                            @RequestParam(required = true) int level,
                                            @RequestParam(required = true) String index,
                                            @RequestParam(required = true)int sort,
                                            @RequestParam(required = false)String lowLevel) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -170,7 +192,12 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/lowlevel_total")
    @ResponseBody
    public String getIndexLowLevelTotal(String endDate, String area, int level, String index, int sort, String lowLevel) {
    public String getIndexLowLevelTotal(@RequestParam(required = true)String endDate,
                                        @RequestParam(required = true)String area,
                                        @RequestParam(required = true)int level,
                                        @RequestParam(required = true)String index,
                                        @RequestParam(required = true)int sort,
                                        @RequestParam(required = false)String lowLevel) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -198,7 +225,11 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/leveltwo_increment")
    @ResponseBody
    public String getIndexLevelTwoIncrement(String startDate, String endDate, String area, int level, String index) {
    public String getIndexLevelTwoIncrement(@RequestParam(required = false)String startDate,
                                            @RequestParam(required = true)String endDate,
                                            @RequestParam(required = true)String area,
                                            @RequestParam(required = true)int level,
                                            @RequestParam(required = true)String index) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -225,19 +256,26 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping(value = "/sign_info")
    @ResponseBody
    public String getAreaSignInfo(String endDate, String area, int level) {
    public String getAreaSignInfo(@RequestParam(required = true)String endDate,
                                  @RequestParam(required = true)String area,
                                  @RequestParam(required = true)int level,
                                  @RequestParam(required = false) String lowCode) {
        try {
            JSONObject result = new JSONObject();
            long sign = statisticsAllService.getIndexTotal(endDate, area, level, "13");
            long weiJf = statisticsAllService.getWeiJiaoFei(endDate, area, level);
            JSONObject signRate = statisticsAllService.getSignRate(endDate, area, level);
            JSONObject signTaskRate = statisticsAllService.getSignTaskRate(endDate, area, level);
            result.put("sign", sign);
            result.put("expenses", weiJf);
            result.put("signRate", signRate);
            result.put("signTaskRate", signTaskRate);
            if (StringUtils.isEmpty(lowCode)) {
                long sign = statisticsAllService.getIndexTotal(endDate, area, level, "13");
                long weiJf = statisticsAllService.getWeiJiaoFei(endDate, area, level);
                JSONObject signRate = statisticsAllService.getSignRate(endDate, area, level);
                JSONObject signTaskRate = statisticsAllService.getSignTaskRate(endDate, area, level);
                result.put("sign", sign);
                result.put("expenses", weiJf);
                result.put("signRate", signRate);
                result.put("signTaskRate", signTaskRate);
            } else {
                result = statisticsAllService.getGroupInfo(endDate, lowCode, area, level);
            }
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
@ -257,7 +295,9 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping(value = "/sixfive_statistics")
    @ResponseBody
    public String getSixFiveStatistics(String startDate, String endDate, String area, int level) {
    public String getSixFiveStatistics(@RequestParam(required = false)String startDate,
                                       @RequestParam(required = true)String endDate,
                                       @RequestParam(required = true)String area, int level) {
        try {
            JSONArray result = statisticsAllService.getSixFiveStatistics(endDate, area, level);
@ -281,14 +321,20 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping(value = "/interval_total")
    @ResponseBody
    public String indexIntervalTotal(String startDate, String endDate, int interval, String area, int level, String index) {
    public String indexIntervalTotal(@RequestParam(required = true)String startDate,
                                     @RequestParam(required = true)String endDate,
                                     @RequestParam(required = true)int interval,
                                     @RequestParam(required = true)String area,
                                     @RequestParam(required = true)int level,
                                     @RequestParam(required = true)String index,
                                     @RequestParam(required = false) String lowCode) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
            if (index != null) {
                for (String idx : indexes) {
                    result.put("index_" + idx, statisticsAllService.getDateTotal(startDate, endDate, interval, area, level, idx));
                    result.put("index_" + idx, statisticsAllService.getDateTotal(startDate, endDate, interval, area, level, idx, lowCode));
                }
            }
@ -310,13 +356,23 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/lowlevel_all")
    @ResponseBody
    public String getIndexLowLevelTotalSign(String date, String area, int level, String index, int sort, String lowLevel) {
    public String getIndexLowLevelTotalSign(@RequestParam(required = true)String date,
                                            @RequestParam(required = true)String area,
                                            @RequestParam(required = true)int level,
                                            @RequestParam(required = true)String index,
                                            @RequestParam(required = true)int sort,
                                            @RequestParam(required = false)String lowLevel,
                                            @RequestParam(required = false) String lowCode) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
            for (String idx : indexes) {
                result.put("index_" + idx, statisticsAllService.getLowLevelTotal(date, area, level, idx, sort, lowLevel));
            if (StringUtils.isNotEmpty(lowCode)) {
                result.put("index_" + index, statisticsAllService.getLevelTwoLowLevelTotal(date, area, level, index, sort, lowLevel, lowCode));
            } else {
                for (String idx : indexes) {
                    result.put("index_" + idx, statisticsAllService.getLowLevelTotal(date, area, level, idx, sort, lowLevel));
                }
            }
            return write(200, "查询成功", "data", result);
@ -337,7 +393,10 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping(value = "/leveltwo_all")
    @ResponseBody
    public String getIndexLevelTwoTotal(String date, String area, int level, String index) {
    public String getIndexLevelTwoTotal(@RequestParam(required = true)String date,
                                        @RequestParam(required = true)String area,
                                        @RequestParam(required = true)int level,
                                        @RequestParam(required = true)String index) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -364,7 +423,10 @@ public class StatisticsController extends BaseController {
     */
    @RequestMapping("/index_all")
    @ResponseBody
    public String getIndexAll(String endDate, String area, int level, String index) {
    public String getIndexAll(@RequestParam(required = true)String endDate,
                              @RequestParam(required = true)String area,
                              @RequestParam(required = true)int level,
                              @RequestParam(required = true)String index) {
        try {
            String[] indexes = index.split(",");
            JSONObject result = new JSONObject();
@ -379,4 +441,5 @@ public class StatisticsController extends BaseController {
            return error(-1, "查询失败");
        }
    }
}

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

@ -90,9 +90,9 @@ weixin_websocket_server = http://172.19.103.76:8000/user/senddata.do
#file upload temp path
upload_temp_path=/var/local/temp
#image store path
image_server=http://172.19.103.87:8882/res/images/
voice_server=http://172.19.103.87:8882/res/voice/
chat_server=http://172.19.103.87:8882/res/chat/
image_server=http://weixin.xmtyw.cn/res/images/
voice_server=http://weixin.xmtyw.cn/res/voice/
chat_server=http://weixin.xmtyw.cn/res/chat/
image_path=/var/local/upload/images
voice_path=/var/local/upload/voice
chat_file_path=/var/local/upload/chat
@ -203,7 +203,7 @@ guahao_url = http://www.xmsmjk.com/UrpNetService/ReservationNet.asmx
guahao_namespace = http://www.zysoft.com.cn/
#EHRµµ°¸·þÎñµØÖ·
ehr_used = true
ehr_used = false
ehr_services = http://localhost:9009/api/v1.0/
ehr_services_base = http://localhost:10220/api/v1.0/

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

@ -3,21 +3,26 @@
   {
	  "name":"家庭医生",
	  "sub_button":[
		 {
			   "type":"view",
			   "name":"签约管理",
			   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fqygl%2fhtml%2fsigning-doctors.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%2fqygl%2fhtml%2fsigning-doctors.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%2fyszx%2fhtml%2fdoctor-consultation.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%2fyszd%2fhtml%2fdoctor-guidance.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%2fjkjy%2fhtml%2farticle_list.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
          }
	  ]
   },

+ 8 - 8
patient-co-wlyy/src/main/webapp/WEB-INF/web.xml

@ -53,14 +53,14 @@
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping> -->
  <filter>
    <filter-name>sitemeshFilter</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sitemeshFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--<filter>-->
    <!--<filter-name>sitemeshFilter</filter-name>-->
    <!--<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>-->
  <!--</filter>-->
  <!--<filter-mapping>-->
    <!--<filter-name>sitemeshFilter</filter-name>-->
    <!--<url-pattern>/*</url-pattern>-->
  <!--</filter-mapping>-->
  <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>