소스 검색

Merge branch 'dev' of chenweida/patient-co-management into dev

chenweida 8 년 전
부모
커밋
8ffacea40d
100개의 변경된 파일0개의 추가작업 그리고 12305개의 파일을 삭제
  1. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/1.png
  2. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/2.png
  3. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/3.png
  4. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/4.png
  5. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/5.png
  6. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/6.png
  7. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/7.png
  8. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/8.png
  9. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot项目启动的2种方式.docx
  10. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/1.png
  11. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/10.png
  12. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/11.png
  13. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/12.png
  14. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/13.png
  15. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/2.png
  16. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/3.png
  17. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/4.png
  18. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/5.png
  19. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/6.png
  20. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/7.png
  21. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/8.png
  22. BIN
      patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/9.png
  23. BIN
      patient-co/patient-co-wlyy-job/doc/接口文档/厦门i健康API文档.docx
  24. 0 10
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/00.readme.txt
  25. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/HBuilder使用该证书打包的例子.png
  26. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/aps推送证书.p12
  27. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/xmijkPro.mobileprovision
  28. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/证书.p12
  29. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/医生端通过HBuilder打包说明(草稿,完整版V0.2).docx
  30. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/发布修改参数.docx
  31. 0 10
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/00.readme.txt
  32. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/20160721170424_该证书的生成命令.png
  33. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/HBuilder使用该证书打包的例子.png
  34. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/ssgg_doctor.keystore
  35. 0 5
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/文档.txt
  36. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/im/im.docx
  37. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/后台/tomcat部署.docx
  38. BIN
      patient-co/patient-co-wlyy-job/doc/部署文档/正式库/微信端/微信端发布.docx
  39. 0 29
      patient-co/patient-co-wlyy-job/readme.MD
  40. 0 22
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/MvcConfig.java
  41. 0 1
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/entity/patient/Patient.java
  42. 0 58
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/BaseInterceptor.java
  43. 0 197
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/DoctorInterceptor.java
  44. 0 85
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/ObserverRequiredInterceptor.java
  45. 0 146
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java
  46. 0 141
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/UserInterceptor.java
  47. 0 103
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/logs/BusinessLogs.java
  48. 0 42
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/logs/InterfaceCallLogs.java
  49. 0 39
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/rest/RestException.java
  50. 0 55
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/rest/RestExceptionHandler.java
  51. 0 2
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/archives/PatientEventService.java
  52. 0 3
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  53. 0 3
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  54. 0 2
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/template/DoctorTeamGuidanceService.java
  55. 0 101
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java
  56. 0 69
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/model/BindCard.java
  57. 0 154
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/model/Charge.java
  58. 0 570
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/service/OnePayService.java
  59. 0 8
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/RSAUtils.java
  60. 0 360
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java
  61. 0 33
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/advert/AdvertController.java
  62. 0 43
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java
  63. 0 71
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/data/DataController.java
  64. 0 66
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java
  65. 0 46
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java
  66. 0 79
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java
  67. 0 63
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java
  68. 0 35
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java
  69. 0 313
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/im/imController.java
  70. 0 45
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java
  71. 0 399
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java
  72. 0 116
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java
  73. 0 52
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java
  74. 0 45
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java
  75. 0 108
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java
  76. 0 360
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java
  77. 0 333
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java
  78. 0 76
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java
  79. 0 66
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java
  80. 0 63
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/data/DataHandingService.java
  81. 0 75
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/data/DataHandlingController.java
  82. 0 1947
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java
  83. 0 217
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/archives/DoctorArchivesController.java
  84. 0 112
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/booking/DoctorBookingController.java
  85. 0 1107
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultController.java
  86. 0 280
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultMoviController.java
  87. 0 297
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultPublicController.java
  88. 0 146
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorEvaluateController.java
  89. 0 224
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java
  90. 0 860
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/discussion/DoctorDiscussionGroupController.java
  91. 0 88
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/family/DoctorFamilyController.java
  92. 0 97
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/feedback/DoctorFeedbackController.java
  93. 0 370
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/followup/DoctorFollowUpController.java
  94. 0 89
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/followup/DoctorFollowupDrugsController.java
  95. 0 295
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java
  96. 0 610
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java
  97. 0 305
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthGuidanceController.java
  98. 0 263
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthRecordController.java
  99. 0 296
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/intervene/DoctorInterveneController.java
  100. 0 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/medical/DoctorMedicalRecordController.java

BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/1.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/2.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/3.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/4.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/5.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/6.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/7.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot启动/8.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/boot项目启动的2种方式.docx


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/1.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/10.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/11.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/12.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/13.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/2.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/3.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/4.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/5.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/6.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/7.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/8.png


BIN
patient-co/patient-co-wlyy-job/doc/技术文档/IDEA操作/tomcat启动/9.png


BIN
patient-co/patient-co-wlyy-job/doc/接口文档/厦门i健康API文档.docx


+ 0 - 10
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/00.readme.txt

@ -1,10 +0,0 @@
----------------------------------
包名:
com.yihu.xmijk
证书密码:
111111
----------------------------------
develope.apple.com 账号:
chunyudang.yihu@gmail.com 
Jkzldangchunyu060201

BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/HBuilder使用该证书打包的例子.png


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/aps推送证书.p12


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/xmijkPro.mobileprovision


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/ios/证书.p12


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/医生端通过HBuilder打包说明(草稿,完整版V0.2).docx


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/发布修改参数.docx


+ 0 - 10
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/00.readme.txt

@ -1,10 +0,0 @@
----------------------------------
包名:
com.wjw.ssgg.doctor
证书别名:
ssgg_doctor.keystore
证书密码:
ssgg_doctor
----------------------------------

BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/20160721170424_该证书的生成命令.png


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/HBuilder使用该证书打包的例子.png


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/ssgg_doctor.keystore


+ 0 - 5
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/app/安卓/文档.txt

@ -1,5 +0,0 @@
upload_preview.js
common_http.js
im_new.js

BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/im/im.docx


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/后台/tomcat部署.docx


BIN
patient-co/patient-co-wlyy-job/doc/部署文档/正式库/微信端/微信端发布.docx


+ 0 - 29
patient-co/patient-co-wlyy-job/readme.MD

@ -1,29 +0,0 @@
项目中涉及到的框架
spring,springMVC,springJPA,springSecurity,springBoot
quartz,swagger-ui,hibernate,redis,fastDfs
项目包结构
doc 项目相关文档
src 代码
    main
        java
            com.yihu.wlyy
                aop 切面相关代码
                config 配置相关代码
                entity jpa 实体类相关代码
                event 事件相关代码
                exception 异常相关代码
                health 体征设备相关代码
                interceptors 拦截器相关代码
                job 任务相关代码
                logs 日志相关代码
                repository dao相关代码
                rest 
                service 服务类相关代码
                task 线程相关代码
                util 工具类相关代码
                web controller相关代码
                wechat 微信相关代码
        resource 资源和配置文件
        webapp  web相关代码

+ 0 - 22
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/MvcConfig.java

@ -1,10 +1,5 @@
package com.yihu.wlyy.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.interceptors.DoctorInterceptor;
import com.yihu.wlyy.interceptors.PatientInterceptor;
import com.yihu.wlyy.interceptors.UserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
@ -19,24 +14,7 @@ import java.util.List;
 */
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private DoctorInterceptor doctorInterceptor;
    @Autowired
    private PatientInterceptor patientInterceptor;
    @Autowired
    private UserInterceptor userInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(doctorInterceptor).addPathPatterns("/doctor/**","/statistics/province/**","/statistics/**");
        registry.addInterceptor(patientInterceptor).addPathPatterns("/patient/**");
        registry.addInterceptor(userInterceptor).addPathPatterns("/user/**");
        super.addInterceptors(registry);
    }
//    /**
//     * 为null的数据不返回
//     * @param converters

+ 0 - 1
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/entity/patient/Patient.java

@ -3,7 +3,6 @@ package com.yihu.wlyy.entity.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabelInfo;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;

+ 0 - 58
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/BaseInterceptor.java

@ -1,58 +0,0 @@
package com.yihu.wlyy.interceptors;
import javax.servlet.http.HttpServletRequest;
import com.yihu.wlyy.repository.url.CudUrlDao;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import com.yihu.wlyy.repository.security.TokenDao;
abstract public class BaseInterceptor implements HandlerInterceptor {
	private Logger logger= LoggerFactory.getLogger(BaseInterceptor.class);
	@Autowired
	public TokenDao tokenDao;
	@Autowired
	public CudUrlDao cudUrlDao;
	public JSONObject getAgent(HttpServletRequest request) {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			logger.info("userAgent:" + userAgent);
			return new JSONObject(userAgent);
		} catch (Exception e) {
			return null;
		}
	}
	public String error(int code, String msg) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			return json.toString();
		} catch (Exception e) {
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			return json.toString();
		} catch (Exception e) {
			return null;
		}
	}
}

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

@ -1,197 +0,0 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.entity.url.CudUrl;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
/**
 * 医生权限校验
 *
 * @author George
 */
@Component
public class DoctorInterceptor extends BaseInterceptor {
    private Logger logger = LoggerFactory.getLogger(DoctorInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        try {
            request.setCharacterEncoding("UTF-8");
            request.setAttribute("log-start", new Date().getTime());
            response.setCharacterEncoding("UTF-8");
            JSONObject json = getAgent(request);
            if (json == null) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
                return false;
            }
            if (json.has("uid") && json.has("admin_token") && StringUtils.isNotEmpty(json.getString("admin_token"))) {
                String adminToken = SystemConf.getInstance().getSystemProperties().getProperty("admin_token");
                String adminUid = SystemConf.getInstance().getSystemProperties().getProperty("admin_uid");
                if (json.getString("uid").equals(adminUid) && json.getString("admin_token").equals(adminToken)) {
                    return true;
                }
            }
            String tokenStr = json.has("token") ? json.getString("token") : "";
            String uid = json.has("uid") ? json.getString("uid") : "";
            String imei = json.has("imei") ? json.getString("imei") : "";
            String observer = json.has("observer") ? json.getString("observer") : "";
            Integer platform = json.has("platform") ? json.getInt("platform") : 2;
            logger.debug("tokenStr:"+tokenStr);
            logger.debug("uid:"+uid);
            logger.debug("imei:"+imei);
            logger.debug("observer:"+observer);
            logger.debug("platform:"+platform);
            //如果是观察者直接返回true
            if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
                Class cls = ((HandlerMethod) handler).getBeanType();
                RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
                Method method = ((HandlerMethod) handler).getMethod();
                RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
                String url = "";
                String urlCls = "";
                String urlMth = "";
                if (clsRm.value() != null && clsRm.value().length > 0) {
                    urlCls = clsRm.value()[0];
                }
                if (mthRm.value() != null && mthRm.value().length > 0) {
                    urlMth = mthRm.value()[0];
                }
                if (StringUtils.isNotEmpty(urlCls)) {
                    url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
                }
                if (StringUtils.isNotEmpty(urlMth)) {
                    url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
                }
                url = url.replace("\\", "/").replace("//", "/");
                CudUrl cudUrl = cudUrlDao.findByUrl(url);
                if (url.equals("/doctor/consult/readed")) {
                    response.getOutputStream().write(write(200, "操作成功").getBytes());
                    return false;
                }
                if (cudUrl != null) {
                    if (StringUtils.isNotEmpty(cudUrl.getMethod()) &&
                            request.getMethod().toUpperCase().compareTo(cudUrl.getMethod()) != 0) {
                        return true;
                    } else {
                        response.getOutputStream().write(error(403, "该操作没有权限").getBytes());
                        return false;
                    }
                }
                return true;
            }
            if (StringUtils.isEmpty(tokenStr) || StringUtils.isEmpty(imei) || StringUtils.isEmpty(uid)) {
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
                return false;
            }
            Token token = null;
            Map<String, Token> tempMap = null;
            if (platform == 2) {
                tempMap = SystemData.doctorTokens;
            } else {
                tempMap = SystemData.doctorPCTokens;
            }
            token = tempMap.get(uid);
            if (token == null) {
                token = tokenDao.findByPatient(uid, platform);
                if (token != null) {
                    // 加入缓存
                    tempMap.put(uid, token);
                }
            }
            if (token == null || token.getPlatform() != 2) {
                // 未登录
                response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
                flag = false;
            } else {
                if (token.getTimeout().getTime() < new Date().getTime()) {
                    // 登录超时
                    response.getOutputStream().write(error(SystemConf.LOGIN_TIMEOUT, "登录超时,请重新登录").getBytes());
                    flag = false;
                } else if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
                    // 别处登录
                    response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录,请重新登录").getBytes());
                    flag = false;
                } else {
                    // 一天只更新一次
                    if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
                        // 今天未更新,则更新缓存
                        token.setCzrq(new Date());
                        // 更新内存
                        tempMap.put(uid, token);
                        // 更新数据库
                        tokenDao.save(token);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (null == request.getAttribute("log-start")) {
            return;
        }
        long start = (long) request.getAttribute("log-start");
        long end = new Date().getTime();
        Class cls = ((HandlerMethod) handler).getBeanType();
        RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
        Method method = ((HandlerMethod) handler).getMethod();
        RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
        String url = "";
        String urlCls = "";
        String urlMth = "";
        if (clsRm.value() != null && clsRm.value().length > 0) {
            urlCls = clsRm.value()[0];
        }
        if (mthRm.value() != null && mthRm.value().length > 0) {
            urlMth = mthRm.value()[0];
        }
        if (StringUtils.isNotEmpty(urlCls)) {
            url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
        }
        if (StringUtils.isNotEmpty(urlMth)) {
            url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
        }
        url = url.replace("\\", "/").replace("//", "/");
        JSONObject json = getAgent(request);
        String uid = json.has("uid") ? json.getString("uid") : "";
        InterfaceCallLogs.info(end - start, url, uid, new JSONObject(request.getParameterMap()).toString());
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

+ 0 - 85
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/ObserverRequiredInterceptor.java

@ -1,85 +0,0 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.aop.ObserverRequired;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
 * Created by Trick on 2017/6/24.
 */
public class ObserverRequiredInterceptor  implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object[] ars = mi.getArguments();
        HttpServletRequest request =null;
        HttpServletResponse response = null;
        for(Object o :ars){
            if(o instanceof HttpServletRequest){
                request = (HttpServletRequest) o;
            }
            if(o instanceof HttpServletResponse){
                response = (HttpServletResponse) o;
            }
        }
        if(request!=null&&response!=null){
            JSONObject json = getAgent(request);
            String tokenStr = json.has("token") ? json.getString("token") : "";
            String uid = json.has("uid") ? json.getString("uid") : "";
            String imei = json.has("imei") ? json.getString("imei") : "";
            String observer = json.has("observer") ? json.getString("observer") : "";
            //if(StringUtils.isNotBlank(observer)&&"1".equals(observer)){
                if(mi.getMethod().isAnnotationPresent(ObserverRequired.class)){
                    System.out.println("----------this method is added @ObserverRequired-------------------------");
                    response.getOutputStream().write(error(403, "该操作没有权限").getBytes());
                    return null;
                }
            //}
        }
        //执行被拦截的方法,切记,如果此方法不调用,则被拦截的方法不会被执行。
        return mi.proceed();
    }
    public JSONObject getAgent(HttpServletRequest request) {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            System.out.println("userAgent:" + userAgent);
            return new JSONObject(userAgent);
        } catch (Exception e) {
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public String error(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
}

+ 0 - 146
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/PatientInterceptor.java

@ -1,146 +0,0 @@
package com.yihu.wlyy.interceptors;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
/**
 * 患者权限校验
 * @author George
 *
 */
@Component
public class PatientInterceptor extends BaseInterceptor {
	private Logger logger = LoggerFactory.getLogger(PatientInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		boolean flag = true;
		try {
			request.setCharacterEncoding("UTF-8");
			request.setAttribute("log-start", new Date().getTime());
			if(request.getRequestURI().contains("/patient/hosptail/getHositalByTownCode")||request.getRequestURI().contains("/patient/feedback/saveAppeal")){
				return true;
			}
			response.setCharacterEncoding("UTF-8");
			JSONObject json = getAgent(request);
			logger.debug("userAgent:"+json);
			if (json == null) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
				return false;
			}
			String tokenStr = json.has("token") ? json.getString("token") : "";
			String user = json.has("uid") ? json.getString("uid") : "";
			String imei = json.has("imei") ? json.getString("imei") : "";
			String openid = json.has("openid") ? json.getString("openid") : "";
			int platform = json.has("platform") ? json.getInt("platform") : 1;
			logger.debug("tokenStr:"+tokenStr);
			logger.debug("uid:"+user);
			logger.debug("imei:"+imei);
			logger.debug("openid:"+openid);
			logger.debug("platform:"+platform);
			if (StringUtils.isEmpty(imei)) {
				imei = openid;
			}
			Token token = null;
			if (platform == 1) {
				token = SystemData.patientTokens.get(user);
			} else if (platform == 3) {
				token = SystemData.wxPatientTokens.get(user);
			}
			if (token == null) {
				token = tokenDao.findByPatient(user, platform);
				// 加入缓存
				if (platform == 1) {
					SystemData.patientTokens.put(user, token);
				} else if (platform == 3) {
					SystemData.wxPatientTokens.put(user, token);
				}
			}
			if (token == null || StringUtils.isEmpty(tokenStr) || (token.getPlatform() != 1 && token.getPlatform() != 3)) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
				flag = false;
			} else {
				if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(user, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
					// 别处登录
					response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录,请重新登录").getBytes());
					flag = false;
				} else {
					// 一天只更新一次
					if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
						// 今天未更新,则更新缓存
						token.setCzrq(new Date());
						// 更新内存
						if (platform == 1) {
							SystemData.patientTokens.put(user, token);
						} else if (platform == 3) {
							SystemData.wxPatientTokens.put(user, token);
						}
						// 更新数据库
						tokenDao.save(token);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if(null==request.getAttribute("log-start")){
			return;
		}
		long start = (long) request.getAttribute("log-start");
		long end = new Date().getTime();
		Class cls = ((HandlerMethod) handler).getBeanType();
		RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
		Method method = ((HandlerMethod) handler).getMethod();
		RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
		String url = "";
		String urlCls = "";
		String urlMth = "";
		if (clsRm.value() != null && clsRm.value().length > 0) {
			urlCls = clsRm.value()[0];
		}
		if (mthRm.value() != null && mthRm.value().length > 0) {
			urlMth = mthRm.value()[0];
		}
		if (StringUtils.isNotEmpty(urlCls)) {
			url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
		}
		if (StringUtils.isNotEmpty(urlMth)) {
			url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
		}
		url = url.replace("\\", "/").replace("//", "/");
		JSONObject json = getAgent(request);
		String uid = json.has("uid") ? json.getString("uid") : "";
		InterfaceCallLogs.info(end - start, url, uid, new JSONObject(request.getParameterMap()).toString());
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
}

+ 0 - 141
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/interceptors/UserInterceptor.java

@ -1,141 +0,0 @@
package com.yihu.wlyy.interceptors;
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yihu.wlyy.logs.InterfaceCallLogs;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.SystemData;
/**
 * 公共方法,权限简单校验
 * @author George
 *
 */
@Component
public class UserInterceptor extends BaseInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try {
			request.setCharacterEncoding("UTF-8");
			request.setAttribute("log-start", new Date().getTime());
			response.setCharacterEncoding("UTF-8");
			JSONObject json = getAgent(request);
			if (json == null) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
				return false;
			}
			// 获取用户token
			String tokenStr = json.has("token") ? json.getString("token") : "";
			String uid = json.has("uid") ? json.getString("uid") : "";
			String imei = json.has("imei") ? json.getString("imei") : "";
			String openid = json.has("openid") ? json.getString("openid") : "";
			if (StringUtils.isEmpty(imei)) {
				imei = openid;
			}
			Token token = null;
			if (SystemData.doctorTokens.containsKey(uid)) {
				token = SystemData.doctorTokens.get(uid);
			} else if (SystemData.patientTokens.containsKey(uid)) {
				token = SystemData.patientTokens.get(uid);
			} else if (SystemData.wxPatientTokens.containsKey(uid)) {
				token = SystemData.wxPatientTokens.get(uid);
			}
			if (token == null) {
				token = tokenDao.findByToken(tokenStr);
				if (token != null) {
					switch (token.getPlatform()) {
					case 1:
						SystemData.patientTokens.put(uid, token);
						break;
					case 2:
						SystemData.doctorTokens.put(uid, token);
						break;
					case 3:
						SystemData.wxPatientTokens.put(uid, token);
						break;
					}
				}
			}
			if (token == null) {
				// 未登录
				response.getOutputStream().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!").getBytes());
				return false;
			} else {
				if (token.getTimeout().getTime() < new Date().getTime()) {
					// 登录超时
					response.getOutputStream().write(error(SystemConf.LOGIN_TIMEOUT, "登录超时,请重新登录").getBytes());
					return false;
				} else if (!StringUtils.equals(tokenStr, token.getToken()) || !StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
					// 别处登录
					response.getOutputStream().write(error(SystemConf.LOGIN_OTHER, "帐号在别处登录,请重新登录").getBytes());
					return false;
				} else {
					// 一天只更新一次
					if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
						// 今天未更新,则更新缓存
						token.setCzrq(new Date());
						// 更新内存
						SystemData.doctorTokens.put(uid, token);
						// 更新数据库
						tokenDao.save(token);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		long start = (long) request.getAttribute("log-start");
		long end = new Date().getTime();
		Class cls = ((HandlerMethod) handler).getBeanType();
		RequestMapping clsRm = (RequestMapping) cls.getAnnotation(RequestMapping.class);
		Method method = ((HandlerMethod) handler).getMethod();
		RequestMapping mthRm = method.getAnnotation(RequestMapping.class);
		String url = "";
		String urlCls = "";
		String urlMth = "";
		if (clsRm.value() != null && clsRm.value().length > 0) {
			urlCls = clsRm.value()[0];
		}
		if (mthRm.value() != null && mthRm.value().length > 0) {
			urlMth = mthRm.value()[0];
		}
		if (StringUtils.isNotEmpty(urlCls)) {
			url += urlCls.startsWith("/") ? urlCls : ("/" + urlCls);
		}
		if (StringUtils.isNotEmpty(urlMth)) {
			url += urlMth.startsWith("/") ? urlMth : ("/" + urlMth);
		}
		url = url.replace("\\", "/").replace("//", "/");
		JSONObject json = getAgent(request);
		String uid = json.has("uid") ? json.getString("uid") : "";
		InterfaceCallLogs.info(end - start, url, uid, new JSONObject(request.getParameterMap()).toString());
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
}

+ 0 - 103
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/logs/BusinessLogs.java

@ -1,103 +0,0 @@
package com.yihu.wlyy.logs;
import com.yihu.wlyy.util.DateUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 业务日志输出
 * <p>
 * Created by lyr-pc on 2017/1/19.
 */
public class BusinessLogs {
    // 日志输出
    private static Logger logger = LoggerFactory.getLogger(BusinessLogs.class);
    /**
     * 业务类型
     */
    public enum BusinessType {
        // 咨询
        consult
        // 指导
        , guidance
        // 健康教育
        , article
        // 随访
        , followup
        // 预约
        , appointment
        // 标签
        , label
        // 注册
        , register
        // 健康档案
        , archive
        // 签约
        , sign
        // 指标
        , index
    }
    /**
     * 业务日志输出
     *
     * @param type 业务类别
     * @param info 日志信息
     */
    public static void info(BusinessType type, String caller,String user, JSONObject info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 2);
            log.put("caller", caller);
            JSONObject data = new JSONObject();
            data.put("businessType", type.ordinal());
            data.put("patient", user);
            data.put("data", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 业务日志输出
     *
     * @param type 业务类别
     * @param info 日志信息
     */
    public static void info(BusinessType type,String caller, String user, JSONArray info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 2);
            log.put("caller", caller);
            JSONObject data = new JSONObject();
            data.put("businessType", type.ordinal());
            data.put("patient", user);
            data.put("data", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 0 - 42
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/logs/InterfaceCallLogs.java

@ -1,42 +0,0 @@
package com.yihu.wlyy.logs;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by lyr-pc on 2017/1/22.
 */
public class InterfaceCallLogs {
    // 日志输出
    private static Logger logger = LoggerFactory.getLogger(InterfaceCallLogs.class);
    /**
     * 接口调用日志输出
     *
     * @param info 日志信息
     */
    public static void info(long time, String url, String user, String info) {
        try {
            JSONObject log = new JSONObject();
            log.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date()));
            log.put("logType", 1);
            log.put("caller", user);
            JSONObject data = new JSONObject();
            data.put("responseTime", time);
            data.put("url", url);
            data.put("params", info);
            log.put("data", data);
            logger.info(log.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 0 - 39
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/rest/RestException.java

@ -1,39 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.rest;
import org.springframework.http.HttpStatus;
/**
 * 专用于Restful Service的异常.
 * 
 * @author calvin
 */
public class RestException extends RuntimeException {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6603105449344479863L;
	
	public HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
	public RestException() {
	}
	public RestException(HttpStatus status) {
		this.status = status;
	}
	public RestException(String message) {
		super(message);
	}
	public RestException(HttpStatus status, String message) {
		super(message);
		this.status = status;
	}
}

+ 0 - 55
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/rest/RestExceptionHandler.java

@ -1,55 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.rest;
import java.util.Map;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springside.modules.beanvalidator.BeanValidators;
import org.springside.modules.mapper.JsonMapper;
import org.springside.modules.web.MediaTypes;
/**
 * 自定义ExceptionHandler,专门处理Restful异常.
 * 
 * @author calvin
 */
// 会被Spring-MVC自动扫描,但又不属于Controller的annotation。
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
	private JsonMapper jsonMapper = new JsonMapper();
	/**
	 * 处理RestException.
	 */
	@ExceptionHandler(value = { RestException.class })
	public final ResponseEntity<?> handleException(RestException ex, WebRequest request) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
		return handleExceptionInternal(ex, ex.getMessage(), headers, ex.status, request);
	}
	/**
	 * 处理JSR311 Validation异常.
	 */
	@ExceptionHandler(value = { ConstraintViolationException.class })
	public final ResponseEntity<?> handleException(ConstraintViolationException ex, WebRequest request) {
		Map<String, String> errors = BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations());
		String body = jsonMapper.toJson(errors);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
		return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
	}
}

+ 0 - 2
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/archives/PatientEventService.java

@ -3,7 +3,6 @@ package com.yihu.wlyy.service.app.archives;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.patient.PatientEvent;
import com.yihu.wlyy.entity.patient.PatientEventImg;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.patient.PatientEventDao;
import com.yihu.wlyy.repository.patient.PatientEventImgDao;
import com.yihu.wlyy.util.DateUtil;
@ -128,7 +127,6 @@ public class PatientEventService {
            }
            patientEventImgDao.save(imgList);
        }
        BusinessLogs.info(BusinessLogs.BusinessType.archive, caller, es.getPatient(), new JSONObject(es));
    }
    /**

+ 0 - 3
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java

@ -8,7 +8,6 @@ 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.entity.patient.SignFamily;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientGroupInfoDao;
import com.yihu.wlyy.repository.doctor.SignPatientLabelDao;
@ -1224,7 +1223,6 @@ public class SignPatientLabelInfoService extends BaseService {
            }
        }
        BusinessLogs.info(BusinessLogs.BusinessType.label, caller, patient, logArray);
        return 1;
    }
@ -1453,7 +1451,6 @@ public class SignPatientLabelInfoService extends BaseService {
            }
        }
        BusinessLogs.info(BusinessLogs.BusinessType.label, caller, patient, logArray);
        return 1;
    }

+ 0 - 3
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java

@ -13,7 +13,6 @@ import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.dict.SystemDictDao;
@ -1179,7 +1178,6 @@ public class FamilyContractService extends BaseService {
            ImUtill.sendImMsg(doc.getCode(), doc.getName(), patient.getCode() + "_" + sf.getTeamCode() + "_" + 2, "0", "家庭医生代理签约成功!", "1");
        }
        BusinessLogs.info(BusinessLogs.BusinessType.sign, signDoctorCode, sf.getPatient(), new JSONObject(sf));
        return temp;
    }
@ -1523,7 +1521,6 @@ public class FamilyContractService extends BaseService {
            ImUtill.sendImMsg(doc.getCode(), doc.getName(), patient.getCode() + "_" + sf.getTeamCode() + "_" + 2, "0", "家庭医生签约成功!", "1");
        }
        result.put("status", 1);
        BusinessLogs.info(BusinessLogs.BusinessType.sign, caller, sf.getPatient(), new JSONObject(sf));
        return result;
    }

+ 0 - 2
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/template/DoctorTeamGuidanceService.java

@ -7,7 +7,6 @@ import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
import com.yihu.wlyy.entity.template.DoctorTeamGuidanceDetail;
import com.yihu.wlyy.entity.template.DoctorTeamGuidanceTemplate;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamMemberDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
@ -386,7 +385,6 @@ public class DoctorTeamGuidanceService extends BaseService {
            Patient p = patientDao.findByCode(patient);
            String imcotent = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\"" + CommonUtil.getSubString(guidance.getContent(), 0, 30) + "\"}";
            consultService.sendMucMessageBySingnType(dc, doctor.getName(), patient, imcotent, "4", p.getName());
            BusinessLogs.info(BusinessLogs.BusinessType.guidance, dc, patient, new JSONObject(guidance));
            //发送成功记录模板发送次数
            doctorTeamGuidanceTemplateDao.countSend(teamId, guidanceCode);
        }

+ 0 - 101
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/common/Configure.java

@ -1,101 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.common;
import org.springframework.context.annotation.Configuration;
/**
 * User: hzp
 * Date: 20170518
 * 这里放置各种配置数据
 */
@Configuration
public class Configure {
	/******************************* 易联众统一支付平台 ***********************************************************/
//	private String onepayApi = "http://120.42.37.94:1301/onepay-web/";
//	private String onepayAppId = "1BGKM1UHM03P7B2CA8C000005626EB0E";
//	private String onepayAppSecret = "1BGKM1UHM03I7B2CA8C00000AB682E9A";
//			开发环境应用信息
//	private String onepayApi = "https://xmhealth.ylzpay.com:8080/";
	private String onepayApi = "http://xmhealth.ylzpay.com:8070/";
	private String onepayAppId = "1BLF5SEGN00087165F0A000027362BE5";
	private String onepayAppSecret = "1BLF5SCBO01V3E78A8C00000F3A0FFE7";
	private String bindCardType = "onepay.sicard.bind.info";
	private String chargeType = "onepay.trade.medical.charge";
	private String chargeQueryType = "onepay.trade.medical.charge.query";
	private String createSicardType = "onepay.sicard.createurl";
//	易联众异步回调
	private String receiveNotify = "wlyy.onepay.receiveNotify";
	private String returnUrl = "wlyy.onepay.returnUrl";
	public String getReturnUrl() {
		return returnUrl;
	}
	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
	public String getReceiveNotify() {
		return receiveNotify;
	}
	public void setReceiveNotify(String receiveNotify) {
		this.receiveNotify = receiveNotify;
	}
	public String getOnepayApi() {
		return onepayApi;
	}
	public String getOnepayAppId() {
		return onepayAppId;
	}
	public String getOnepayAppSecret() {
		return onepayAppSecret;
	}
	public String getBindCardType() {
		return bindCardType;
	}
	public String getChargeType() {
		return chargeType;
	}
	public String getChargeQueryType() {
		return chargeQueryType;
	}
	public String getCreateSicardType() {
		return createSicardType;
	}
	/******************* 微信社保支付配置 ******************************************/
	//这个就是自己要保管好的私有Key了(切记只能放在自己的后台代码里,不能放在任何可能被看到源代码的客户端程序中)
	// 每次自己Post数据给API的时候都要用这个key来对所有字段进行签名,生成的签名会放在Sign这个字段,API收到Post数据的时候也会用同样的签名算法对Post过来的数据进行签名和验证
	// 收到API的返回的时候也要用这个key来对返回的数据算下签名,跟API的Sign数据进行比较,如果值不一致,有可能数据被第三方给篡改
	private String key = "2935b54b53a957d9516c920a544f2537";
	//微信分配的公众号ID(开通公众号之后可以获取到)
	private String appID = "wxd03f859efdf0873d";
	public String getKey(){
		return key;
	}
	public String getAppid(){
		return appID;
	}
	//获取token地址
	public String TOKEN_API = "https://api.weixin.qq.com/payinsurance/gettoken";
	//挂号/诊间支付统一下单 API 接口
	public String ORDER_API = "https://api.weixin.qq.com/payinsurance/unifiedorder?access_token ACCESS_TOKEN";
}

+ 0 - 69
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/model/BindCard.java

@ -1,69 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.service.third.httplog.LogService;
import com.yihu.wlyy.service.weixin.wxpay.common.Configure;
import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.domain.RequestParams;
import com.ylzinfo.onepay.sdk.domain.ResponseParams;
import com.ylzinfo.onepay.sdk.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
 * 社保卡绑定信息
 * add by hzp at 20170524
 */
public class BindCard {
    private String attachCardNo;
    private String attachIdType;
    private String attachIdNo;
    private String attachName;
    private String attachRelation;   //01配偶 02父母 03子女  98本人 99未知
    public String getAttachCardNo() {
        return attachCardNo;
    }
    public void setAttachCardNo(String attachCardNo) {
        this.attachCardNo = attachCardNo;
    }
    public String getAttachIdType() {
        return attachIdType;
    }
    public void setAttachIdType(String attachIdType) {
        this.attachIdType = attachIdType;
    }
    public String getAttachIdNo() {
        return attachIdNo;
    }
    public void setAttachIdNo(String attachIdNo) {
        this.attachIdNo = attachIdNo;
    }
    public String getAttachName() {
        return attachName;
    }
    public void setAttachName(String attachName) {
        this.attachName = attachName;
    }
    public String getAttachRelation() {
        return attachRelation;
    }
    public void setAttachRelation(String attachRelation) {
        this.attachRelation = attachRelation;
    }
}

+ 0 - 154
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/model/Charge.java

@ -1,154 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.model;
/**
 * 医保扣费
 * add by hzp at 20170524
 */
public class Charge {
    private String tradeStatus; //交易状态    0 成功 1 失败  2 已退款
    private String chargeNo;  //医保业务流水号
    private String chargeTime;  //  医保交易成功时间
    private String outChargeNo;  //  接入应用业务流水号
    private String outChargeTime;  //  接入应用内业务时间
    private String medOrgNo;  //  医疗机构编号
    private String medOrgName;  //  医疗机构名称
    private String billNo;  //  待结算费用单据号
    private String cardNo;  //  医保卡号
    private String totalAmount;  //  交易总金额
    private String insuranceAmount;  //  医保支付金额
    private String selfPayAmount;  //  自付金额
    private String userId;  // 用户openId
    private String userName;  // 用户姓名
    private String idType;  // 证件号码
    private String idNo;  // 证件类型
    //private String responseContent;  //扣费详情
    public String getTradeStatus() {
        return tradeStatus;
    }
    public void setTradeStatus(String tradeStatus) {
        this.tradeStatus = tradeStatus;
    }
    public String getChargeNo() {
        return chargeNo;
    }
    public void setChargeNo(String chargeNo) {
        this.chargeNo = chargeNo;
    }
    public String getChargeTime() {
        return chargeTime;
    }
    public void setChargeTime(String chargeTime) {
        this.chargeTime = chargeTime;
    }
    public String getOutChargeNo() {
        return outChargeNo;
    }
    public void setOutChargeNo(String outChargeNo) {
        this.outChargeNo = outChargeNo;
    }
    public String getOutChargeTime() {
        return outChargeTime;
    }
    public void setOutChargeTime(String outChargeTime) {
        this.outChargeTime = outChargeTime;
    }
    public String getMedOrgNo() {
        return medOrgNo;
    }
    public void setMedOrgNo(String medOrgNo) {
        this.medOrgNo = medOrgNo;
    }
    public String getMedOrgName() {
        return medOrgName;
    }
    public void setMedOrgName(String medOrgName) {
        this.medOrgName = medOrgName;
    }
    public String getBillNo() {
        return billNo;
    }
    public void setBillNo(String billNo) {
        this.billNo = billNo;
    }
    public String getCardNo() {
        return cardNo;
    }
    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }
    public String getTotalAmount() {
        return totalAmount;
    }
    public void setTotalAmount(String totalAmount) {
        this.totalAmount = totalAmount;
    }
    public String getInsuranceAmount() {
        return insuranceAmount;
    }
    public void setInsuranceAmount(String insuranceAmount) {
        this.insuranceAmount = insuranceAmount;
    }
    public String getSelfPayAmount() {
        return selfPayAmount;
    }
    public void setSelfPayAmount(String selfPayAmount) {
        this.selfPayAmount = selfPayAmount;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getIdType() {
        return idType;
    }
    public void setIdType(String idType) {
        this.idType = idType;
    }
    public String getIdNo() {
        return idNo;
    }
    public void setIdNo(String idNo) {
        this.idNo = idNo;
    }
}

+ 0 - 570
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/weixin/wxpay/service/OnePayService.java

@ -1,570 +0,0 @@
package com.yihu.wlyy.service.weixin.wxpay.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.organization.HospitalMapping;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.charge.ChargeDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.third.httplog.LogService;
import com.yihu.wlyy.service.weixin.wxpay.common.Configure;
import com.yihu.wlyy.service.weixin.wxpay.model.BindCard;
import com.yihu.wlyy.service.weixin.wxpay.model.Charge;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.wx.OnePayController;
import com.ylzinfo.onepay.sdk.OnepayDefaultClient;
import com.ylzinfo.onepay.sdk.domain.RequestParams;
import com.ylzinfo.onepay.sdk.domain.ResponseParams;
import com.ylzinfo.onepay.sdk.utils.DateUtil;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 易联众统一支付服务类
 * add by hzp at 20170523
 */
@Service
@Transactional
public class OnePayService {
    @Autowired
    private Configure config;
    @Autowired
    private LogService logService;
    private String signType = "MD5";
    private String encryptType = "AES";
    @Autowired
    private HospitalMappingDao hospitalMappingDao;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    ChargeDao chargeDao;
    @Autowired
    PatientDao patientDao;
    @Autowired
    SignFamilyDao signFamilyDao;
    @Autowired
    DoctorDao doctorDao;
    @Value("${server.server_url}")
    private String serverUrl;
    @Value("${wechat.accId}")
    private String accId;
    Properties systemConf = SystemConf.getInstance().getSystemProperties();
    private static final Logger LOGGER = LoggerFactory.getLogger(OnePayController.class);
    /**
     * 查询绑卡信息(本人)
     */
    public BindCard bindCard(String patient, String openid) throws Exception {
        BindCard card = ownerCard(openid);
        //更新患者信息
        if (card != null) {
            Patient p = patientDao.findByCode(patient);
            p.setOpenid(openid);
            p.setSsc(card.getAttachCardNo());
//            增加绑定电子社保卡信息
            p.setSicardStatus(1);
            if (p.getSicardTime() == null) {
                p.setSicardTime(new Date());
            }
            ;
            if (card.getAttachIdType() == "01")      //身份证
            {
                p.setIdcard(card.getAttachIdNo());
            }
            if (!card.getAttachName().equals(p.getName())) {
                System.out.print("姓名不一致,姓名:" + p.getName() + "  社保姓名:" + card.getAttachName());
            }
            patientDao.save(p);
        }
        return card;
    }
    /**
     * 查询绑卡信息(本人)
     */
    private BindCard ownerCard(String openid) throws Exception {
        BindCard re = null;
        List<BindCard> cardList = bindCardList(openid);
        //更新患者信息
        if (cardList != null && cardList.size() > 0) {
            for (BindCard card : cardList) {
                if ("98".equals(card.getAttachRelation())) {
                    re = card;
                    break;
                }
            }
        }
        return re;
    }
    /**
     * 查询绑卡信息(所有卡)
     */
    private List<BindCard> bindCardList(String openid) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        List<BindCard> result = new ArrayList<BindCard>();
        String appId = config.getOnepayAppId();
        String appSecret = config.getOnepayAppSecret();
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
        try {
            RequestParams requestParams = new RequestParams();
//            requestParams.setTransType();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
            requestParams.setAppId(appId);
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            // 请求报文体参数,详见接口文档各接口——请求参数定义
            // 如医保绑卡信息请求参数
            JSONObject params = new JSONObject();
            params.put("openId", openid);
            params.put("accId", accId); //微信公众号开发者ID
            requestParams.setParam(params);
            requestParams.setTransType(config.getBindCardType());
            msgBody = JSON.toJSONString(requestParams);
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            // 如医保卡绑卡信息返回参数
            if (OnepayDefaultClient.isSuccessful(res)) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, BindCard.class);
//                只返回了业务出参的附属绑卡情况 res.getRespCode()级别获取所有返回参数
                result = objectMapper.readValue(objectMapper.writeValueAsString(res.getParam().get("attachList")), javaType);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        //type=3易联众接口 保存http日志
        logService.saveHttpLog(isSuccess, config.getBindCardType(), "查询绑卡信息", "POST", null, msgBody, response, error, logService.onepayType);
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    /**
     * 家庭医生签约支付
     */
    public String charge(String orgCode, String chargeType, String chargeRelation, String totalAmount, String patient, String openid, String accessToken) throws Exception {
        //获取机构映射
        HospitalMapping hos = hospitalMappingDao.findByCode(orgCode);
        if (hos == null) {
            throw new Exception("no hospital mapping!");
        }
        return charge(orgCode, hos.getName(), hos.getAppId(), hos.getAppSecret(),hos.getSbCode(), chargeType, chargeRelation, totalAmount,patient, openid,accessToken);
//        对应机构的APPID和appsecret
//        return charge(orgCode, hos.getName(), "54BBAF5148521AC9E053F000660AC502", "54BBAF5148531AC9E053F000660AC502",hos.getSbCode(), chargeType, chargeRelation, totalAmount,patient, openid,accessToken);
//        return charge(orgCode, hos.getName(), "54BBAF5148521AC9E053F000660AC502", "54BBAF5148531AC9E053F000660AC502", "0380", chargeType, chargeRelation, totalAmount, patient, openid, accessToken);
    }
    /**
     * 家庭医生签约支付,成功则返回支付路径
     */
    private String charge(String orgCode, String orgName, String appId, String appSecret, String sbCode, String chargeType, String chargeRelation, String totalAmount, String patient, String openid, String accessToken) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = "";
        String channel = "WX_MMP";   //  医保支付渠道
        String subject = "家庭医生签约支付";   //  订单名称
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
//     未真正完成支付以前预存储支付信息到wlyy_charge表
        WlyyCharge charge = new WlyyCharge();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        charge.setChargeType(chargeType);   //交易类型
        charge.setChargeRelation(chargeRelation);  //交易关联代码 wlyy_sign_family字段code
        charge.setCode(uuid);  //  接入应用支付业务流水号
        Date now = new Date();
        charge.setCreateTime(now);
        charge.setPatient(patient);     //  用户
        charge.setOpenid(openid);     //  用戶微信openid
        try {
            charge.setHospital(orgCode);
            charge.setHospitalName(orgName);
            charge.setChannel(channel);
            charge.setMerchName(orgName);
            charge.setSubject(subject);
            charge.setTotalAmount(Integer.parseInt(totalAmount));  //  交易总金额
            BindCard card = ownerCard(openid);
            String name = card.getAttachName();
            String ssc = card.getAttachCardNo();
            String idType = card.getAttachIdType();
            String idNo = card.getAttachIdNo();
            charge.setName(name);
            charge.setIdType(idType);
            charge.setIdNo(idNo);
            charge.setSsc(ssc);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String currentDateTime = formatter.format(now);
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
            requestParams.setAppId(appId);
            requestParams.setTimestamp(currentDateTime);
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeType());
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", uuid);  //接入应用结算业务流水号
            params.put("outChargeTime", currentDateTime);    //接入应用内结算时间
            params.put("userId", openid);   //用户 ID
            params.put("cardNo", ssc);   //医保卡号"D64775061"
            //获取绑卡信息
            params.put("userName", name);
            params.put("idType", idType);
            params.put("idNo", idNo);
            params.put("totalAmount", totalAmount);   //交易总金额
            Properties systemConf = SystemConf.getInstance().getSystemProperties();
            String returnUrl = systemConf.getProperty("return_url");
            returnUrl = returnUrl.replace("{server}", serverUrl);
            params.put("returnUrl", returnUrl);   //页面跳转地址
            params.put("channel", channel);  //微信医保支付
            params.put("merchName", orgName);  //收款单位名称
            params.put("subject", subject);  //订单名称
            params.put("wxToken", accessToken);
            //extendParams 扩展入参
            //家庭医生签约信息
            //      根据签约code查询签约信息
            SignFamily signFamily = signFamilyDao.findByCode(chargeRelation);
            if (signFamily != null) {
//                //签约人Code
                String signDoctorCode = signFamily.getSignDoctorCode();
                String people = signFamily.getPatient();
                Doctor doctor = doctorDao.findByCode(signDoctorCode);
                Patient user = patientDao.findByCode(people);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                Map<String, String> familyContent = new HashMap<>();
//                familyContent.put("moRegNo", chargeRelation);//医院签约号限长20  signFamily code
                String moregNo = sdf.format(new Date())+ uuid.substring(0,6);
                familyContent.put("moRegNo", moregNo);//医院签约号限长20  signFamily code
                familyContent.put("moRegName",signFamily.getName()); //签约人姓名
//                familyContent.put("moRegName", "沈在鑫"); //签约人姓名
                familyContent.put("moRegAddr", user.getAddress()); //签约人地址
                familyContent.put("moRegTelephone", signFamily.getMobile());//签约人联系电话
                familyContent.put("moRegOrgNo", sbCode); //签约机构 限长4
                familyContent.put("moRegDocNo", doctor.getIdcard());//签约医生编号 限长18 身份证号
                familyContent.put("moRegDocName", signFamily.getSignDoctorName()); //签约医生姓名
                familyContent.put("moRegTime", sdf.format(signFamily.getBegin())); //签约时间
                familyContent.put("moRegEndTime", sdf.format(signFamily.getEnd())); //签约截止时间
//            familyContent.put("moRegYear", "04");//签约年度
                familyContent.put("moRegTear", signFamily.getSignYear());//签约年度
                familyContent.put("moRegSource", signFamily.getSignSource()); //签约来源
                familyContent.put("moCollectOrgNo", sbCode); //扣费机构 签约机构
                familyContent.put("moCollectorNo", signFamily.getSignDoctorName());//扣费人 签约医生姓名
                familyContent.put("benefitType", signFamily.getExpensesType()); //补贴类型
//                familyContent.put("benefitType", "01"); //补贴类型
                familyContent.put("moBookOrgNo", sbCode);//登记机构 签约机构
                familyContent.put("moBookerNo", signFamily.getSignDoctorName()); //登记人 签约医生姓名
                familyContent.put("moBookTime", sdf.format(signFamily.getBegin())); //登记时间 签约时间
                params.put("familyContent", objectMapper.writeValueAsString(familyContent));// 家庭医生签约信息
            }
            //请求结构体
            Map<String, String> map = new HashMap<>();
            map.put("feeType", "04");//家庭医生签约
            map.put("settleType", "03"); //健康账户支付
            params.put("requestContent", objectMapper.writeValueAsString(map));// 请求结构体
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
            //执行支付  获取预支付原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                JSONObject json = res.getParam();
                String chargeNo = String.valueOf(json.get("chargeNo"));      //医保结算业务流水号
                result = String.valueOf(json.get("payUrl"));
                charge.setChargeNo(chargeNo);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        //保存交易记录
        chargeDao.save(charge);
        //保存http日志
        logService.saveHttpLog(isSuccess, config.getChargeType(), "家庭医生签约支付", "POST", null, msgBody, response, error, logService.onepayType);
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    /**
     * 家庭医生签约支付查询
     */
    public String chargeQuery(String code, String accessToken) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = null;
        WlyyCharge charge = chargeDao.findByCode(code);
        HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(charge.getHospital());
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), hospitalMapping.getAppId(), hospitalMapping.getAppSecret(), signType, encryptType);
//        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), "54BBAF5148521AC9E053F000660AC501", "54BBAF5148531AC9E053F000660AC501", signType, encryptType);
        try {
            RequestParams requestParams = new RequestParams();
//            requestParams.setVersion();
//            requestParams.setSign();
//            requestParams.setEncryptData();
//            requestParams.setAppId(appId);
            requestParams.setAppId(hospitalMapping.getAppId());
//            requestParams.setAppId("54BBAF5148521AC9E053F000660AC501");
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTransType(config.getChargeQueryType());
            //业务参数
            JSONObject params = new JSONObject();
            params.put("outChargeNo", code);  //接入应用结算业务流水号
            params.put("wxToken", accessToken);
            requestParams.setParam(params);
            msgBody = JSON.toJSONString(requestParams);
            //执行支付 返回原生返回值
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            if (OnepayDefaultClient.isSuccessful(res)) {
                //业务处理*******************
//                只返回业务出参
//                result = JSON.toJavaObject(res.getParam(), Charge.class);
                result = JSON.toJSONString(res.getParam());
//                 返回医保机构体
//                System.out.println("请求成功,返回参数:" + result.getTradeStatus() + "  " + result.getUserName());
                LOGGER.info("请求成功,返回参数: "+result);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        //type = 3易联众接口保存http日志
        logService.saveHttpLog(isSuccess, config.getChargeType(), "家庭医生签约支付查询", "POST", null, msgBody, response, error, logService.onepayType);
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    /**
     * 生成电子社保卡
     */
    public String createSicard(String patient, String openid) throws Exception {
        Boolean isSuccess = true;
        String msgBody = "";
        String response = "";
        String error = "";
        String result = "";
        String appId = config.getOnepayAppId();
        String appSecret = config.getOnepayAppSecret();
        OnepayDefaultClient onepayClient = new OnepayDefaultClient(config.getOnepayApi(), appId, appSecret, signType, encryptType);
        try {
            RequestParams requestParams = new RequestParams();
            requestParams.setAppId(appId);
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            requestParams.setSignType(signType);
            requestParams.setEncryptType(encryptType);
            requestParams.setTimestamp(DateUtil.getCurrentDateTime());
            // 请求报文体参数,详见接口文档各接口——请求参数定义
            // 如医保绑卡信息请求参数
            JSONObject params = new JSONObject();
            params.put("openId", openid);
            params.put("accId", accId);  //微信公众号开发者ID
            requestParams.setParam(params);
            requestParams.setTransType(config.getCreateSicardType());
            msgBody = JSON.toJSONString(requestParams);
            ResponseParams<JSONObject> res = onepayClient.execute(requestParams);
            response = JSON.toJSONString(res);
            // 如医保卡绑卡信息返回参数
            if (OnepayDefaultClient.isSuccessful(res)) {
                JSONObject json = res.getParam();
                result = String.valueOf(json.get("sicardUrl"));      //电子社保卡连接
                //保存到患者表
                Patient p = patientDao.findByCode(patient);
                p.setOpenid(openid);
//            增加绑定电子社保卡信息
                p.setSicardTime(new Date());
                patientDao.save(p);
            } else {
                isSuccess = false;
                error = "请求失败,返回结果:" + res.getRespCode() + "," + res.getRespMsg();
            }
        } catch (Exception ex) {
            isSuccess = false;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            error = sw.toString();
        }
        //保存http日志
        logService.saveHttpLog(isSuccess, config.getBindCardType(), "生成电子社保卡", "POST", null, msgBody, response, error, logService.onepayType);
        if (!isSuccess) {
            throw new Exception(error);
        }
        return result;
    }
    /**
     * 更新所有记录的交易状态
     */
    private List<WlyyCharge> updateTradeStatus(List<WlyyCharge> list, String accessToken) {
        //更新交易状态
        if (list != null && list.size() > 0) {
            for (WlyyCharge item : list) {
                try {
//                    Charge charge = chargeQuery(item.getCode(), accessToken);
                    String result = chargeQuery(item.getCode(), accessToken);
                    Charge charge = objectMapper.readValue(result, Charge.class);
                    if (charge != null) {
                        item.setTradeStatus(charge.getTradeStatus());            //  交易状态0 成功 1 失败 2 已退款
                        item.setChargeNo(charge.getChargeNo());       //  流水号
                        item.setChargeTime(charge.getChargeTime());      // 扣费时间
                        item.setMedOrgNo(charge.getMedOrgNo()); // 医疗机构编码
                        item.setMedOrgName(charge.getMedOrgName());  //医疗机构名称
                        item.setBillNo(charge.getBillNo());  //待结算费用单据号
                    }
                } catch (Exception ex) {
                    System.out.print("update trade status fail!");
                }
            }
            chargeDao.save(list);
        }
        return list;
    }
    /**
     * 通过交易关联代码获取交易列表
     */
    public List<WlyyCharge> chargeList(String chargeType, String chargeRelation, String accessToken) throws Exception {
        List<WlyyCharge> list = chargeDao.findByChargeTypeAndChargeRelation(chargeType, chargeRelation);
        return updateTradeStatus(list, accessToken);
    }
    /**
     * 通过患者代码获取交易列表
     */
    public List<WlyyCharge> chargeListByPatient(String patient, String accessToken, Integer page, Integer size) throws Exception {
        PageRequest pageRequest = new PageRequest(page - 1, size);
        List<WlyyCharge> list = chargeDao.findByPatient(patient, pageRequest);
        return updateTradeStatus(list, accessToken);
    }
    /**
     * 更改数据 wlyy_sign_family wlyy_charge
     */
    public void updateData(String chargeCode, String chargeNo, String chargeTime, String totalAmount, String insuranceAmount, String selfPayAmount, String billNo, String miRegisterNo) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date chargeSuccess = sdf.parse(chargeTime);
        Date updateTime = new Date();
        chargeDao.updateByChargeCode(chargeCode, chargeTime, updateTime, Integer.parseInt(totalAmount), Integer.parseInt(insuranceAmount), Integer.parseInt(selfPayAmount),
                billNo, miRegisterNo, "0");
//        根据wlyy_charge的code 去查找关联代码signCode在更新签约表
        WlyyCharge charge = chargeDao.findByCode(chargeCode);
        signFamilyDao.updatePatientBegin(charge.getChargeRelation(), chargeSuccess, chargeNo, "1",2);
    }
}

+ 0 - 8
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/RSAUtils.java

@ -47,17 +47,9 @@ public class RSAUtils {
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private RSADao rsaDao;
    private BaseService baseService;
    @PostConstruct
    public void cleanRSA() {
        // 情况缓存表
        rsaDao.deleteAll();
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
    /**

+ 0 - 360
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java

@ -1,360 +0,0 @@
package com.yihu.wlyy.web.common;
import java.beans.Encoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImageCompress;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
@Controller
@RequestMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "文件上传")
public class FileUploadController extends BaseController {
    @ApiParam
    FastDFSUtil fastDFSUtil;
    @Autowired
    private CommonUtil CommonUtil;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    /**
     * 患者头像上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "patientPhoto", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String patientPhoto(HttpServletRequest request, HttpServletResponse response, String photo) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            String firstPhoto = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                firstPhoto = photo.substring(0, photo.lastIndexOf(".")) + "_small." + fileExt;
                File uploadFile = new File(SystemConf.getInstance().getTempPath() + File.separator + firstPhoto);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", String.join(",", firstPhoto));
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 图片上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "image", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String image(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> images = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 生成缩略图
                ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
                // 添加到上传成功数组中
                images.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String image : tempPaths) {
                if (urls.length() == 0) {
                    urls = image;
                } else {
                    urls += "," + image;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : images) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 聊天附件上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "chat", method = RequestMethod.POST)
    @ResponseBody
    public String chatFile(HttpServletRequest request, HttpServletResponse response) {
        List<String> tempPaths = new ArrayList<String>();
        try {
            String fastUrl = fastdfs_file_url;
            String type  = request.getParameter("type");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                if("3".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String map3Path = tempPath.substring(0,tempPath.lastIndexOf("."));
                    CommonUtil.changeToMp3(tempPath,map3Path);
                    File tempFile = new File(tempPath);
                    File mp3File = new File(map3Path);
                    ObjectNode objectNode = fastDFSUtil.upload(new FileInputStream(mp3File),"mp3","");
                    tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(mp3File!=null){
                        mp3File.delete();
                    }
                }else if("4".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
                    File tempFile = new File(tempPath);
                    File pngFile = new File(pngPath);
                    long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
                    if(times<1000){
                        JSONObject json = new JSONObject();
                        json.put("status", -1);
                        json.put("success",true);
                        json.put("msg", "视频录制时间太短!");
                        json.put("times", times);
                        return json.toString();
                    }
                    ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
                    tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(times+"");
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(pngFile!=null){
                        pngFile.delete();
                    }
                } else{
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode objectNode = fastDFSUtil.upload(mf.getInputStream() ,fileExt,"");
                    tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                }
            }
            String urls = String.join(",", tempPaths);
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("success",true);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("附件上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "voice", method = RequestMethod.POST)
    @ResponseBody
    public String voice(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> voices = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 添加到上传成功数组中
                voices.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String voice : tempPaths) {
                if (urls.length() == 0) {
                    urls = voice;
                } else {
                    urls += "," + voice;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("语音上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : voices) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ResponseBody
    public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<String> tempPaths = new ArrayList<String>();
        String fastUrl = fastdfs_file_url;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();
            String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
            String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
            File tempFile = new File(tempPath);
            File pngFile = new File(pngPath);
            long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
            ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
            tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(times+"");
            if(tempFile!=null){
                tempFile.delete();
            }
            if(pngFile!=null){
                pngFile.delete();
            }
        }
        String urls = String.join(",", tempPaths);
        return urls;
    }
}

+ 0 - 33
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/advert/AdvertController.java

@ -1,33 +0,0 @@
package com.yihu.wlyy.web.common.advert;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.service.common.advert.AdvertService;
import com.yihu.wlyy.web.BaseController;
@Controller
@RequestMapping(value = "common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "广告")
public class AdvertController extends BaseController {
	
	@Autowired
	private AdvertService advertService;
	@RequestMapping(value = "advert")
	@ResponseBody
	public String list(int type) {
		try {
			return write(200, "查询成功", "list" , advertService.findByType(type));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
}

+ 0 - 43
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java

@ -1,43 +0,0 @@
package com.yihu.wlyy.web.common.area;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.common.area.AreaService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/area")
@Api(description = "城市、城镇管理")
public class AreaController extends BaseController {
    @Autowired
    AreaService areaService;
    /**
     * 查询城市下的城镇
     *
     * @param city 城市
     * @return
     */
    @RequestMapping(value = "/{city}/towns", method = RequestMethod.GET)
    public String getCityTowns(@PathVariable String city) {
        try {
            List<Town> towns = areaService.getCityTowns(city);
            return write(200, "查询成功", "data", towns == null ? new ArrayList<Town>() : towns);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 0 - 71
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/data/DataController.java

@ -1,71 +0,0 @@
package com.yihu.wlyy.web.common.data;
import java.util.List;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.dict.Disease;
import com.yihu.wlyy.service.common.data.DataService;
import com.yihu.wlyy.web.BaseController;
@RequestMapping(value = "/common/data", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Controller
@Api(description = "疾病与社区")
public class DataController extends BaseController {
	@Autowired
	private DataService dataService;
	@RequestMapping(value = "diseases")
	@ResponseBody
	public String diseases() {
		try {
			JSONArray array = new JSONArray();
			List<Disease> list = dataService.findAllDisease();
			for (Disease temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				json.put("code", temp.getCode());
				json.put("name", temp.getName());
				array.put(json);
			}
			return write(200, "获取疾病成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取疾病失败!");
		}
	}
	@RequestMapping(value = "diseases_community")
	@ResponseBody
	public String diseasesCommunity() {
		try {
			JSONArray array = new JSONArray();
			List<Disease> list = dataService.findAllDisease();
			for (Disease temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				json.put("code", temp.getCode());
				json.put("name", temp.getName() + "社区");
				array.put(json);
			}
			return write(200, "获取疾病社区成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取疾病社区失败!");
		}
	}
}

+ 0 - 66
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java

@ -1,66 +0,0 @@
package com.yihu.wlyy.web.common.device;
import com.yihu.wlyy.entity.device.Device;
import com.yihu.wlyy.entity.device.DeviceCategory;
import com.yihu.wlyy.service.app.device.DeviceService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "设备管理")
public class DeviceController extends BaseController {
	
	@Autowired
	private DeviceService deviceService;
	@ApiOperation("获取设备分类")
	@RequestMapping(value = "DeviceCategory")
	@ResponseBody
	public String getDeviceCategory() {
		try {
			List<DeviceCategory> list = deviceService.findAllCategory();
			return write(200,"获取设备分类成功!","data",list);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "获取设备分类失败!");
		}
	}
	@ApiOperation("获取设备列表")
	@RequestMapping(value = "DeviceList")
	@ResponseBody
	public String getDeviceList(@ApiParam(name="category_code",value="设备类型代码",defaultValue = "1")
								 @RequestParam(value="category_code",required = true) String categoryCode) {
		try {
			List<Device> list = deviceService.findDeviceByCategory(categoryCode);
			return write(200,"获取设备列表成功!","data",list);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "获取设备列表失败!");
		}
	}
	@ApiOperation("获取设备信息")
	@RequestMapping(value = "DeviceInfo")
	@ResponseBody
	public String getDeviceInfo(@ApiParam(name="id",value="设备ID",defaultValue = "19")
									   @RequestParam(value="id",required = true) String id) {
		try {
			Device device = deviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
}

+ 0 - 46
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java

@ -1,46 +0,0 @@
package com.yihu.wlyy.web.common.district;
import java.util.List;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.service.common.district.DistrictService;
import com.yihu.wlyy.web.BaseController;
/**
 * 省市区三级地址控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "省市区三级地址")
public class DistrictController extends BaseController {
	@Autowired
	private DistrictService districtService;
	/**
	 * 省市一二三级查询接口
	 * @param type 1一级目录,2二级目录,3三级目录,4街道目录
	 * @param code 省或市标识
	 * @return
	 */
	@RequestMapping(value = "district")
	@ResponseBody
	public String district(int type, String code) {
		try {
			List<?> list = districtService.findByType(type, code);
			return write(200, "查询成功!", "list", list);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
}

+ 0 - 79
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java

@ -1,79 +0,0 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.entity.education.FoodComp;
import com.yihu.wlyy.service.app.health.FoodCompService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
 * 患者端:食物热量查询
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/common/health/food", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-食物热量查询")
public class FoodCompController extends BaseController {
	@Autowired
	private FoodCompService foodCompService;
	/**
	 * 查询食物热量列表
	 * @param pid 父id
	 * @return 列表
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam("pid")long pid) {
		try {
			List<FoodComp> foodComps = foodCompService.getByPid(pid);
			return write(200, "查询成功", "list", foodComps);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询食物热量查询
	 * @param name 查询名称
	 * @return 列表
	 */
	@RequestMapping(value = "search")
	@ResponseBody
	public String list(@RequestParam("name")String name) {
		try {
			List<FoodComp> foodComps = foodCompService.getByName(name);
			return write(200, "查询成功", "list", foodComps);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询食物热量详情
	 * @param id 查询名称
	 * @return 列表
	 */
	@RequestMapping(value = "detail")
	@ResponseBody
	public String list(@RequestParam("id")Long id) {
		try {
			FoodComp foodComp = foodCompService.getById(id);
			return write(200, "查询成功", "list", foodComp);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
}

+ 0 - 63
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java

@ -1,63 +0,0 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Reece on 2017/2/13.
 */
@Controller
@RequestMapping(value = "/common")
@Api(description = "获取福州健康教育文章并保存")
public class HealthEduArticlesController extends BaseController{
    @Autowired
    private HealthEduArticleService healthEduArticleService;
    @RequestMapping(value = "getHealthEduArticles",method = RequestMethod.GET)
    @ResponseBody
    public String getHealthEduArticles(
            @RequestParam(value = "医院名称") String hospitalName,
            @RequestParam(value = "开始时间") String startTime,
            @RequestParam(value = "截至时间") String endTime,
            @RequestParam(value = "文章来源 0 医生自创 1健康之路 2 39健康网") String MessageFrom,
            @RequestParam(value = "获取文章数量默认10",defaultValue = "10") String pageSize,
            @RequestParam(value = "展示页数,从0开始",defaultValue = "0") String pageNumber
    ){
        try {
            Map<String,String> params = new HashMap<>();
            params.put("hospitalName",hospitalName);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            params.put("MessageFrom",MessageFrom);
            params.put("pageSize",pageSize);
            params.put("pageNumber",pageNumber);
//      timestamp必须与服务器时间相差在5分钟以内,否则调用将失败
            String timestamp = Long.toString(System.currentTimeMillis());
            params.put("timestamp",timestamp);
//          获取福州健康教育文章
            String result = healthEduArticleService.getHealthEduArticles(params);
//          保存福州健康教育文章
            int rows = healthEduArticleService.saveHealthEduArticles(result);
            if(rows>0){
                return write(200, "数据导入成功");
            }
            return write(-1, "数据导入失败!");
        }catch (Exception e){
            return error(-1, "数据导入失败!");
        }
    }
}

+ 0 - 35
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java

@ -1,35 +0,0 @@
package com.yihu.wlyy.web.common.hospital;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/hospitals")
@Api(description = "医院管理")
public class HospitalCommonController extends BaseController {
    @Autowired
    HospitalService hospitalService;
    @RequestMapping(value = "/{town}/community_hospitals",method = RequestMethod.GET)
    @ApiOperation(value = "查询城镇下社区")
    public String getTownHospitals(@PathVariable String town) {
        try {
            List<Hospital> hospitals = hospitalService.getHositalByTownCode(town);
            return write(200, "查询成功", "data", hospitals == null ? new ArrayList<Hospital>() : hospitals);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 0 - 313
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/im/imController.java

@ -1,313 +0,0 @@
package com.yihu.wlyy.web.common.im;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.util.ImUtill;
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;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping(value = "im_new", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "IM-即时消息")
public class imController extends BaseController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ImUtill ImUtill;
    /**
     * 获取单个咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/getTopic")
    @ResponseBody
    public String getTopic(String consult) {
        try {
            return success(ImUtill.getTopic(consult).get("data").toString());
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    /**
     * 获取当前团队的咨询列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamList", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam int adminTeamCode,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = ImUtill.getTeamConsultByStatus(doctor,adminTeamCode, status, reply, page, pagesize);
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getList", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam(required = false) Integer type,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = null;
            if(type==null){
                consult = ImUtill.getConsultByStatus(doctor, status, reply, page, pagesize);
            }else {
                consult = ImUtill.getConsultByStatusAndType(doctor, status, reply,type, page, pagesize);
            }
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队统计数据
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamData", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamData(@RequestParam int adminTeamCode) {
        try {
            String uid = getUID();
            List<Map<String, Object>> doctors = getMemberByDoctor(uid);
            JSONObject json = new JSONObject();
            List list = new ArrayList();
            int countUnReply = 0;
            int countReply = 0;
            int countConsult = 0;
//        团队下的医生统计数量
            for (Map<String, Object> doc : doctors) {
                Map map = new HashMap();
                String doctor = doc.get("code").toString();
                map.put("photo", doc.get("photo") == null ? "" : doc.get("photo").toString());
                map.put("name", doc.get("name").toString());
                map.put("sex", doc.get("sex").toString());
                map.put("doctor", doctor);
                map.put("type", doc.get("level") == null ? "" : doc.get("level").toString());
//                未回复
                String totalUnReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 0);
                int unReply = Integer.parseInt(totalUnReply);
                map.put("totalUnReply", unReply);
//                已回复
                String totalReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 1);
                String totalReply1 = ImUtill.getConsultData(doctor,adminTeamCode, 10, null);
                int reply = Integer.parseInt(totalReply) + Integer.parseInt(totalReply1);
                map.put("totalReply", reply);
//                总咨询量
                String totalConsult = ImUtill.getConsultData(doctor, adminTeamCode,null, null);
                int consult = Integer.parseInt(totalConsult);
                map.put("totalConsult", consult);
                countUnReply += unReply;
                countReply += reply;
                countConsult += consult;
                list.add(map);
            }
            json.put("totalUnReply", countUnReply);
            json.put("totalReply", countReply);
            json.put("totalConsult", countConsult);
            json.put("doctors", list);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队医生下居民的咨询
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/getConsultByPatient", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByPatient(@RequestParam String patient) {
        try {
//            1.调im接口
//            2.判断团队长和当前咨询居民是否存在签约关系
            String doctor = getUID();
            int count = signFamilyDao.findByPatientAndDoctor(patient, doctor);
            boolean flag = (count == 0) ? false : true;
            return write(200, "查询成功", "data", flag);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 提醒医生相关信息
     *
     * @param doctor  提醒的医生
     * @param content 提醒的内容
     * @return
     */
    @RequestMapping(value = "/message/remain", method = RequestMethod.POST)
    @ResponseBody
    public String reaminDoctor(String doctor, String content) {
        try {
            JSONObject participants = new JSONObject();
            participants.put(doctor, 0);
            participants.put(getUID(), 0);
            Doctor d = doctorDao.findByCode(getUID());
            //创建医生会话讨论组
            JSONObject sessionObj = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, d.getName() + "发来消息提醒", "");
            if (sessionObj.getInt("status") == -1) {
                throw new RuntimeException(sessionObj.getString("message"));
            }
            JSONObject session = sessionObj.getJSONObject("data");
            ImUtill.sendImMsg(getUID(), d.getName(), session.getString("id"), "1", content, "REMAIN");
            return success("提醒成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    public List getMemberByDoctor(String doctor) {
        String sql = "SELECT d.photo,d.`name`,d.sex,d.`code`,d.level " +
                " from wlyy_admin_team t,wlyy_admin_team_member m,wlyy_doctor d " +
                " where t.id = m.team_id and m.doctor_code = d.`code` and t.available = 1 and m.available=1 " +
                " and t.leader_code = ? ";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql, doctor);
        return doctors;
    }
}

+ 0 - 45
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java

@ -1,45 +0,0 @@
package com.yihu.wlyy.web.common.messages;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
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 java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/im/common/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-消息")
public class ImMessageController extends BaseController {
    @Autowired
    private MessageService messageService;
    @RequestMapping(value = "messages")
    @ResponseBody
    @ApiOperation("查询医生未读消息和最后消息")
    public String messages() {
        try {
            JSONObject json = messageService.findDoctorAllMessage(getUID());
            return write(200, "获取消息总数成功!", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
}

+ 0 - 399
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java

@ -1,399 +0,0 @@
package com.yihu.wlyy.web.common.qrcode;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.service.common.QrcodeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * Created by lyr on 2016/08/10.
 */
@Controller
@RequestMapping(value = "/qrcode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "二维码")
public class QrCodeController extends WeixinBaseController {
    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private DoctorService doctorService;
    @RequestMapping(value = "/doctors")
    @ResponseBody
    public String makeDoctorQrcodes(String hospital) {
        try {
            if (qrcodeService.makeDoctorQrCode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成某个医生的二维码
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor")
    @ResponseBody
    public String makeDoctorQrcode(String doctor) {
        try {
            if (qrcodeService.makeDoctorQrcode(doctor, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成社区二维码
     *
     * @param hospital
     * @return
     */
    @RequestMapping(value = "/hospital")
    @ResponseBody
    public String makeHospitalQrcode(String hospital) {
        try {
            if (qrcodeService.makeHospitalQrcode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成区二维码
     *
     * @param town
     * @return
     */
    @RequestMapping(value = "/town")
    @ResponseBody
    public String makeTownQrcode(String town) {
        try {
            if (qrcodeService.makeTownQrcode(town, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 下载某个社区的二维码
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/hospital_img")
    public void downloadSqQrcode(String hospital, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + hospital + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeHospitalQrcode(hospital, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + hospital + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
        }
    }
    /**
     * 下载某个区的二维码
     *
     * @param town
     * @param response
     */
    @RequestMapping(value = "/town_img")
    public void downloadTownQrcode(String town, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + town + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeTownQrcode(town, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + town + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/download")
    public void downloadQrcode(String doctor, HttpServletResponse response) {
        try {
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + doc.getQrcode());
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/doctor_img")
    public void downloadQrcodeImage(String doctor, HttpServletResponse response) {
        try {
            System.out.println("------------------doctor:" + doctor);
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + doc.getQrcode());
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载所有医生的二维码图片
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/download/doctors")
    public void downloadQrcodes(String hospital, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadDoctorQrCodes(hospital, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=doctors_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个区的社区的二维码图片
     *
     * @param area
     * @param response
     */
    @RequestMapping(value = "/download/hospitals")
    public void downloadSqQrcodes(String area, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadHospitalQrCodes(area, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=hospitals_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个城市的区的二维码图片
     *
     * @param city
     * @param response
     */
    @RequestMapping(value = "/download/towns")
    public void downloadTownQrcodes(String city, HttpServletResponse response) {
        try {
            File file = qrcodeService.downLoadTownQrcodes(city, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=towns_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
}

+ 0 - 116
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java

@ -1,116 +0,0 @@
package com.yihu.wlyy.web.common.sms;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
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.common.SMSService;
import com.yihu.wlyy.util.NetworkUtil;
import com.yihu.wlyy.web.BaseController;
import java.util.List;
@Controller
@RequestMapping(value = "/common")
@Api(description = "短信")
public class SMSController extends BaseController {
	@Autowired
	public SMSService smsService;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DoctorDao doctorDao;
	/**
	 * 发送短信验证码接口
	 * @param mobile 手机号
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录 .6患者签约验证 7用户变更手机号验证 8用户新手机号验证 9绑定手机号
	 *             10 家庭成员添加验证
	 * @return
	 */
	@RequestMapping(value = "captcha", method = RequestMethod.POST)
	@ResponseBody
	public String send(String mobile, int type, @RequestParam(required = false) String captchaToken) {
		try {
			if (type > 10 || type < 1) {
				return error(-1, "无效的请求!");
			}
			if (StringUtils.isEmpty(mobile)) {
				return error(-1, "手机号码不允许为空!");
			}
			if (type == 4) {
				// 登录时校验用户是否存在
				List<Patient> patients = patientDao.findByMobile(mobile);
				if (patients == null||patients.size()==0) {
					return error(-1, "该手机号未注册!");
				}
			} else if (type == 5) {
				// 登录时校验用户是否存在
				Doctor doctor = doctorDao.findByMobile(mobile);
				if (doctor == null) {
					return error(-1, "该手机号未注册!");
				}
			}
			if (StringUtils.isNotEmpty(captchaToken)) {
				String ct = request.getSession().getAttribute("captchaToken").toString();
				if (!StringUtils.equalsIgnoreCase(captchaToken, ct)) {
					return error(-1, "图形验证码错误!");
				}
			}
			// 获取ip地址
			String ip = NetworkUtil.getIpAddress(request);
			if (StringUtils.isEmpty(ip)) {
				return error(-1, "无效的ip请求!");
			}
//			String res = smsService.send(mobile, ip, type, getUID());
			String res = smsService.send(mobile, ip, type, getRepUID());
			if (StringUtils.equals(res, "ok")) {
				return write(200, "验证码短信已发送!");
			} else {
				return error(-1, res);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "短信发送失败!");
		}
	}
	/**
	 * 验证手机验证码
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码
	 * @param mobile
	 * @param captcha
	 * @return
	 */
	@RequestMapping(value = "check_captcha", method = RequestMethod.POST)
	@ResponseBody
	public String checkCaptcha(int type, String mobile, String captcha) {
		try {
			// 对验证码进行校验
			int res = smsService.check(mobile, type, captcha);
			switch (res) {
			case -2:
				return error(-1, "验证码已过期!");
			case -1:
				return error(-1, "验证码错误!");
			case 0:
				return error(-1, "验证码无效!");
			}
			return success("有效验证码!");
		} catch (Exception e) {
			error(e);
			return error(-1, "验证码检查失败!");
		}
	}
}

+ 0 - 52
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java

@ -1,52 +0,0 @@
package com.yihu.wlyy.web.common.system;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
@Controller
@RequestMapping(value = "/common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "系统字典")
public class SystemDictController extends BaseController {
    @Autowired
    private SystemDictService systemDictService;
    @ApiOperation("根據dictname查找字典数据")
    @RequestMapping(value = "/getDictByDictName", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getDictByDictName(@ApiParam(name="name",value="字典名",defaultValue = "")
                                        @RequestParam(value="name",required = true) String name){
        try {
            List<SystemDict> list=systemDictService.getDictByDictName(name);
            JSONArray ja=new JSONArray();
            for (SystemDict systemDict:list){
                JSONObject jo=new JSONObject();
                jo.put("code",systemDict.getCode());
                jo.put("value",systemDict.getValue());
                ja.put(jo);
            }
            return write(200,"查询成功","list",ja);
        } catch (Exception e) {
            error(e);
            return error(-1, "验证码检查失败!");
        }
    }
}

+ 0 - 45
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java

@ -1,45 +0,0 @@
package com.yihu.wlyy.web.common.url;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr-pc on 2017/1/17.
 */
@RestController
@RequestMapping(value = "/common/cud_url")
@Api("增删改路径查询")
public class CudUrlController extends BaseController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 查询增删改路径
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "查询增删改路径")
    public String getCudUrl() {
        try {
            String sql = "select * from wlyy_cud_url";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            return write(200,"查询成功","data",result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
}

+ 0 - 108
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java

@ -1,108 +0,0 @@
package com.yihu.wlyy.web.common.util;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 患者端验证码生成控制器。验证码生成后保存到Redis中,并将Redis的Key与图片路径返回。
 * 客户端获取图片,并由用户输入后,与redis的key一块返回,用于验证是否出错。
 *
 * @author Sand
 * @created 2016/09/28
 */
@Api(description = "验证码")
@RestController
@RequestMapping(value = "/patient/captcha", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CaptchaController extends BaseController {
    private Map<String, String> captchaCache = new ConcurrentHashMap<>();
    private DefaultKaptcha captchaProducer = new DefaultKaptcha();
    public CaptchaController() {
        Properties properties = new Properties();
        properties.put("kaptcha.textproducer.font.color", "blue");
        properties.put("kaptcha.textproducer.font.size", "45");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
    }
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation("生成验证码,用于第一次请求")
    public String createCaptcha(){
        try{
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{legacy_key}", method = RequestMethod.POST)
    @ApiOperation("刷新验证码,需提供第一次生成验证码返回的key")
    public String refreshCaptcha(@PathVariable("legacy_key") String legacyKey){
        try{
            cleanCaptcha(legacyKey);
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{key}", method = RequestMethod.GET)
    @ApiOperation("校验证码,提供key及用户输入的验证码")
    public String verifyCaptcha(@PathVariable("key") String key,
                                @RequestParam("text") String text){
        try{
            boolean pass = false;
            String captcha = captchaCache.get(key);
            if (captcha != null && captcha.equals(text.toLowerCase())){
                pass = true;
                cleanCaptcha(key);
            }
            return write(200, "ok", "pass", pass);
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    private String generateCaptcha() throws IOException {
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Img = new BASE64Encoder().encode(outputStream.toByteArray());
        String key = "captcha:" + UUID.randomUUID().toString() + ":text";
        Map<String, String> data = new HashMap<>();
        data.put("key", key);
        data.put("image", base64Img);
        data.put("format", "png");
        captchaCache.put(key, captchaText.toLowerCase());
        return write(200, "ok", "data", data);
    }
    private void cleanCaptcha(String key){
        captchaCache.remove(key);
    }
}

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

@ -1,360 +0,0 @@
package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.job.*;
import com.yihu.wlyy.job.consult.EvaluateScoreJob;
import com.yihu.wlyy.job.consult.FamousConsultTimesJob;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.statistics.StatisticsService;
import com.yihu.wlyy.service.common.util.ManageUtilService;
import com.yihu.wlyy.service.common.util.SignTeamAndGroupRunnable;
import com.yihu.wlyy.util.SpringUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
/**
 * Created by lyr on 2016/09/13.
 */
@RestController
@RequestMapping(value = "/manage_util", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "管理工具及后台任务控制")
public class ManagerUtilController extends BaseController {
    @Autowired
    PatientDiseaseService diseaseService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    QuartzHelper quartzHelper;
    @Autowired
    DoctorWorkTimeService workTimeService;
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    ManageUtilService manageUtilService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ConsultTeamDoctorDao consultTeamDoctorDao;
    /*********************************************患者疾病相关******************************************/
    /**
     * 更新到redis
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_redis")
    public String updateToRedid() {
        try {
            diseaseService.updateToRedis();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新到疾病表
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_disease")
    public String updateToDisease() {
        try {
            diseaseService.updateToDisease();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 查询患者redis疾病
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/disease/patient")
    public String getDiseaseFromRedis(String patient) {
        try {
            return write(200, "查询成功", "data", redisTemplate.opsForValue().get("disease:" + patient));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /***********************************************名医咨询相关****************************************/
    /**
     * 开始名医咨询剩余次数统计任务
     *
     * @return
     */
    @RequestMapping(value = "/famous_doctor/start_job")
    public String startConsultTimesJob() {
        try {
            if (!quartzHelper.isExistJob("famous-doctor-times")) {
                quartzHelper.addJob(FamousConsultTimesJob.class, "0 0 0 * * ?", "famous-doctor-times", new HashMap<String, Object>());
                return write(200, "启动成功");
            } else {
                return write(200, "任务已存在");
            }
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 名医咨询剩余次数手动更新
     *
     * @return
     */
    @RequestMapping(value = "/famous_doctor/times_update")
    public String famousConsultTimeUpdate() {
        try {
            workTimeService.consultTimesRemain(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /*********************************************统计相关*******************************************/
    /**
     * 更新人口数据到redis
     *
     * @return
     */
    @RequestMapping(value = "/people_num_to_redis")
    public String peopleNumToRedis(String year) {
        try {
            statisticsService.peopleNumToRedis(year);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team")
    public String signSetGroupAndTeam() {
        try {
            manageUtilService.signPatientSetGroup();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_page")
    public String signSetGroupAndTeamPage(int page) {
        try {
            manageUtilService.setSignTeamAndGroupByPage(page);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_id")
    public String signSetGroupAndTeamId(Long id) {
        try {
            manageUtilService.setSignTeamAndGroupById(id);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_error_page_id")
    public String getErrorPage(int type) {
        try {
            if (type == 1) {
                return write(200, "查询成功", "data", ManageUtilService.page);
            } else if (type == 2) {
                return write(200, "查询成功", "data", ManageUtilService.errorPages);
            } else {
                return write(200, "查询成功", "data", ManageUtilService.errorSigns);
            }
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_team_group_thread")
    public String getErrorPage(long start, long end) {
        try {
            new Thread(SpringUtil.getBean(SignTeamAndGroupRunnable.class)
                    .setEnd(end).setStart(start)).start();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 健康教育数据清洗
     *
     * @return
     */
    @RequestMapping(value = "/tranform_edu_article")
    public String tranformEduArticle() {
        try {
            manageUtilService.transformEduArticle();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 开始名医咨询剩余次数统计任务
     *
     * @return
     */
    @RequestMapping(value = "/start_sign_end_job")
    public String startSignEndJob() {
        try {
            if (!quartzHelper.isExistJob("sign_end_job")) {
                quartzHelper.addJob(SignEndJob.class, "0 45 10 * * ?", "sign_end_job", new HashMap<String, Object>());
                return write(200, "启动成功");
            } else {
                return write(200, "任务已存在");
            }
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 统计任务
     *
     * @return
     */
    @RequestMapping(value = "/start_evaluate_score_job")
    @ResponseBody
    public String startEvaluateScoreJob() {
        try {
            if (!quartzHelper.isExistJob("evaluate_score_job")) {
                quartzHelper.addJob(EvaluateScoreJob.class, "59 59 23 * * ?", "evaluate_score_job", new HashMap<String, Object>());
                return write(200, "启动成功");
            } else {
                return write(200, "任务已存在");
            }
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/start_evaluate_score_job_now")
    @ResponseBody
    public String startEvaluateScoreJobNow() {
        try {
            quartzHelper.startNow(EvaluateScoreJob.class, "evaluate_score_job"+UUID.randomUUID(), new HashMap<String, Object>());
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/prescription_pay_overdue_job_now")
    @ResponseBody
    public String startPrescriptionPayOverdueJobNow() {
        try {
            quartzHelper.startNow(EvaluateScoreJob.class, "prescription_pay_overdue_job"+UUID.randomUUID(), new HashMap<String, Object>());
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/start_renew_to_sign_job")
    @ResponseBody
    public String startRenewToSignJob() {
        try {
            if (!quartzHelper.isExistJob("renew_to_sign_job")) {
                quartzHelper.startNow(RenewToSignJob.class, "renew_to_sign_job", new HashMap<String, Object>());
                return write(200, "启动成功");
            } else {
                return write(200, "任务已存在");
            }
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 立即开始后台群发图文消息任务
     *
     * @return
     */
    @RequestMapping(value = "/start_sign_again_job")
    @ResponseBody
    public String startSignAgainJob() {
        try {
            quartzHelper.startNow(SignAgainJob.class, "start_sign_again_job"+UUID.randomUUID(), new HashMap<String, Object>());
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 产检提醒
     *  每天早上六点
     * @return
     */
//    @RequestMapping(value = "/start_prenatal_inspector_job")
//    @ResponseBody
//    public String startPrenatalInspectorJob() {
//        try {
//            if (!quartzHelper.isExistJob("prenatal_inspector_job")) {
//                quartzHelper.addJob(PrenatalInspectorJob.class, "0 0 6 * * ?", "prenatal_inspector_job", new HashMap<String, Object>());
//                return write(200, "启动成功");
//            } else {
//                return write(200, "任务已存在");
//            }
//        } catch (Exception e) {
//            return error(-1, "启动失败");
//        }
//    }
}

+ 0 - 333
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java

@ -1,333 +0,0 @@
package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.service.third.guahao.GuahaoXMService;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by lyr on 2016/9/29.
 */
@RestController
@RequestMapping(value = "/wlyy_service")
@Api(description = "卫计委签约接口调试")
public class WlyySerivceController extends BaseController{
    @Autowired
    private GuahaoXMService guahaoXM;
    @Autowired
    private JwSmjkService jwSmjkService;
    @Autowired
    private HttpUtil HttpUtil;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;
    /**
     * 检查是否签约
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/CheckSignFamily",method = RequestMethod.POST)
    @ApiOperation("检查是否签约")
    public String checkSignFamily(@RequestParam("idcard") String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/CheckSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 上传签约数据
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/third/sign/UploadSignFamily",method = RequestMethod.POST)
    @ApiOperation("上传签约数据")
    public String uploadSignFamily(@RequestParam("code")String code){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/UploadSignFamily?code=" + code, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 初次采集签约接口
     *
     * @param start_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadAllSignFamily",method = RequestMethod.POST)
    @ApiOperation("初次采集签约接口")
    public String loadAllSignFamily(@RequestParam("start_time")String start_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadAllSignFamily?start_time=" + start_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 单条采集签约接口
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamily",method = RequestMethod.POST)
    @ApiOperation("单条采集签约接口")
    public String loadSingleSignFamily(@RequestParam("idcard")String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 时间范围采集签约接口
     *
     * @param start_time
     * @param end_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamilyBatch",method = RequestMethod.POST)
    @ApiOperation("时间范围采集签约接口")
    public String loadSignFamilyBatch(@RequestParam("start_time")String start_time,@RequestParam("end_time")String end_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamilyBatch?start_time=" + start_time + "&end_time=" + end_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 补上传签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUploadSignFamily",method = RequestMethod.POST)
    public String reuploadSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUploadSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 补更新签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUpdateSignFamily",method = RequestMethod.POST)
    public String reupdateSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUpdateSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 转诊预约医生特殊号源获取
     * @param OrgCode 医院编号
     * @param DeptCode 科室编号
     * @param DocCode 医生编号
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorSectionList",method = RequestMethod.POST)
    @ApiOperation("转诊预约获取特殊号源接口")
    public String getSpeDoctorSectionList(@RequestParam("OrgCode") String OrgCode,
                                          @RequestParam("DeptCode") String DeptCode,
                                          @RequestParam("DocCode") String DocCode){
        try{
            List<Map<String,Object>> list = guahaoXM.GetDoctorArrangeTenDay(OrgCode,DeptCode,DocCode);
            return write(200, "获取医生排班成功!", "data", list);
           /* *//*****modify by linz 暂时把号源转换成普通号源****//*
            List<Map<String,Object>> list =  guahaoXM.GetDoctorArrange(OrgCode,DeptCode,DocCode);
            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,"医生排班时间获取失败");
        }
    }
    /**
     * 获取转诊预约医生列表
     * @param city
     * @param hospitalId
     * @param hosDeptId
     * @param filter
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorList",method = RequestMethod.POST)
    @ApiOperation("获取转诊预约医生列表")
    @ResponseBody
    public String getRegDeptSpeDoctorList(
            @ApiParam(name = "city", value = "城市编码", defaultValue = "350200")@RequestParam(value = "city", required = true) String city,
            @ApiParam(name="hospitalId",value="医院编码",defaultValue = "350211A1001") @RequestParam(name="hospitalId",required = true) String hospitalId,
            @ApiParam(name="hosDeptId",value="科室编码",defaultValue = "1040610") @RequestParam(name="hosDeptId",required = true) String hosDeptId,
            @ApiParam(name = "filter", value = "过滤条件", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "pageIndex", value = "第几页", defaultValue = "")
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @ApiParam(name = "pageSize", value = "每页记录数", defaultValue = "")
            @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            //10天排班的医生列表
            //String list  = jwSmjkService.getRegDeptSpeDoctorList(orgCode,deptCode);
            //7天排班的医生列表
            String list = jwSmjkService.GetDoctorList(hospitalId,hosDeptId);
            return list;
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1,"获取转诊预约医生列表列表失败");
        }
    }
    /**
     * 转诊预约医生号源转换
     * @param xml
     * @return
     */
    private List<Map<String,Object>>  parseXmlForSpe(String xml) {
            List<Map<String,Object>> re = new ArrayList<>();
            Document document = null;
            try{
                 document = DocumentHelper.parseText(xml);
             }catch (Exception e){
                throw new RuntimeException("解析数据失败!");
            }
            Element root = document.getRootElement();
            List<?> child = root.elements();//取出root的子集合
            for (Object o : child) {
                List<?> dataList = ((Element) o).elements();
                for(Object dataElement:dataList) {
                    Element e = (Element) dataElement;
                    // 日期
                    String date = e.attributeValue("date");
                    // a或者p
                    String time = e.attributeValue("time");
                    // 限号
                    String max = e.attributeValue("max");
                    // 已使用的号
                    String used = e.attributeValue("used");
                    // 1正常、2满号、3已过期
                    String status = e.attributeValue("status");
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", date);
                    map.put("time", time);
                    map.put("max", max);
                    map.put("used", used);
                    map.put("status", status);
                    // 排班信息
                    List<?> sections = e.elements();
                    List<Map<String, String>> arrangeList = new ArrayList<>();
                    for (Object s : sections) {
                        Element section = (Element) s;
                        // 限号
                        String s_max = section.attributeValue("max");
                        // 已使用的号
                        String s_used = section.attributeValue("used");
                        // 一次专家坐诊时间段的开始时间
                        String start_time = section.attributeValue("start_time");
                        // 结束时间
                        String end_time = section.attributeValue("end_time");
                        Map<String, String> item = new HashMap<>();
                        item.put("max", s_max);
                        item.put("used", s_used);
                        item.put("startTime", start_time);
                        item.put("endTime", end_time);
                        arrangeList.add(item);
                    }
                    map.put("sections", arrangeList);
                    re.add(map);
                }
            }
            return  re;
        }
        public static Date getDateAfter(Date d, int day) {
            Calendar now = Calendar.getInstance();
            now.setTime(d);
            now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
            return now.getTime();
      }
}

+ 0 - 76
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java

@ -1,76 +0,0 @@
package com.yihu.wlyy.web.common.verified;
import com.yihu.wlyy.service.third.verified.VerifiedService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImageCompress;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@RequestMapping(value = "/verified", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "实名认证")
public class VerifiedController extends BaseController {
	@Autowired
	private VerifiedService verifiedService;
	/**
	 * 人脸识别
	 */
	@RequestMapping(value = "face", method = RequestMethod.POST)
	@ResponseBody
	public String face(
			@ApiParam(name="idcard",value="身份证号码",defaultValue = "350628198802200051")
			@RequestParam(value="idcard",required = true) String idcard,
			@ApiParam(name="username",value="姓名",defaultValue = "黄展鹏")
			@RequestParam(value="username",required = true) String username,
			@ApiParam(name="picData",value="图片Base64转化后的输入流",defaultValue = "")
			@RequestBody String picData) throws Exception {
		try {
			/*// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
			String imgFile = "D:/1.jpg";// 待处理的图片
			InputStream in = null;
			byte[] data = null;
			// 读取图片字节数组
			try {
				in = new FileInputStream(imgFile);
				data = new byte[in.available()];
				in.read(data);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			picData = encoder.encode(data);*/
			verifiedService.faceVerified(idcard,username,picData);
			return write(200, "人脸识别成功!");
		} catch (Exception e) {
			return error(-1, e.getMessage());
		}
	}
}

+ 0 - 66
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java

@ -1,66 +0,0 @@
package com.yihu.wlyy.web.common.version;
import io.swagger.annotations.Api;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.Versions;
import com.yihu.wlyy.service.app.version.VersionsService;
import com.yihu.wlyy.web.BaseController;
/**
 * 版本号控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/version", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "版本")
public class VersionController extends BaseController {
	@Autowired
	private VersionsService versionsService;
	/**
	 * 校验APP版本号
	 * @param code 版本类型编码
	 * @param version 当前版本号
	 * @return
	 */
	@RequestMapping(value = "app")
	@ResponseBody
	public String appVersion(String code, double version) {
		try {
			Versions temp = versionsService.findVersionByCode(code);
			if (temp == null) {
				return error(-1, "无效的APP类型失败!");
			}
			if (version > 0) {
				if (temp.getVersionInt() > version) {
					// 有新的版本号
					return write(200, "发现新版本!", "url", temp.getUrl());
				} else {
					// 已是最新版本
					return write(200, "已是最新版本!");
				}
			} else {
				JSONObject json = new JSONObject();
				json.put("version_int", temp.getVersionInt());
				json.put("version_str", temp.getVersionStr());
				json.put("url", temp.getUrl());
				json.put("info", temp.getInfo());
				json.put("size", temp.getSize());
				return write(200, "读取版本号成功!", "data", json);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "版本号校验失败!");
		}
	}
}

+ 0 - 63
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/data/DataHandingService.java

@ -1,63 +0,0 @@
package com.yihu.wlyy.web.data;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
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.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.UUID;
/**
 * Created by Administrator on 2016.10.17.
 */
@Service
public class DataHandingService {
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private DoctorDao doctorDao;
    @Transactional
    public String producePatientAndDoctorPassword() {
        int patientCount=0;
        int patientErrorCount=0;
        int doctorCount=0;
        int doctorErrorCount=0;
        List<Patient> patients= patientDao.findAllIdCardPatientAndNoPassword();
        for (Patient patient:patients){
            String idcard=patient.getIdcard();
            if(!StringUtils.isEmpty(patient.getPassword())||StringUtils.isEmpty(idcard)||(idcard.length()!=15&&idcard.length()!=18)){
                patientErrorCount++;
                continue;
            }
            String password=idcard.substring(idcard.length()-6);
            String salt= UUID.randomUUID().toString().replace("-","");
            patient.setSalt(salt);
            patient.setPassword(MD5.GetMD5Code(password+salt));
            patientCount++;
        }
        patientDao.save(patients);
        List<Doctor> doctors= doctorDao.findAllDoctors();
        for (Doctor doctor:doctors){
            String phone= doctor.getMobile();
            if(!StringUtils.isEmpty(doctor.getPassword())||StringUtils.isEmpty(phone)||phone.length()!=11){
                doctorErrorCount++;
                continue;
            }
            String password=phone.substring(5);
            String salt= UUID.randomUUID().toString().replace("-","");
            doctor.setSalt(salt);
            doctor.setPassword(MD5.GetMD5Code(password+salt));
            doctorCount++;
        }
        doctorDao.save(doctors);
        return "更新患者(默认身份证后六位):"+patientCount+",有身份证异常的患者:"+patientErrorCount+",更新医生(默认电话后六位):"+doctorCount+",有电话号码异常的医生:"+doctorErrorCount;
    }
}

+ 0 - 75
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/data/DataHandlingController.java

@ -1,75 +0,0 @@
package com.yihu.wlyy.web.data;
import com.yihu.wlyy.entity.organization.HospitalDept;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.web.BaseController;
import org.json.JSONArray;
import org.json.JSONObject;
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;
/**
 * Created by Administrator on 2016.10.08.
 * 修改历史数据处理控制器
 */
@Controller
@RequestMapping(value = "/dataHandling", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DataHandlingController extends BaseController {
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private DataHandingService dataHandingService;
    /**
     * 生成签约表中的行政团队的code
     */
    @RequestMapping(value = "produceSignAdminTeamCode")
    @ResponseBody
    public String produceSignAdminTeamCode() {
        try {
            return write(200, familyContractService.produceSignAdminTeamCode());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 生成咨询表中中的行政团队的code
     * @return
     */
    @RequestMapping(value = "produceConsultAdminTeamCode")
    @ResponseBody
    public String produceConsultAdminTeamCode() {
        try {
            return write(200, consultTeamService.produceConsultAdminTeamCode());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 生成医生和患者表中有身份的用户的密码
     * @return
     */
    @RequestMapping(value = "producePatientAndDoctorPassword")
    @ResponseBody
    public String producePatientAndDoctorPasswor() {
        try {
            return write(200, dataHandingService.producePatientAndDoctorPassword());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
}

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

@ -1,1947 +0,0 @@
package com.yihu.wlyy.web.doctor.account;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.profile.DoctorComment;
import com.yihu.wlyy.entity.organization.HospitalDept;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamDao;
import com.yihu.wlyy.repository.doctor.SignPatientLabelDao;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.hospital.HospitalDeptService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.common.account.RoleService;
import com.yihu.wlyy.util.*;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.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 org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.consult.DoctorCommentService;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
/**
 * 用户注册的Controller.
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/doctor", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生")
public class DoctorController extends BaseController {
    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DoctorCommentService doctorCommentService;
    @Autowired
    private DrHealthTeamService drHealthTeamService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private HospitalDeptService hospitalDeptService;
    @Autowired
    private HospitalDeptService deptService;
    @Autowired
    private DoctorWorkTimeService workTimeService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    SignPatientLabelDao labelDao;
    @Autowired
    private CommonUtil CommonUtil;
    /**
     * 社区医院下医生列表查询接口 没分页
     *
     * @param hospital 医院标识
     * @return
     */
    @RequestMapping(value = "getDoctorsByhospitalNoPage")
    @ResponseBody
    public String getDoctorsByhospitalNoPage(
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type) {
        try {
            JSONArray array = new JSONArray();
            List<Map<String, Object>> list = familyContractService.getDoctorsByhospitalNoPage(hospital, name, type);
            if (list != null) {
                for (Map<String, Object> doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.get("id"));
                    // 医生标识
                    json.put("code", doctor.get("code"));
                    // 医生姓名
                    json.put("name", doctor.get("name"));
                    // 所在医院名称
                    json.put("hospital", doctor.get("hospital"));
                    // 所在医院名称
                    json.put("hospital_name", doctor.get("hospital_name"));
                    // 科室名称
                    json.put("dept_name", (doctor.get("dept_name") == null ||
                            StringUtils.isEmpty(doctor.get("dept_name").toString())) ? " " : doctor.get("dept_name"));
                    // 职称名称
                    json.put("job_name", (doctor.get("job_name") == null ||
                            StringUtils.isEmpty(doctor.get("job_name").toString())) ? " " : doctor.get("job_name"));
                    // 头像
                    json.put("photo", doctor.get("photo"));
                    // 简介
                    json.put("introduce", doctor.get("introduce"));
                    // 专长
                    json.put("expertise", doctor.get("expertise"));
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院下医生列表查询接口 有分页
     *
     * @param hospital 医院标识
     * @return
     */
    @RequestMapping(value = "getDoctorsByhospital")
    @ResponseBody
    public String getDoctorsByhospital(
            @RequestParam(required = false) String hospital, //医院code
            @RequestParam(required = false) String city, //市代码
            @RequestParam(required = false) String town, //区代码
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String name, //名称
            @RequestParam(required = true) Long id,
            @RequestParam(required = true) Integer pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = familyContractService.findDoctors(hospital, city, town, name, type, id, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    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.getHospitalName());
                    // 科室名称
                    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());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院列表查询接口
     *
     * @param type     医院类型:0全部,1大医院,2社区医院
     * @param province 患标识
     * @param city     城市标识
     * @param key      搜索关键字,用于搜索医院名称
     * @return
     */
    @RequestMapping(value = "hospitals")
    @ResponseBody
    public String hospitals(
            int type,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String town,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Hospital> list = familyContractService.findHospitals(type, province, city, town, key, id, pagesize);
            if (list != null) {
                for (Hospital hospital : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    // 医院标识
                    json.put("code", hospital.getCode());
                    // 医院名称
                    json.put("name", hospital.getName());
                    // 省名
                    json.put("province_name", hospital.getProvinceName());
                    // 城市名
                    json.put("city_name", hospital.getCityName());
                    // 区县名
                    json.put("town_name", hospital.getTownName());
                    // 详细地址
                    json.put("address", hospital.getAddress());
                    // 简介
                    json.put("intro", hospital.getIntro());
                    // 医院图片
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "获取医院列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院列表失败!");
        }
    }
    /**
     * 查询存在医生的医院列表
     *
     * @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) {
            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 = "1") 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) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据机构查找科室
     *
     * @param hospital 机构code
     * @param key      科室名称
     * @param id       主键
     * @param pagesize 每页显示条数
     * @return
     */
    @RequestMapping(value = "findDeptByHsoptail")
    @ResponseBody
    public String findDeptByHsoptail(
            String hospital,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<HospitalDept> list = hospitalDeptService.findDeptByHsoptail(hospital, key, id, pagesize);
            if (list != null) {
                for (HospitalDept dept : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", dept.getId());
                    // 科室标识
                    json.put("code", dept.getCode());
                    // 科室名称
                    json.put("name", dept.getName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 根据科室查找医生
     *
     * @param dept     科室code
     * @param key      医生名称
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @RequestMapping(value = "findDoctorByDept")
    @ResponseBody
    public String findDoctorByDept(
            @RequestParam(required = false) String dept,
            @RequestParam(required = false) String hosptial,
            @RequestParam(required = false) String key,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = doctorInfoService.findDoctorByDept(dept, hosptial, key, page, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 名医列表
     *
     * @param key      医生名称
     * @param type     是否是名医 1是  0不是
     * @param level    医生的等级 1专科医生,2全科医生,3健康管理师 不传默认是全部
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @RequestMapping(value = "findFamousDoctor")
    @ResponseBody
    public String findFamousDoctor(
            @RequestParam(required = false) String key,
            @RequestParam(required = false) Integer level,
            Integer type,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            List<Doctor> list = doctorInfoService.findFamousDoctorList(key, type, page, pagesize, level);
            if (list != null) {
                for (Doctor doctor : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    json.put("expertise", doctor.getExpertise());
                    json.put("isworking", 1);
                    array.put(json);
                }
            }
            return write(200, "获取名医列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取名医列表失败!");
        }
    }
    /**
     * 修改密码
     *
     * @param oldpwd 旧密码
     * @param newpwd 新密码
     * @return
     */
    @RequestMapping(value = "updatepwd")
    @ResponseBody
    @ObserverRequired
    public String updatepwd(String oldpwd, String newpwd) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "修改失败!");
            } else {
                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(doctor.getSalt()), oldpwd);
                if (StringUtils.equals(doctor.getPassword(), encodePWD)) {
                    doctor.setPassword(newpwd);
                    doctorInfoService.updateDoctorPwd(doctor);
                    return success("修改成功!");
                } else {
                    return error(-1, "修改失败:旧密码错误!");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "修改失败!");
        }
    }
    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "loginout")
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(2, getUID());
            return success("已成功退出!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfo")
    @ResponseBody
    public String baseinfo(
            @RequestParam(required = false) String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                code = getUID();
            }
            Doctor temp = doctorInfoService.findDoctorByCode(code);
            Integer leader = doctorAdminTeamDao.findLeader(code);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生手机号码
                json.put("mobile", temp.getMobile());
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", temp.getPhoto());
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院code
                json.put("hospital", temp.getHospital());
                // 设置医院名称
                json.put("hospitalName", temp.getHospitalName());
                // 设置部门名称
                json.put("deptName", StringUtils.isNotEmpty(temp.getDeptName()) ? temp.getDeptName() : "");
                // 设置职称
                json.put("jobName", StringUtils.isNotEmpty(temp.getJobName()) ? temp.getJobName() : "");
                // 设置医生专长
                json.put("expertise", StringUtils.isNotEmpty(temp.getExpertise()) ? temp.getExpertise() : "");
                // 设置医生简介
                json.put("introduce", StringUtils.isNotEmpty(temp.getIntroduce()) ? temp.getIntroduce() : "");
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                // 审核总数
                json.put("signed_amount", familyContractService.countAmountSigned(getUID()));
                // 等审核总数
                json.put("unsign_amount", familyContractService.countAmountUnsign(getUID()));
                // 咨询统计
                Map<String, Long> consultCount = consultTeamService.getAllCount(getUID());
                // 咨询总数
                json.put("consultAmount", consultCount.get("all"));
                // 当天咨询数
                json.put("consultAmountToday", consultCount.get("today"));
                //身份类型
                json.put("level", temp.getLevel().intValue());
                //身份证号
                json.put("idcard", temp.getIdcard());
                //是否认证
                json.put("isCertified", temp.getIscertified());
                //是否名医
                json.put("isFamous", temp.getIsFamous());
                //是否医生提示 提示过是1 其他都是0
                json.put("isPasswordPrompt", StringUtils.isEmpty(temp.getIsPasswordPrompt()) ? "0" : temp.getIsPasswordPrompt());
                //获取医生角色和区域权限
                List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(temp.getCode());
                json.put("userRole", roleMap);
                json.put("evaluateScore", temp.getEvaluateScore());
//                是否团队长
                json.put("isLeader", leader == null ? "0" : "1");
//                团队长所管辖的团队code 一个团队长只管辖一个团队
                json.put("adminTeamCode", leader);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfoCount")
    @ResponseBody
    public String baseinfoCount(
            String doctorType) {
        try {
            Doctor temp = doctorInfoService.findDoctorByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                int count = familyContractService.countAmountSigned(getUID());
                // 审核总数
                json.put("signed_amount", count);
                int count1 = familyContractService.countAmountUnsign(getUID());
                // 等审核总数
                json.put("unsign_amount", count1);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 患者基本信息保存
     *
     * @param photo     頭像
     * @param sex       性別
     * @param expertise 专长
     * @param introduce 简介
     * @param province  省标识
     * @param city      市标识
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    @ObserverRequired
    public String save(
            @RequestParam(required = false) String photo,
            @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String expertise,
            @RequestParam(required = false) String introduce,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String mobile) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (StringUtils.isNotEmpty(mobile)) {
                if (!mobile.equals(doctor.getMobile())) {
                    if (doctorInfoService.findNormalByMobile(mobile) != null) {
                        return error(-2, "该手机号码已被注册!");
                    }
                    doctor.setMobile(mobile);
                }
            }
            // 设置头像
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
                if (StringUtils.isNotEmpty(photo)) {
                    doctor.setPhoto(photo);
                }
            }
            // 设置性别
            if (sex != null) {
                doctor.setSex(sex);
            }
            // 设置生日
            // if (StringUtils.isNotEmpty(birthday)) {
            // doctor.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
            // }
            // 设置医生专长
            if (StringUtils.isNotEmpty(expertise)) {
                doctor.setExpertise(expertise);
            }
            // 设置介绍内容
            if (StringUtils.isNotEmpty(introduce)) {
                doctor.setIntroduce(introduce);
            }
            // 设置省份标识
            if (StringUtils.isNotEmpty(province)) {
                doctor.setProvince(province);
            }
            // 设置城市标识
            if (StringUtils.isNotEmpty(city)) {
                doctor.setCity(city);
            }
            // 设置区县标识
            // if (StringUtils.isNotEmpty(town)) {
            // doctor.setTown(town);
            // }
            // 设置医院标识
            // if (StringUtils.isNotEmpty(hospital)) {
            // doctor.setHospital(hospital);
            // }
            // // 设置部门标识
            // if (StringUtils.isNotEmpty(dept)) {
            // doctor.setDept(dept);
            // }
            // // 设置职称
            // if (StringUtils.isNotEmpty(job)) {
            // doctor.setJob(job);
            // }
            if (doctorInfoService.updateDoctor(doctor) != null) {
                // 修改成功
                return write(200, "保存成功!", "data", doctor.getPhoto());
            } else {
                // 注册失败
                return error(-1, "保存失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 红黄绿标患者数查询接口
     *
     * @return
     */
    @RequestMapping(value = "patients")
    @ResponseBody
    public String patients() {
        try {
            return write(200, "查询成功!", "data", familyContractService.amountPatients(getUID()));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 患者评价查询接口
     *
     * @param id       最后一个id
     * @param pagesize 分页大小
     * @return
     */
    @RequestMapping(value = "comments")
    @ResponseBody
    public String comments(Integer id, Integer pagesize) {
        try {
            Page<DoctorComment> page = doctorCommentService.findByDoctor(getUID(), id, pagesize);
            JSONArray array = new JSONArray();
            if (page != null) {
                for (DoctorComment dc : page) {
                    if (dc == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // id
                    json.put("id", dc.getId());
                    // 评价人姓名
                    json.put("name", dc.getUname());
                    // 设置评价内容
                    json.put("content", dc.getContent());
                    // 评价星级
                    json.put("star", dc.getStar());
                    // 评价类型:1视频咨询评价、2图文咨询评价
                    json.put("type", dc.getType());
                    // 评价时间
                    json.put("czrq", DateUtil.dateToStrLong(dc.getCzrq()));
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", page, array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
//	 /**
//	 * 医生三师工作组查询接口
//	 * @return
//	 */
//	 @RequestMapping(value = "teams")
//	 @ResponseBody
//	 public String teams() {
//	 try {
//	 List<DoctorTeam> teams = doctorTeamService.getDoctorTeams(getUID());
//	 JSONArray array = new JSONArray();
//	 if (teams != null) {
//	 for (DoctorTeam team : teams) {
//	 if (team == null) {
//	 continue;
//	 }
//	 JSONObject json = new JSONObject();
//	 json.put("icon", team.getIcon());
//	 json.put("code", team.getCode());
//	 json.put("name", team.getName());
//	 json.put("doctor", team.getDoctorName());
//	 array.put(json);
//	 }
//	 }
//	 return write(200, "查询成功!", "list", array);
//	 } catch (Exception e) {
//	 error(e);
//	 return error(-1, "查询失败!");
//	 }
//	 }
    // /**
    // * 查询三师团队下的医生列表
    // * @param team
    // * @return
    // */
    // @RequestMapping(value = "team_members")
    // @ResponseBody
    // public String teamMembers(String team) {
    // try {
    // List<Doctor> members = doctorTeamService.findTeamMembersByCode(team);
    // JSONArray array = new JSONArray();
    // if (members != null) {
    // for (Doctor member : members) {
    // if (member == null) {
    // continue;
    // }
    // JSONObject json = new JSONObject();
    // json.put("photo", member.getPhoto());
    // json.put("code", member.getCode());
    // json.put("name", member.getName());
    // array.put(json);
    // }
    // }
    // return write(200, "查询成功!", "list", array);
    // } catch (Exception e) {
    // error(e);
    // return error(-1, "查询失败!");
    // }
    // }
    /**
     * 根据类别获取医院列表
     *
     * @param type
     * @param query    查询条件 医院名称
     * @param id
     * @param pageSize 页数
     * @return
     */
    @RequestMapping(value = "/hospital_list")
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) Integer type,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) long id,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Hospital> hospitalList = hospitalService.getHospitalList(query, type, id, pageSize);
            JSONArray array = new JSONArray();
            if (hospitalList != null) {
                for (Hospital hospital : hospitalList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    json.put("code", hospital.getCode());
                    json.put("name", hospital.getName());
                    json.put("province", hospital.getProvince());
                    json.put("provinceName", hospital.getProvinceName());
                    json.put("city", hospital.getCity());
                    json.put("cityName", hospital.getCityName());
                    json.put("town", hospital.getTown());
                    json.put("townName", hospital.getTownName());
                    json.put("level", hospital.getLevel());
                    String levelName = "";
                    switch (hospital.getLevel()) {
                        case 1:
                            levelName = "医院";
                            break;
                        case 2:
                            levelName = "社区医院";
                            break;
                    }
                    json.put("levelName", levelName);
                    json.put("address", hospital.getAddress());
                    json.put("intro", hospital.getIntro());
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 邀请医生咨询
     *
     * @param patientCode
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/hospital_list_type")
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = true) int consultType,
            @RequestParam(required = true) String patientCode,
            @RequestParam(required = false) String name,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            if (doctorType == 3) {
                //查找所有的全科医生
                Doctor doctor = doctorInfoService.getDoctor(consultType, patientCode);
                return null;
            } else if (doctorType == 2) {
                //查找所有的专科医生
                Page<Doctor> doctorList = doctorInfoService.getDoctorListByPatientCode(consultType, patientCode, name, page, pageSize);
                JSONArray array = new JSONArray();
                if (doctorList != null) {
                    for (Doctor doctor : doctorList) {
                        JSONObject json = new JSONObject();
                        json.put("id", doctor.getId());
                        json.put("code", doctor.getCode());
                        json.put("name", doctor.getName());
                        json.put("photo", doctor.getPhoto());
                        json.put("sex", doctor.getSex());
                        String sexName = "";
                        switch (doctor.getSex()) {
                            case 1:
                                sexName = "男";
                                break;
                            case 2:
                                sexName = "女";
                                break;
                        }
                        json.put("sexName", sexName);
                        json.put("job", doctor.getJob());
                        json.put("jobName", doctor.getJobName());
                        json.put("hospital", doctor.getHospital());
                        json.put("hospitalName", doctor.getHospitalName());
                        json.put("dept", doctor.getDept());
                        json.put("deptName", doctor.getDeptName());
                        array.put(json);
                    }
                }
                return write(200, "查询成功!", "list", array);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            error(ex);
            return error(-1, "查询失败!");
        }
        return null;
    }
    /**
     * 根据医院标识获取医生信息
     *
     * @param hospital 医院标识
     * @param query    查询条件 :医生名称
     * @param page
     * @param pageSize 页数
     * @return
     */
    @RequestMapping(value = "/doctor_list")
    @ResponseBody
    public String getDoctorByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(query, hospital, page, pageSize,2);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("evaluateScore", doctor.getEvaluateScore());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 登录患者获取三师信息
     *
     * @return
     */
    @RequestMapping(value = "teachers")
    @ResponseBody
    public String teachers(String patient) {
        try {
            // 查询签约信息
            SignFamily signContract = familyContractService.findBySsPatient(patient);
            if (signContract == null) {
                return error(1, "无三师签约信息");
            }
            JSONObject doctorJson = new JSONObject();
            // 设置签约日期
            doctorJson.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
            // 签约编号
            doctorJson.put("team_code", signContract.getTeamCode());
            // 查询三师医生信息
            List<Doctor> doctors = drHealthTeamService.findTeamDoctors(patient, 1);
            JSONArray jsonArray = new JSONArray();
            if (doctors != null) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    // 类型:1专科医生,2全科医生,3健康管理师
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    jsonArray.put(json);
                }
            }
            doctorJson.put("list", jsonArray);
            return write(200, "查询成功!", "data", doctorJson);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * @param type 医生类别 1专科医生,2全科医生,3健康管理师
     * @return
     */
    @RequestMapping(value = "/doctor_combobox")
    @ResponseBody
    public String getDoctorCombobxByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String type) {
        try {
            List<Doctor> doctorList = doctorInfoService.getDoctorCombobxByHospital(type, hospital);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 患者端 专科医生列表
     *
     * @param name
     * @param paitentCode
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/doctor_1_list")
    @ResponseBody
    public String doctor_1_list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String paitentCode,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(name, null, page, pageSize,1);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
//					json.put("photo", doctor.getPhoto());
//					json.put("sex", doctor.getSex());
//					String sexName = "";
//					switch (doctor.getSex()) {
//						case 1:
//							sexName = "男";
//							break;
//						case 2:
//							sexName = "女";
//							break;
//					}
//					//json.put("sexName", sexName);
//					json.put("job", doctor.getJob());
//					json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
//					json.put("dept", doctor.getDept());
//					json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 把专科医生拉到团队里面
     *
     * @param teamCode   团队code
     * @param doctor     专科医生code
     * @param sickNCode  慢病code
     * @param sickName   慢病名字
     * @param doctorName 专科医生名字
     * @return
     */
    @RequestMapping(value = "/doctor_1_Toteam")
    @ResponseBody
    @ObserverRequired
    public String doctor_1_Toteam(
            @RequestParam(required = false) String teamCode, //没用
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = false) String groupCode,//没用
            @RequestParam(required = true) String doctor,
            @RequestParam(required = true) String doctorName,
            @RequestParam(required = true) String sickName,
            @RequestParam(required = true) String sickNCode) {
        try {
            doctorInfoService.doctor_1_Toteam(teamCode, doctor, doctorName, groupCode, super.getIMEI(), parientCode, sickName, sickNCode);
            return write(200, "成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据病人ID查找团队里面的全科医生
     *
     * @param parientCode 病人code
     * @return
     */
    @RequestMapping(value = "/getDoctor2ByParient")
    @ResponseBody
    public String getDoctor2ByParient(
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = true) String consultCode) {
        try {
            Doctor doctor = doctorInfoService.getDoctor2ByParient(parientCode, consultCode);
            JSONObject json = null;
            if (doctor != null) {
                json = new JSONObject(doctor);
                if (json.has("password")) {
                    json.remove("password");
                }
                if (json.has("salt")) {
                    json.remove("salt");
                }
                JSONObject iswork = workTimeService.isDoctorWorking(doctor.getCode());
                if (iswork.getString("status").equals("1")) {
                    json.put("isworking", 1);
                } else {
                    json.put("isworking", 0);
                }
            }
            return write(200, "查询成功!", "doctor", json);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个
     *
     * @param parientCode 病人code
     * @return
     */
    @RequestMapping(value = "/getDoctor1ByParient")
    @ResponseBody
    public String getDoctor1ByParient(
            @RequestParam(required = true) String consultCode,
            @RequestParam(required = true) String parientCode,
            Integer page,
            Integer pageSize) {
        try {
            Map<String, Object> doctorList = doctorInfoService.getDoctor1ByParient(consultCode, parientCode, page, pageSize);
            JSONObject jo = new JSONObject();
            List<JSONObject> doctors = doctorList.get("doctors") != null ? (List<JSONObject>) doctorList.get("doctors") : new ArrayList<>();
            for (JSONObject obj : doctors) {
                JSONObject iswork = workTimeService.isDoctorWorking(obj.getString("code"));
                if (iswork.getString("status").equals("1")) {
                    obj.put("isworking", 1);
                } else {
                    obj.put("isworking", 0);
                }
            }
            jo.put("totalPage", doctorList.get("totalPage"));
            jo.put("doctors", doctors);
            return write(200, "查询成功!", "data", jo);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 验证患者的名字,身份证和医保卡
     *
     * @return
     */
    @RequestMapping(value = "/validatePatient")
    @ResponseBody
    public String validatePatient(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) String idcard,
            @RequestParam(required = true) String ssc) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致,请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0 && ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                    return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            return write(200, "查询成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 得到 健康咨询  签约消息 健康体征 重要通知 和讨论组的消息数目
     */
    @RequestMapping(value = "/getAllMessageNum")
    @ResponseBody
    public String getAllMessageNum(
            String doctorCode,
            String doctorType) {
        try {
            JSONObject json = new JSONObject();
//			if("2".equals(doctorType)){
//				//全科医生
//				json.put("healthConsult", doctor.getCode());//健康咨询
//				json.put("sign", doctor.getName());//签约消息
//				json.put("healthTZ", doctor.getPhoto());//健康体征
//				json.put("importantMessage", doctor.getId());//重要通知
//				json.put("groupMessage", doctor.getId());//讨论组消息
//			}else{
//				//健康管理师
//				json.put("healthConsult", doctor.getCode());//健康咨询
//				json.put("sign", doctor.getName());//签约消息
//				json.put("healthTZ", doctor.getPhoto());//健康体征
//				json.put("importantMessage", doctor.getId());//重要通知
//				json.put("groupMessage", doctor.getId());//讨论组消息
//			}
            return write(200, "查询成功!", "doctors", json);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据身份证号
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/patient_cardno")
    @ResponseBody
    public String getPatientCardNo(String idcard) {
        try {
            String cardNo = "";
            Patient patient = patientInfoService.findByIdcard(idcard);
            if (patient == null || StringUtils.isEmpty(patient.getSsc())) {
                SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18(idcard);
                if (socialSecurityInfo != null) {
                    cardNo = socialSecurityInfo.getCardno();
                }
            } else {
                cardNo = patient.getSsc();
            }
            return write(200, "查询成功!", "data", cardNo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据level查找机构下的类别医生
     *
     * @param hospital
     * @param level
     * @return
     */
    @RequestMapping(value = "/findDoctorByLevelAndHospital")
    @ResponseBody
    public String findDoctorByLevelAndHospital(String hospital, Integer level) {
        try {
            List<Doctor> doctorList = doctorInfoService.findDoctorByLevelAndHospital(hospital, level);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "doctors", array);
        } catch (Exception e) {
            return error(-1, "查询失败!");
        }
    }
    /**
     * 更新身份证号
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/idcard_update")
    @ResponseBody
    @ObserverRequired
    public String updateIdcard(String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateDoctorIdcard(idcard, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生性别
     *
     * @param sex
     * @return
     */
    @RequestMapping(value = "/sex_update")
    @ResponseBody
    @ObserverRequired
    public String updateSex(int sex) {
        try {
            if (doctorInfoService.updateSex(sex, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生介绍
     *
     * @param introduce
     * @return
     */
    @RequestMapping(value = "/introduce_update")
    @ResponseBody
    @ObserverRequired
    public String updateIntroduce(String introduce) {
        try {
            if (StringUtils.isEmpty(introduce)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateIntroduce(introduce, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生专长
     *
     * @param expertise
     * @return
     */
    @RequestMapping(value = "/expertise_update")
    @ResponseBody
    @ObserverRequired
    public String updateExpertise(String expertise) {
        try {
            if (StringUtils.isEmpty(expertise)) {
                return error(-1, "专长不能为空");
            }
            if (doctorInfoService.updateExpertise(expertise, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 设置给医生名医
     *
     * @param doctorCode 医生code
     * @param status     1 是 0否
     * @return
     */
    @RequestMapping(value = "/setFamous")
    @ResponseBody
    @ObserverRequired
    public String setFamous(String doctorCode, Integer status) {
        try {
            doctorInfoService.setFamous(doctorCode, status);
            return write(200, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 转换团队中的健康管理师
     *
     * @param newDoctorCode 新的健康管理师的code
     * @param oldDoctorCode 旧的健康管理师的code
     * @param patients      患者code 多个逗号分隔
     * @return
     */
    @RequestMapping(value = "/updateTeamHealthDoctors")
    @ResponseBody
    @ObserverRequired
    public String updateTeamHealthDoctors(String newDoctorCode,
                                          @RequestParam(required = false) String oldDoctorCode,
                                          @RequestParam(required = false) String patients,
                                          @RequestParam(required = false) String isAll) {
        try {
            String status = redisTemplate.opsForValue().get("jianguanshifenpei:" + getUID());
            status = StringUtils.isEmpty(status) ? "0" : status;
            if (!status.equals("1")) {
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "1");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 20, TimeUnit.MINUTES);
            } else {
                return error(-2, "正在分配,请勿重复操作");
            }
            if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")) {
                int result = doctorInfoService.updateTeamHealthDoctorsAll(newDoctorCode, getUID());
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                if (result == 1) {
                    return write(200, "分配健管师成功");
                } else if (result == 2) {
                    return write(200, "部分居民因没有服务团队分配失败");
                }
            } else {
                if (StringUtils.isEmpty(patients)) {
                    redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                    redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                    return error(-1, "居民不能为空");
                }
                Map<String, Integer> returnMap = doctorInfoService.updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, getUID());
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                return write(200, "已成功处理" + returnMap.get("success") + "个居民," + returnMap.get("error") + "个居民因有未结束的咨询,无法处理");
            }
            redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
            redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return write(200, "更新成功");
        } catch (Exception e) {
            error(e);
            redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
            redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return error(-1, "更新失败");
        }
    }
    /**
     * 转换团队中的全科医生
     *
     * @param newDoctorCode 新的全科医生的code
     * @param oldDoctorCode 旧的全科医生的code
     * @param patients      患者code 多个逗号分隔
     * @return
     */
    @RequestMapping(value = "/updateTeamDoctors")
    @ResponseBody
    @ObserverRequired
    public String updateTeamDoctors(String newDoctorCode,
                                    String oldDoctorCode,
                                    String patients) {
        try {
            String status = redisTemplate.opsForValue().get("quankeyishengfenpei:" + getUID());
            status = StringUtils.isEmpty(status) ? "0" : status;
            if (!status.equals("1")) {
                redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "1");
                redisTemplate.expire("quankeyishengfenpei:" + getUID(), 20, TimeUnit.MINUTES);
            } else {
                return error(-2, "正在分配,请勿重复操作");
            }
            Map<String, Integer> returnMap = doctorInfoService.updateTeamDoctors(newDoctorCode, oldDoctorCode, patients, getUID());
            redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "0");
            redisTemplate.expire("quankeyishengfenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return write(200, "已成功处理" + returnMap.get("success") + "个居民," + returnMap.get("error") + "个居民因有未结束的咨询,无法处理");
        } catch (Exception e) {
            redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "0");
            redisTemplate.expire("quankeyishengfenpei:" + getUID(), 10, TimeUnit.MINUTES);
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 医生手机号变更
     *
     * @param mobile  新手机号
     * @param captcha 验证码
     * @param type    1:变更手机号  2:绑定手机号
     * @return
     */
    @RequestMapping(value = "/mobile_update", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String changeDoctorMobile(String mobile, String captcha, int type) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "请填写新手机号码");
            }
            if (StringUtils.isEmpty(captcha)) {
                return error(-1, "请输入验证码");
            }
            if (type != 1 && type != 2) {
                return error(-1, "操作类型参数错误");
            }
            int result = doctorInfoService.changeMobile(getUID(), mobile, captcha, type);
            if (result == -1) {
                return error(-1, "医生信息查找失败");
            } else if (result == -2) {
                return error(-1, "手机已注册");
            } else if (result == -3) {
                return error(-1, "验证码错误");
            } else if (result == 1) {
                return write(200, "手机号更新成功");
            } else {
                return write(-1, "手机号更新失败");
            }
        } catch (Exception e) {
            return error(-1, "手机号更新失败");
        }
    }
    /**
     * 手机号是否注册
     *
     * @param mobile 手机号
     * @return
     */
    @RequestMapping("/is_mobile_register")
    @ResponseBody
    public String isMobileRegister(String mobile) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号码不能为空");
            }
            int result = doctorInfoService.isMobileRegister(mobile);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 修改密码
     *
     * @param newPassword1 新密码1
     * @param newPassword2 新密码2
     * @param oldPassword  旧密码
     * @param doctorCode   医生code
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updatePassword(String newPassword1,
                                 String newPassword2,
                                 String oldPassword,
                                 String doctorCode) {
        try {
            newPassword1 = RSAUtils.getInstance(doctorInfoService).decryptString(newPassword1);
            newPassword2 = RSAUtils.getInstance(doctorInfoService).decryptString(newPassword2);
            oldPassword = RSAUtils.getInstance(doctorInfoService).decryptString(oldPassword);
            newPassword1 = StringUtils.reverse(newPassword1);
            newPassword2 = StringUtils.reverse(newPassword2);
            oldPassword = StringUtils.reverse(oldPassword);
            doctorInfoService.updatePassword(newPassword1, newPassword2, oldPassword, doctorCode);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    /**
     * 当前医生是否与居民签约
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/is_patient_signed")
    @ResponseBody
    public String isPatientSign(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }
            boolean isSigned = doctorInfoService.isPatientSigned(patient, getUID());
            return write(200, "查询成功", "data", isSigned ? "1" : "0");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 心跳接口
     *
     * @return
     */
    @RequestMapping(value = "/islive")
    @ResponseBody
    public String islive() {
        try {
            return write(200, "成功");
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 分配及转移健管师
     *
     * @param newDoctorCode
     * @param oldDoctorCode
     * @param patients      多个患者用,隔开
     * @param group         团队标签分组名称
     * @param sendCount
     * @param teamId
     * @param typeId
     * @return
     */
    @RequestMapping(value = "/allotOrMoveHealth")
    @ResponseBody
    @ObserverRequired
    public String allotOrMoveHealth(
            @RequestParam String newDoctorCode,
            @RequestParam(required = false) String oldDoctorCode,
            @RequestParam(required = false) String patients,
            @RequestParam(required = false) String group,
            @RequestParam(required = false) Integer sendCount,
            @RequestParam String teamId,
            @RequestParam(required = false) String typeId) {
        try {
            Long teamCode = Long.parseLong(teamId);
//            patients不为空是由团队中分配及转移的搜索居民 转移健管师 否则是分组分配健管师
            if (StringUtils.isNotEmpty(patients)) {
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            } else if(StringUtils.isNotEmpty(group)){
//            按条件获取居民
                patients = "";
                if (StringUtils.isEmpty(teamId)||StringUtils.isEmpty(typeId)||sendCount==null){
                    return write(-1, "参数不能为空!");
                }
                JSONObject list = familyContractService.findNoHealthSignFamilyHealth(null, typeId, null, teamCode);
                List<SignPatientLabel> s = labelDao.findByLabelTypeAndStatusAndTeamCode(typeId, 1, teamCode);
                for (SignPatientLabel label :s) {
//                    String labelName = label.getLabelCode();
                    String labelName = label.getLabelName();
                    if (labelName.equals(group)){
                        JSONArray jsonArray = list.getJSONArray(labelName);
                        for (int i=0;i<sendCount;i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String  patient = jsonObject.get("code").toString();
//                转移时需要剔除处于咨询状态的居民
                            if (StringUtils.isNotEmpty(oldDoctorCode)){
                                ConsultTeam consultTeam = consultTeamService.getConsultByPatientAndDoctor(patient, oldDoctorCode);
                                if (consultTeam == null) {
//                                   不是咨询状态
                                    patients+=(patient+",");
                                }
                            }else {
                                patients+=(patient+",");
                            }
                        }
                    }
                }
                patients =  patients.substring(0,patients.length()-1);
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            }else {
                List<SignFamily> signFamily = familyContractService.findNoHealthSignFamilyNum(teamCode);
                patients = "";
                if (StringUtils.isEmpty(teamId)||StringUtils.isEmpty(typeId)||sendCount==null){
                    return write(-1, "参数不能为空!");
                }
                for (SignFamily patient:signFamily) {
                    String code = patient.getPatient();
                    patients+=(code+",");
                }
                patients =  patients.substring(0,patients.length()-1);
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败");
        }
    }
    /**
     * 设置审方密码
     * @param password
     * @return
     */
    @RequestMapping(value = "/setCheckPassword", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String setCheckPassword(@RequestParam String password){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "密码设置失败!");
            }
            doctorInfoService.setCheckPassword(doctor,password);
            return write(200, "密码设置成功");
        }catch (Exception e){
            error(e);
            return invalidUserException(e, -1, "密码设置失败");
        }
    }
    /**
     * 修改审方密码
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/updateCheckPassword", method = RequestMethod.POST)
    public String updateCheckPassword(@RequestParam String oldPassword,@RequestParam String newPassword){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "修改审方密码失败!");
            } else {
                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(doctor.getCheckSalt()), oldPassword);
                if (StringUtils.equals(doctor.getCheckPassword(), encodePWD)) {
                    doctorInfoService.setCheckPassword(doctor,newPassword);
                    return write(200, "密码设置成功");
                } else {
                    return error(-1, "修改失败:审方旧密码错误!");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "修改失败!");
        }
    }
}

+ 0 - 217
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/archives/DoctorArchivesController.java

@ -1,217 +0,0 @@
package com.yihu.wlyy.web.doctor.archives;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.service.app.archives.PatientEventService;
import com.yihu.wlyy.service.app.archives.PatientRecordService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
/**
 * Created by hzp on 2016/11/24.
 */
@Controller
@RequestMapping(value = "/doctor/archives", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-健康档案服务接口")
public class DoctorArchivesController extends BaseController {
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private PatientEventService patientEventService;
    @ApiOperation("获取门诊记录/住院记录(基卫+APP)")
    @RequestMapping(value = "/event", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getAllEvent(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                              @RequestParam(value="patient",required = false) String patient,
                              @ApiParam(name="type",value="类型",defaultValue = "")
                              @RequestParam(value="type",required = false) String type,
                              @ApiParam(name="page",value="第几页",defaultValue = "1")
                              @RequestParam(value="page",required = true) String page,
                              @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                              @RequestParam(value="pageSize",required = true) String pageSize,
                              @ApiParam(name="lastTime",value="最后一条时间",defaultValue = "2010-10-10 00:00:00")
                              @RequestParam(value="lastTime",required = false) String lastTime) {
        try {
            List<Map<String,String>> result = patientRecordService.getAllEvent(patient,type,page,pageSize,lastTime);
            return write(200, "获取就诊记录成功!", "data", result);
        } catch (Exception e) {
            if(e.getMessage().indexOf("卡号尚未在医疗机构注册过")>0)
            {
                return error(-1,"对不起,您的社保卡有变更,请改天再试");
            }
            else if(e.getMessage().startsWith("error"))
            {
                return error(-1,e.getMessage());
            }
            else{
                return error(-1,"获取门/急诊数据失败!");
            }
        }
    }
    @RequestMapping(value = "/event/healthData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取健康档案详情(基卫)")
    public String getHealthData(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                                @RequestParam(value="patient",required = false) String patient,
                                @ApiParam(name="event",value="事件ID",defaultValue = "")
                                @RequestParam(value="event",required = true) String event,
                                @ApiParam(name="catalog",value="档案类型",defaultValue = "")
                                @RequestParam(value="catalog",required = true) String catalog,
                                @ApiParam(name="serial",value="该类别顺序号,默认填1",defaultValue = "1")
                                @RequestParam(value="serial",required = true) String serial) {
        try {
            String result = patientRecordService.getHealthData(patient, event, catalog, serial);
            return write(200, "获取健康档案详情成功!", "data", result);
        } catch (Exception e) {
            if(e.getMessage().indexOf("卡号尚未在医疗机构注册过")>0)
            {
                return error(-1,"对不起,您的社保卡有变更,请改天再试");
            }
            else if(e.getMessage().startsWith("error"))
            {
                return error(-1,e.getMessage());
            }
            else{
                return error(-1,"获取健康档案详情失败!");
            }
        }
    }
    @RequestMapping(value = "/event/catalog", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("通过事件号获取档案类型列表(基卫)")
    public String getEventCatalog(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                                  @RequestParam(value="patient",required = false) String patient,
                                  @ApiParam(name="event",value="事件ID",defaultValue = "")
                                  @RequestParam(value="event",required = true) String event) {
        try {
            List<Map<String,String>> result = patientRecordService.getEventCatalog(patient,event);
            return write(200, "通过事件号获取档案类型列表成功!", "data", result);
        } catch (Exception e) {
            if(e.getMessage().indexOf("卡号尚未在医疗机构注册过")>0)
            {
                return error(-1,"对不起,您的社保卡有变更,请改天再试");
            }
            else if(e.getMessage().startsWith("error"))
            {
                return error(-1,e.getMessage());
            }
            else{
                return error(-1,"获取档案类型列表失败!");
            }
        }
    }
    @RequestMapping(value = "/event/drug", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取用药记录(基卫)")
    public String getDrugsList(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                               @RequestParam(value="patient",required = false) String patient,
                               @ApiParam(name="page",value="第几页",defaultValue = "1")
                               @RequestParam(value="page",required = true) String page,
                               @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                               @RequestParam(value="pageSize",required = true) String pageSize) {
        try {
            String result = patientRecordService.getDrugsListPage(patient, page, pageSize);
            return write(200, "获取用药记录成功!", "data", result);
        } catch (Exception e) {
            if(e.getMessage().indexOf("卡号尚未在医疗机构注册过")>0)
            {
                return error(-1,"对不起,您的社保卡有变更,请改天再试");
            }
            else if(e.getMessage().startsWith("error"))
            {
                return error(-1,e.getMessage());
            }
            else{
                return error(-1,"获取用药记录失败!");
            }
        }
    }
    @ApiOperation("获取检查检验报告(基卫+APP)")
    @RequestMapping(value = "/event/report", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getReportList(@ApiParam(name="patient",value="患者代码",defaultValue = "")
                                @RequestParam(value="patient",required = false) String patient,
                                @ApiParam(name="page",value="第几页",defaultValue = "1")
                                @RequestParam(value="page",required = true) String page,
                                @ApiParam(name="pageSize",value="每页几行",defaultValue = "10")
                                @RequestParam(value="pageSize",required = true) String pageSize,
                                @ApiParam(name="lastTime",value="最后一条时间",defaultValue = "2010-10-10 00:00:00")
                                    @RequestParam(value="lastTime",required = false) String lastTime)
    {
        try {
            List<Map<String,String>> result = patientRecordService.getExamAndLabReport(patient, page, pageSize,lastTime);
            return write(200, "获取检查检验报告成功!", "data", result);
        } catch (Exception e) {
            if(e.getMessage().indexOf("卡号尚未在医疗机构注册过")>0)
            {
                return error(-1,"对不起,您的社保卡有变更,请改天再试");
            }
            else if(e.getMessage().startsWith("error"))
            {
                return error(-1,e.getMessage());
            }
            else{
                return error(-1,"获取检查检验报告失败!");
            }
        }
    }
    /******************************************* 就诊事件管理 **********************************************************/
    @RequestMapping(value = "/event/detail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取就诊事件详情")
    public String getEventDetail(@ApiParam(name="event",value="事件ID",defaultValue = "")
                                 @RequestParam(value="event",required = true) String event)
    {
        try {
            JSONObject result = patientEventService.getEventDetail(event);
            return write(200, "获取就诊事件详情成功!", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取就诊事件详情失败!");
        }
    }
    @RequestMapping(value = "/event/save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("保存就诊事件详情")
    @ObserverRequired
    public String saveEventDetail(@ApiParam(name="data",value="就诊事件json数据",defaultValue = "")
                                 @RequestParam(value="data",required = true) String data)
    {
        try {
            patientEventService.saveEventDetail(data, getUID());
            return write(200, "保存就诊事件成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存就诊事件失败!");
        }
    }
}

+ 0 - 112
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/booking/DoctorBookingController.java

@ -1,112 +0,0 @@
package com.yihu.wlyy.web.doctor.booking;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.patient.PatientReservation;
import com.yihu.wlyy.repository.patient.PatientReservationDao;
import com.yihu.wlyy.service.app.reservation.PatientReservationService;
import com.yihu.wlyy.service.third.guahao.GuahaoXMService;
import com.yihu.wlyy.service.third.guahao.GuahaoYihuService;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 预约挂号
 * Created by yeshijie on 2017/2/4.
 */
@Controller
@RequestMapping(value = "/doctor/guahao")
@Api(description = "预约挂号接口-医生端")
public class DoctorBookingController extends BaseController{
    @Autowired
    private GuahaoXMService guahaoXM;
    @Autowired
    private JwSmjkService jwSmjkService;
    @Autowired
    private GuahaoYihuService guahaoYihu;
    @Autowired
    private PatientReservationService patientReservationService;
    @Autowired
    private PatientReservationDao patientReservationDao;
    @RequestMapping(value = "isCancelOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("医生是否可取消代预约")
    public String cancelOrderDt(@ApiParam(name = "orderId", value = "订单id", defaultValue = "48")
                                @RequestParam(value = "orderId", required = true) Long orderId){
        try{
            PatientReservation obj = patientReservationService.findById(orderId);
            if(obj != null){
                PatientReservation pr = patientReservationDao.findByPatientAndCancelerAndCancelTime(obj.getPatient(),getUID(), DateUtil.getCurMonthFirstDayShort());//"6c0cfe5065e011e69f7c005056850d66"
                if(pr == null){
                    return write(200,"查询成功","status","1");//取消预约次数将计入居民取消次数,居民每月取消超过3次将纳入黑名单。是否继续撤销?
                }else{
                    return write(200,"查询成功","status","0");//对不起,您本月已取消过该居民预约,如需继续撤销,请让居民自行处理
                }
            }else{
                return error(-1, "挂号单不存在!");
            }
        }catch (Exception e){
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "CancelOrder", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("取消挂号单")
    @ObserverRequired
    public String CancelOrder(@ApiParam(name = "orderId", value = "订单id", defaultValue = "48")
                              @RequestParam(value = "orderId", required = true) Long orderId,
                              @ApiParam(name = "code", value = "订单code", defaultValue = "48")
                              @RequestParam(value = "code", required = false) String code,
                              @ApiParam(name = "ssc", value = "社保卡号", defaultValue = "48")
                              @RequestParam(value = "ssc", required = false) String ssc) {
        try {
            //获取订单信息
            PatientReservation obj = patientReservationService.findById(orderId);
            boolean re = false;
            if(obj==null){
                re = jwSmjkService.CancelOrder(code,ssc);
            }else {
                re = jwSmjkService.CancelOrder(obj.getCode(),obj.getSsc());
            }
//            if (obj != null) {
//                String type = obj.getType();
//                String code = obj.getCode();
//                if (type.equals("0")) {  //医护网接口
//                    re = guahaoYihu.CancelOrder(code);
//                } else if (type.equals("1"))   //厦门市民健康预约接口
//                {
//                    re = guahaoXM.CancelOrder(code, obj.getSsc());
//                }
//            }
            if (re) {
                //更新状态
                if(obj!=null){
                    patientReservationService.doctorCancelOrder(orderId,getUID());//"6c0cfe5065e011e69f7c005056850d66"
                }
                return write(200, "取消挂号单成功!");
            } else {
                return error(-1, "取消挂号单失败!");
            }
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
}

+ 0 - 1107
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultController.java

@ -1,1107 +0,0 @@
package com.yihu.wlyy.web.doctor.consult;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroup;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroupMember;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamilyServer;
import com.yihu.wlyy.entity.patient.prescription.Prescription;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.patient.SignFamilyServerDao;
import com.yihu.wlyy.repository.prescription.PrescriptionDao;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.prescription.PrescriptionDiagnosisService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.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 java.util.List;
import java.util.Map;
/**
 * 医生端:三师咨询控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "三师咨询")
public class DoctorConsultController extends WeixinBaseController {
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private PatientInfoService patientService;
    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private PatientHealthGuidanceService patientHealthGuidanceService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private ConsultService consultService;
    @Autowired
    private TalkGroupService talkGroupService;
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private ImUtill ImUtill;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private SignFamilyServerDao signFamilyServerDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private PrescriptionDiagnosisService prescriptionDiagnosisService;
    /**
     * 三师咨询列表查询
     *
     * @param type     咨询类型:0、全部,1、咨询我的,2、公共的, 3、参与过的,4、已结束的  5 名医咨询 全部
     *                 6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医   10查询我咨询的
     * @param id
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(int type,
                       int id,
                       int pagesize,
                       @RequestParam(required = false) String patient,
                       @RequestParam(required = false) String title) {
        try {
            Page<ConsultTeam> list = consultTeamService.findByDoctor(getUID(), type, id, pagesize, patient, title);
            JSONArray jsonArray = new JSONArray();
            if (list != null) {
                for (ConsultTeam consult : list) {
                    if (consult == null) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", consult.getId());
                    // 设置咨询标识
                    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());
                    if (consult.getType() == 7) {
                        Doctor d = doctorInfoService.findDoctorByCode(consult.getPatient());
                        // 设置患者头像
                        json.put("photo", d.getPhoto());
                        // 设置患者年龄
                        json.put("age", IdCardUtil.getAgeForIdcard(d.getIdcard()));
                        // 设置性别
                        json.put("sex", d.getSex());
                    } else {
                        Patient p = patientService.findByCode(consult.getPatient());
                        // 设置患者头像
                        json.put("photo", p.getPhoto());
                        // 设置患者年龄
                        json.put("age", IdCardUtil.getAgeForIdcard(p.getIdcard()));
                        // 设置性别
                        json.put("sex", p.getSex());
                    }
                    // 设置咨询标识
                    json.put("title", consult.getSymptoms());
                    // 设置评价内容
                    json.put("comment", consult.getCommentContent());
                    // 设置评价星级
                    json.put("star", consult.getCommentStar());
                    // 设置咨询类型:1三师咨询,2家庭医生咨询 6名医咨询
                    json.put("type", consult.getType());
                    // 设置咨询时间
                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    // 咨询状态
                    json.put("status", consult.getStatus());
                    // 未读消息
                    json.put("doctorRead", consult.getDoctorRead());
                    // 设置关联指导
                    json.put("guidance", consult.getGuidance());
                    json.put("startId", consult.getStartMsgId());
                    json.put("endId", consult.getEndMsgId());
                    List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
                    if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
                        for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
                            json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
                            json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
                        }
                    }
                    jsonArray.put(json);
                }
            }
            return write(200, "查询成功", "list", list, jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "居民咨询列表查询")
    public String listByTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
                             @RequestParam @ApiParam(value = "团队Code") Long teamCode,
                             @RequestParam @ApiParam(value = "第几页") int page,
                             @RequestParam @ApiParam(value = "页大小") int pagesize) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "请输入需查询的居民的团队");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray jsonArray = consultTeamService.findByPatientAndTeam(patient, teamCode, page, pagesize);
            return write(200, "查询成功", "data", jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取三师家庭咨询
     *
     * @param status   0未处理或未回复 1已回复 2已结束
     * @param id
     * @param pagesize
     * @param patient
     * @return
     */
    @RequestMapping(value = "/list_by_status")
    @ResponseBody
    public String listByStatus(int status, int id, int pagesize,
                               @RequestParam(required = false) String patient) {
        try {
            Page<ConsultTeam> list = consultTeamService.findConsultByDoctor(getUID(), status, id, pagesize);
            JSONArray jsonArray = new JSONArray();
            for (ConsultTeam consult : list) {
                if (consult == null) {
                    continue;
                }
                if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
                    continue;
                }
                Patient p = patientService.findByCode(consult.getPatient());
                JSONObject json = new JSONObject();
                json.put("id", consult.getId());
                // 设置咨询标识
                json.put("consult", consult.getConsult());
                // 设置患者标识
                json.put("patient", consult.getPatient());
                // 设置患者头像
                json.put("photo", p.getPhoto());
                // 设置咨询标识
                json.put("title", consult.getSymptoms());
                // 设置患者姓名
                json.put("name", consult.getName());
                // 设置患者年龄
                json.put("age", IdCardUtil.getAgeForIdcard(p.getIdcard()));
                // 设置评价内容
                json.put("comment", consult.getCommentContent());
                // 设置评价星级
                json.put("star", consult.getCommentStar());
                // 设置咨询类型:1三师咨询,2家庭医生咨询 6名医咨询
                json.put("type", consult.getType());
                // 设置咨询时间
                json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                // 咨询状态
                json.put("status", consult.getStatus());
                json.put("doctor", consult.getDoctor());
                json.put("doctorName", consult.getDoctorName());
                // 设置性别
                json.put("sex", p.getSex());
                // 未读消息
                json.put("doctorRead", consult.getDoctorRead());
                // 设置关联指导
                json.put("guidance", consult.getGuidance());
                json.put("startId", consult.getStartMsgId());
                json.put("endId", consult.getEndMsgId());
                List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
                if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
                    for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
                        json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
                        json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
                    }
                }
                jsonArray.put(json);
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "/hasTnvite")
    @ResponseBody
    public String hasTnvite(String groupCode) {
        try {
            JSONObject jo = new JSONObject();
            List<WlyyTalkGroupMember> wlyyTalkGroupMembers = talkGroupService.findTalkGroupMembers(groupCode);
            if (wlyyTalkGroupMembers.size() > 2) {
                jo.put("hasTnvite", 1);//有邀请
            } else {
                jo.put("hasTnvite", 0);//没邀请
            }
            return write(200, "查询成功", "list", jo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 名医列表
     *
     * @return
     */
    @RequestMapping(value = "famousDoctorList")
    @ResponseBody
    public String famousDoctorList(
            @RequestParam(required = false) String name) {
        try {
            JSONArray array = new JSONArray();
            List<Doctor> list = doctorService.getDoctorFamousDoctorList(name);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    // 过滤掉自己
                    if (doctor.getCode().equals(getUID())) {
                        continue;
                    }
                    // 判断名医是否在工作
                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(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("level", doctor.getLevel());
                    // 所在医院名称
                    json.put("hospital", doctor.getHospital());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHospitalName());
                    // 科室名称
                    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());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 获取咨询全科医生签约量
     *
     * @param consults
     * @return
     */
    @RequestMapping(value = "/consult_sign")
    @ResponseBody
    public String consultSign(String consults) {
        try {
            List<Map<String, Object>> list = consultTeamService.getConsultSign(consults.split(","));
            return write(200, "查询成功", "data", new JSONArray(list));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 结束三师咨询接口
     *
     * @param consult 三师咨询标识
     * @return
     */
    @RequestMapping(value = "finish")
    @ResponseBody
    @ObserverRequired
    public String finish(String consult) {
        try {
            int flag = consultTeamService.finish(consult, getUID(), 2);
            if (flag > 0) {
                return success("咨询已关闭");
            }else if(flag==-2){
                return error(-1, "续方未审核,不能结束续方咨询!");
            }  else {
                return error(-1, "关闭失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "关闭失败!");
        }
    }
    /**
     * 设置消息已读
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/readed")
    @ResponseBody
    @ObserverRequired
    public String readMessage(String consult) {
        try {
            int result = consultTeamService.readMessage(consult);
            return write(200, "设置成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "设置失败");
        }
    }
    /**
     * 医生咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param patient  患者标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    @RequestMapping(value = "record")
    @ResponseBody
    public String record(String consult, String patient, long id, int pagesize) {
        try {
            Patient patientTemp = null;
            if (id <= 0) {
                // 只有第一页才会查询患者信息
                patientTemp = patientService.findByCode(patient);
                // 更新医生未读数量为0
                consultTeamService.clearDoctorRead(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("content", log.getContent());
                    // 设置回复医生姓名
                    json.put("doctorName", log.getDoctorName());
                    // 设置回复人头像
                    json.put("photo", log.getPhoto());
                    // 设置日志类型
                    json.put("type", log.getType());
                    // 设置记录类型
                    json.put("chatType", log.getChatType());
                    // 设置咨询或回复时间
                    json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jsonArray.put(json);
                }
            }
            // 设置返回结果
            JSONObject values = new JSONObject();
            if (patientTemp != null) {
                JSONObject patientJson = new JSONObject();
                // 设置患者标识
                patientJson.put("patient", patientTemp.getCode());
                // 设置姓名
                patientJson.put("name", patientTemp.getName());
                // 设置头像
                patientJson.put("photo", patientTemp.getPhoto());
                values.put("patient", patientJson);
            }
            values.put("list", jsonArray);
            // 返回结果
            return write(200, "查询成功", "data", values);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 医生回复网络咨询
     *
     * @param patient 患者标识
     * @param consult 咨询标识
     * @param content 回复内容
     * @param type    回复类型,1文字,2图片,3语音
     * @return
     */
    @RequestMapping(value = "reply")
    @ResponseBody
    public String reply(String patient, String consult, String content, int type) {
        try {
            // 查询医生基本信息
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "回复失败!");
            } else {
                ConsultTeamLog log = new ConsultTeamLog();
                // 设置咨询标识
                log.setConsult(consult);
                // 拷贝图片
                if (StringUtils.isNotEmpty(content)) {
                    if (type == 3) {
                        // 语音
                        content = CommonUtil.copyTempVoice(content);
                    } else if (type == 2) {
                        // 图片
                        content = CommonUtil.copyTempImage(content);
                    }
                }
                // 设置回复内容
                log.setContent(content);
                log.setDel("1");
                // 设置回复医生标识
                log.setDoctor(doctor.getCode());
                // 设置医生姓名
                log.setDoctorName(doctor.getName());
                // 设置医生头像
                log.setPhoto(doctor.getPhoto());
                // 设置咨询类型为医生回复
                log.setType(1);
                // 设置记录类型
                log.setChatType(type);
                // 保存医生回复内容
                log = consultTeamService.reply(log, patient, getUID(), log.getType());
                if (log == null) {
                    return error(-1, "回复失败!");
                } else {
                    // 推送消息给患者
                    // PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.P_CT_01.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.三师咨询.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.医生回复了您.name(), consult);
                    // 推送消息给微信端
                    ConsultTeam ct = consultTeamService.findByCode(consult);
                    Patient p = patientService.findByCode(patient);
                    if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
                        JSONObject json = new JSONObject();
                        json.put("first", p.getName() + ",您好!\n您的健康咨询有新的回复");
                        json.put("toUser", p.getCode());
                        String symp = ct.getSymptoms();
                        json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...")  : content);
                        String replycontent = content.length() > 50 ? content.substring(0, 50) + "..." : content;
                        if (type == 2) {
                            replycontent = "[图片]";
                        } else if (type == 3) {
                            replycontent = "[语音]";
                        }
                        json.put("consult", consult);
                        json.put("replycontent", replycontent);
                        json.put("doctorName", doctor.getName());
                        json.put("remark", "医生已为您提供问诊方案");
                        // PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
                    }
                    if (type == 2) {
                        return write(200, "回复成功!", "data", content);
                    }
                    return success("回复成功!");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "回复失败!");
        }
    }
    /**
     * 查询医生的总咨询次数和今日咨询次数
     *
     * @param doctorCode
     * @return
     */
    @RequestMapping(value = "getConsultCount")
    @ResponseBody
    public String getAllCount(@RequestParam(required = true) String doctorCode) {
        try {
            JSONObject json = new JSONObject();
            Map<String, Long> counts = consultTeamService.getAllCount(doctorCode);
            json.put("all", counts.get("all"));
            json.put("today", counts.get("today"));
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "回复失败!");
        }
    }
    /**
     * 查询患者的服务数目
     *
     * @return
     */
    @RequestMapping(value = "getPatientServicNum")
    @ResponseBody
    public String getPatientServicNum(String patientCode) {
        try {
            JSONObject json = new JSONObject();
            //统计咨询数目
            Integer allSize1 = consultTeamService.findByDoctorSize(patientCode, getUID());
            //查询健康指导
            Integer allSize2 = patientHealthGuidanceService.findGuidanceByPatient(patientCode, getUID());
            json.put("consult", allSize1);
            json.put("guide", allSize2);
            //json.put("today", counts.get("today"));
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "回复失败!");
        }
    }
    /**
     * 根据医生code和和患者code判断是否有存在进行中的咨询
     *
     * @param patientCode 多个患者 逗号分隔
     * @param doctor
     * @return 只返回存在咨询的患者的code
     */
    @RequestMapping(value = "getConsultByPatientAndDoctor")
    @ResponseBody
    public String getConsultByPatientAndDoctor(String patientCode, String doctor) {
        try {
            JSONArray json = new JSONArray();
            String[] patients = patientCode.split(",");
            for (int i = 0; i < patients.length; i++) {
                ConsultTeam consultTeam = consultTeamService.getConsultByPatientAndDoctor(patients[i], doctor);
                if (consultTeam != null) {
                    json.put(patients[i]);
                }
            }
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "回复失败!");
        }
    }
    /**
     * 名医咨询添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param images     图片URL地址,多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "famousAdd")
    @ResponseBody
    @ObserverRequired
    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.isNotEmpty(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);//设置专科医生
            // 保存到数据库
            JSONObject result = consultTeamService.famousConsult(consult, getUID(), "2",null);
            // 推送消息给医生
            pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
            if (StringUtils.isNotEmpty(images)) {
                String[] arr = images.split(",");
                for (String img : arr) {
                    pushMsgTask.put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
                }
            }
            return write(200,"创建成功!","data",result);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败!");
        }
    }
    /**
     * 查询与某个医生是否存在未结束的咨询
     *
     * @param doctor 医生
     * @return
     */
    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isExistsUnfinishedConsult(@RequestParam(required = false) String patient,
                                            @RequestParam(required = true) String doctor) {
        try {
            JSONObject result = new JSONObject();
            List<ConsultTeam> consults = consultTeamService.getUnfinishedConsult(StringUtils.isEmpty(patient) ? getUID() : patient, 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 consult 咨询code
     * @return
     */
    @RequestMapping(value = "/consultTeam", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String consult(@RequestParam(required = false) String consult) {
        try {
            ConsultTeam consultTeam = consultTeamService.findByCode(consult);
            return write(200, "查询成功", "data", consultTeam);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 三师咨询转接接口
     *
     * @param consult 图咨询标识
     * @param doctor  转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
     * @param type    转接对象类型,1三师团队,2指定医生,3工作组团队
     * @return
     */
    @RequestMapping(value = "transfer")
    @ResponseBody
    @ObserverRequired
    public String transfer(
            String consult,
            String doctor,
            @RequestParam(required = false) int type) {
        try {
            consultTeamService.transfers(getUID(), doctor, consult);
            return success("转接成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "转接失败!");
        }
    }
    /**
     * 根据咨询code获取咨询的log
     *
     * @param consultCode
     * @return
     */
    @RequestMapping(value = "getConsultLog")
    @ResponseBody
    public String getConsultLog(
            String consultCode) {
        try {
            List<ConsultTeamLog> consultTeamLogs = consultTeamService.getConsultLog(consultCode);
            JSONArray ja = new JSONArray();
            for (ConsultTeamLog log : consultTeamLogs) {
                JSONObject json = new JSONObject();
                json.put("id", log.getId());
                // 设置回复内容
                json.put("content", log.getContent());
                // 设置回复医生姓名
                json.put("doctorName", log.getDoctorName());
                // 设置回复人头像
                json.put("photo", log.getPhoto());
                // 设置日志类型
                json.put("type", log.getType());
                // 设置记录类型
                json.put("chatType", log.getChatType());
                // 设置咨询或回复时间
                json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                ja.put(json);
            }
            return write(200, "查询成功", "data", ja);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 医生求助添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param groupCode  从哪个讨论组发起的求助
     * @param images     图片URL地址,多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "forHelpAdd")
    @ResponseBody
    @ObserverRequired
    public String forHelpAdd(
            @RequestParam(required = false) String when,
            String symptoms,
            @RequestParam(required = false) String oldConsultCode,
            @RequestParam(required = false) String groupCode,
            @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医生发起的名医咨询 10医生发起的求助
            consult.setType(10);
            // 设置来源(从哪个讨论组发起的求助)
            consult.setTeam(groupCode);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            if(consultTeamService.isCommonTeam( doctorCode, getUID() ))
                consultTeamService.sendForHelpMsg( consult, getUID(), oldConsultCode );
            else
                consultTeamService.addForHelpTeamConsult( consult, getUID(), oldConsultCode );
            // 推送消息给医生
            /*PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
            if (StringUtils.isNotEmpty(images)) {
                String[] arr = images.split(",");
                for (String img : arr) {
                    PushMsgTask.getInstance().put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
                }
            }*/
            return success("提交成功");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败!");
        }
    }
    @RequestMapping(value = "hasUnfinished")
    @ResponseBody
    public String hasUnfinished(String doctorCode) {
        try {
            String curDoc =  getUID();
            JSONObject json = new JSONObject();
            if(consultTeamService.isCommonTeam(doctorCode, curDoc)){
                json.put("isCommonTeam", 1);
                return write(200, "查询成功", "data", json);
            }
            List<ConsultTeam>  ls = consultTeamService.hasUnfinished(doctorCode, curDoc);
            if(ls!=null && ls.size() > 0){
                ConsultTeam ct =  ls.get(0);
                json.put("consult", ct.getConsult());
                //是否是医生求助医生
                if(ct.getType()==10){
                    //取出原有咨询求助返回原咨询的患者
                    ConsultTeam consultTeam = consultTeamService.findByConsultCode(ct.getTeam());
                    Patient patient = patientService.findByCode(consultTeam.getPatient());
                    json.put("zxGroupCode",consultTeam.getPatient()+"_"+consultTeam.getTeam()+"_"+consultTeam.getType());
                    json.put("from", ct.getPatient());
                    json.put("patient_name", patient.getName());
                }
            }
            return write(200, "查询成功", "data", json);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 该咨询求助过的医生列表
     * @param consult 关联的上一个咨询
     * @return
     */
    @RequestMapping(value = "forHelpDocs")
    @ResponseBody
    public String forHelpDocs(String consult) {
        try {
            List<String> ls = consultTeamService.findByTeam(consult);
            JSONObject json = new JSONObject();
            if(ls!=null){
                for(String o : ls){
                    json.put(o, 1);
                }
            }
            return write(200, "查询成功", "data", json);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "/isConsultFinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isConsultFinished(@RequestParam String consult) {
        try {
            ConsultTeam ct = consultTeamService.findByConsultCode(consult);
            return write(200, "查询咨询状态成功", "data", ct.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询咨询状态失败");
        }
    }
    @RequestMapping(value = "seekHelp")
    @ResponseBody
    @ObserverRequired
    public String seekHelp(
            @RequestParam(required = true) String symptoms,
            @RequestParam(required = false) String oldConsultCode,
            @RequestParam(required = false) String doctorCode,
            @RequestParam(required = false) String images,
            @RequestParam(required = true) Integer isSend){
        try {
                if (StringUtils.isEmpty(images)) {
                    images = fetchWxImages();
                    // 将临时图片拷贝到正式存储路径下
                    if (StringUtils.isNotEmpty(images)) {
                        images = CommonUtil.copyTempImage(images);
                    }
                }
                ConsultTeam consult = new ConsultTeam();
                // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
                consult.setType(10);
                // 设置主要症状
                consult.setSymptoms(symptoms);
                // 设置咨询图片URL
                consult.setImages(images);
                consult.setDoctor(doctorCode);//设置专科医生
                // 保存到数据库
                if(consultTeamService.isCommonTeam(doctorCode, getUID())){
                    consultTeamService.addSeekHelpTeam(consult, getUID(), oldConsultCode,isSend);
                }else{
                    consultTeamService.addSeekHelpOtherTeam(consult, getUID(), oldConsultCode,isSend);
                }
                return success("提交成功");
            } catch (Exception ex) {
                error(ex);
                return invalidUserException(ex, -1, "提交失败!");
            }
    }
    /**
     * 结束咨询接口
     * @param consult 咨询标识
     * @return
     */
    @RequestMapping(value = "finish_consult")
    @ResponseBody
    @ObserverRequired
    public String finishConsult(@RequestParam(required = false) String consult) {
        try {
            int flag = consultTeamService.finishConsult(consult, getUID(), 2);
            //int flag = consultTeamService.finishConsult(consult, "test00000000005", 2);
            if (flag > 0) {
                return success("咨询已关闭");
            } else if(flag == -1) {
                return error(-1, "该咨询已经关闭,不需重复关闭!");
            } else if(flag == -2) {
                return error(-1, "续方未审核,不能结束续方咨询!");
            }  else {
                return error(-1, "关闭失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "关闭失败!");
        }
    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
    @RequestMapping(value = "loglist")
    @ResponseBody
    public String loglist(@RequestParam String consult, @RequestParam int page, @RequestParam int pagesize) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在!");
            }
            JSONObject messageObj = ImUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, getUID());
            return write(200, "查询成功", "list", messageObj);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /*********************************************续方咨询**************************************************************/
    @RequestMapping(value = "prescriptionDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取续方信息")
    public String prescriptionDetail(@RequestParam(required = true) String consult){
        try {
            JSONObject json = new JSONObject();
            Consult consult1 = consultDao.findByCode(consult);
            String prescriptionCode = consult1.getRelationCode();
            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
            json.put("status",prescription.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
            json.put("prescriptionDt",prescriptionDiagnosisService.getPrescriptionDiagnosis(prescriptionCode));//续方疾病类型
            json.put("prescriptionInfo",prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
            //服务类型
            List<SignFamilyServer> list = signFamilyServerDao.findBySignCodeAndType(consult1.getSignCode());
            JSONArray jsonArray = new JSONArray();
            if(list!=null&&list.size()>0){
                for(SignFamilyServer server:list){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("serverType",server.getServerType());
                    jsonObject.put("serverTypeName",server.getServerTypeName());
                    jsonArray.put(jsonObject);
                }
            }
            json.put("signFamilyServer",jsonArray);
            return write(200, "查询成功!", "list", json);
        }catch (Exception e){
            error(e);
            return error(-1, "查询失败!");
        }
    }
}

+ 0 - 280
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultMoviController.java

@ -1,280 +0,0 @@
package com.yihu.wlyy.web.doctor.consult;
import java.sql.Time;
import java.util.Date;
import com.yihu.wlyy.aop.ObserverRequired;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
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.ResponseBody;
import com.yihu.wlyy.entity.consult.ConsultMoVi;
import com.yihu.wlyy.entity.consult.ConsultMoViReferral;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.service.app.consult.ConsultMoviService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
/**
 * 电话视频咨询的Controller.
 * 
 * @author George
 */
@Controller
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "电话咨询")
public class DoctorConsultMoviController extends BaseController {
	@Autowired
	private ConsultMoviService consultMoviService;
	@Autowired
	private DoctorService doctorService;
	/**
	 * 电话视频咨询列表查询
	 * @param type 1、电话预约,2、视频预约,3电话咨询记录,4视频咨询记录
	 * @param pagesize 每页显示数,默认为10
	 * @return
	 */
	@RequestMapping(value = "movi_list")
	@ResponseBody
	public String list(int type, String appoDate, int pagesize) {
		try {
			Page<ConsultMoVi> list = consultMoviService.findByDoctor(getUID(), type, DateUtil.strToDateLong(appoDate), pagesize);
			if (list != null) {
				JSONArray jsonArray = new JSONArray();
				for (ConsultMoVi consult : list) {
					if (consult == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", consult.getId());
					// 设置咨询标识
					json.put("code", consult.getConsult());
					// 设置患者标识
					json.put("patient", consult.getPatient());
					// 设置患者姓名
					json.put("name", consult.getName());
					// 患者性别
					json.put("sex", consult.getSex());
					// 患者年龄
					json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
					// 设置预约备注
					json.put("content", consult.getContent());
					// 设置预约日期
					json.put("appo_date", DateUtil.dateToStrLong(consult.getAppoDate()));
					// 设置预约星期
					json.put("appo_week", consult.getAppoWeek());
					// 设置预约时间段
					json.put("hour_begin", DateUtil.dateToStr(consult.getHourBegin(), DateUtil.HH_MM));
					json.put("hour_end", DateUtil.dateToStr(consult.getHourEnd(), DateUtil.HH_MM));
					// 设置头像
					json.put("photo", consult.getPhoto());
					// 设置状态
					json.put("status", consult.getStatus());
					if (consult.getComment() != null) {
						// 设置评价内容
						json.put("comment", consult.getComment().getContent());
						// 设置星级
						json.put("star", consult.getComment().getStar());
					}
					jsonArray.put(json);
				}
				return write(200, "查询成功", list.isFirst(), list.isLast(), list.getTotalElements(), list.getTotalPages(), "list", jsonArray);
			} else {
				return success("查询成功");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 根据code查询电话和视频详情
	 * @param consult 咨询标识
	 * @return
	 */
	@RequestMapping(value = "movi_info")
	@ResponseBody
	public String info(String code) {
		try {
			ConsultMoVi consult = consultMoviService.findByCode(code);
			if (consult != null) {
				JSONObject json = new JSONObject();
				// 设置咨询标识
				json.put("code", consult.getConsult());
				// 设置患者标识
				json.put("patient", consult.getPatient());
				// 设置患者姓名
				json.put("name", consult.getName());
				// 患者性别
				json.put("sex", consult.getSex());
				// 患者年龄
				json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
				// 设置头像
				json.put("photo", consult.getPhoto());
				// 设置预约日期
				json.put("appo_date", DateUtil.dateToStr(consult.getAppoDate(), DateUtil.YYYY_MM_DD));
				// 设置预约星期
				json.put("appo_week", consult.getAppoWeek());
				// 设置预约时间段
				json.put("hour_begin", DateUtil.dateToStr(consult.getHourBegin(), DateUtil.HH_MM));
				json.put("hour_end", DateUtil.dateToStr(consult.getHourEnd(), DateUtil.HH_MM));
				// 设置预约备注
				json.put("content", consult.getContent());
				// 设置状态
				json.put("status", consult.getStatus());
				return write(200, "查询成功", "data", json);
			} else {
				return success("查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 结束视频咨询
	 * @param consult 咨询标识
	 * @return
	 */
	@RequestMapping(value = "movi_finish")
	@ResponseBody
	@ObserverRequired
	public String finish(String code) {
		try {
			int row = consultMoviService.finish(code);
			if (row > 0) {
				return success("操作成功");
			} else {
				return error(-1, "操作失败!");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "操作失败!");
		}
	}
	/**
	 * 查询三师团队的其他医生
	 * @param consult 患者标识
	 * @return
	 */
//	@RequestMapping(value = "referral_doc")
//	@ResponseBody
//	public String referralDoc(String consult) {
//		try {
//			ConsultMoVi cm = consultMoviService.findByCode(consult);
//			JSONArray array = new JSONArray();
//			// 查询对应的团队成员
//			Iterable<DoctorTeamInfo> iterable = consultMoviService.findMoviTransferByTeam(cm.getTeam(), consult);
//			if (iterable != null) {
//				Iterator<DoctorTeamInfo> it = iterable.iterator();
//				while (it != null && it.hasNext()) {
//					DoctorTeamInfo dti = it.next();
//					if (dti == null) {
//						continue;
//					}
//					JSONObject temp = new JSONObject();
//					temp.put("doctor", dti.getDoctor());
//					temp.put("name", dti.getName());
//					array.put(temp);
//				}
//			}
//			return write(200, "查询成功", "list", array);
//		} catch (Exception e) {
//			error(e);
//			return invalidUserException(e, -1, "查询失败!");
//		}
//	}
	/**
	 * 视频转诊
	 * @param doctor 转接医生标识
	 * @param consult 视频咨询标识
	 * @param scheduling 排班标识
	 * @param appo_date 预约日期
	 * @param appo_week 预约星期
	 * @param hour_begin 预约开始时间
	 * @param hour_end 预约结束时间
	 * @param content 转诊说明
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "referral")
	@ObserverRequired
	public String referral(String doctor, String consult, String scheduling, String appo_date, int appo_week, String hour_begin, String hour_end, String content) {
		try {
			// 查询医生信息
			Doctor d = doctorService.findDoctorByCode(getUID());
			// 查询视频咨询信息
			ConsultMoVi cm = consultMoviService.findByCode(consult);
			// 设置排班标识
			cm.setScheduling(scheduling);
			// 设置预约日期
			cm.setAppoDate(DateUtil.strToDateAppendNowTime(appo_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			// 设置预约星期
			cm.setAppoWeek(appo_week);
			// 设置预约时段
			cm.setHourBegin(Time.valueOf(hour_begin));
			cm.setHourEnd(Time.valueOf(hour_end));
			// 更新老的转诊记录
			ConsultMoViReferral oldCmr = consultMoviService.findReferralByConsult(getUID(), consult);
			// 设置为已转诊
			oldCmr.setFlag(1);
			// 新的转诊记录
			ConsultMoViReferral cmr = new ConsultMoViReferral();
			cmr.setCzrq(new Date());
			cmr.setFlag(0);
			// 设置转出医生标识
			cmr.setFrom(d.getCode());
			// 设置转出医生姓名
			cmr.setFromName(d.getName());
			cmr.setTo(doctor);
			// 设置排班标识
			cmr.setScheduling(scheduling);
			// 设置预约日期
			cmr.setAppoDate(DateUtil.strToDate(appo_date, DateUtil.YYYY_MM_DD));
			// 设置预约星期
			cmr.setAppoWeek(appo_week);
			// 设置预约时段
			cmr.setHourBegin(Time.valueOf(hour_begin));
			cmr.setHourEnd(Time.valueOf(hour_end));
			cmr.setContent(content);
			consultMoviService.transfer(cm, cmr, oldCmr);
			return success("转诊成功!");
		} catch (Exception e) {
			error(e);
			return error(-1, "转诊失败!");
		}
	}
	/**
	 * 添加检查检验接口
	 * @param patient 患者标识
	 * @param items 检查检验项
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "inspect")
	@ObserverRequired
	public String addInspect(String patient, String items) {
		try {
			return success("保存成功!");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败!");
		}
	}
}

+ 0 - 297
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultPublicController.java

@ -1,297 +0,0 @@
package com.yihu.wlyy.web.doctor.consult;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.ConsultPublic;
import com.yihu.wlyy.entity.consult.ConsultPublicReply;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.consult.ConsultPublicService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
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;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
/**
 * 医生端:公共咨询控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/consult/public", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "公共咨询")
public class DoctorConsultPublicController extends BaseController {
	@Autowired
	private ConsultPublicService consultPublicService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private CommonUtil CommonUtil;
	@Autowired
	PatientService patientService;
	@Autowired
	WeiXinAccessTokenUtils weiXinAccessTokenUtils;
	@Autowired
	WeiXinOpenIdUtils weiXinOpenIdUtils;
	@Autowired
	private PushMsgTask pushMsgTask;
	/**
	 * 查询公共咨询记录
	 * @param type 查询类型:0全部,1我的回答
	 * @param pagesize 分页大小
	 * @param disease 疾病类型标识
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam(required = false) String disease, int type, long id, int pagesize) {
		try {
			JSONArray list = new JSONArray();
			Page<ConsultPublic> datas = consultPublicService.findPublicQuestionByDoctor(getUID(), disease, type, id, pagesize);
			if (datas != null) {
				for (ConsultPublic cp : datas) {
					if (cp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", cp.getId());
					// 设置问题标识
					json.put("consult", cp.getConsult());
					// 设置患者姓名
					json.put("name", cp.getName());
					// 设置患者头像
					json.put("photo", cp.getPhoto());
					// 设置问题标题
					json.put("title", cp.getTitle());
					// 设置问题描述
					json.put("content", cp.getContent());
					// 设置发病时间
					json.put("when", cp.getWhen());
					// 设置疾病标识
					json.put("disease", cp.getDisease());
					// 设置疾病名称
					json.put("diseaseName", cp.getDiseaseName());
					// 设置是否包含图片
					json.put("hasImg", StringUtils.isNoneEmpty(cp.getImages()));
					// 设置回复总数
					json.put("amount", cp.getAmount());
					list.put(json);
				}
			}
			return write(200, "查询成功!", "list", list);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 查询咨询详细信息
	 * @param consult
	 * @return
	 */
	@RequestMapping(value = "info")
	@ResponseBody
	public String info(String consult) {
		try {
			JSONObject json = new JSONObject();
			ConsultPublic cp = consultPublicService.findByConsult(consult);
			if (cp != null) {
				// 设置咨询标识
				json.put("consult", cp.getConsult());
				// 设置姓名
				json.put("name", cp.getName());
				// 设置头像
				json.put("photo", cp.getPhoto());
				// 设置问题
				json.put("question", cp.getTitle());
				// 设置问题描述
				json.put("content", cp.getContent());
				// 设置发病时间
				json.put("when", cp.getWhen());
				// 设置回复图片
				json.put("images", cp.getImages());
				// 设置疾病标识
				json.put("disease", cp.getDisease());
				// 设置疾病名称
				json.put("diseaseName", cp.getDiseaseName());
				// 设置回复时间
				json.put("czrq", DateUtil.dateToStrLong(cp.getCzrq()));
			}
			return write(200, "查询成功!", "data", json);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 查询回复列表
	 * @param consult 咨询标识
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "reply_list")
	@ResponseBody
	public String replyList(String consult, long id, int pagesize) {
		try {
			JSONArray list = new JSONArray();
			Page<ConsultPublicReply> datas = consultPublicService.findReplyListByConsult(consult, id, pagesize);
			if (datas != null) {
				for (ConsultPublicReply cpr : datas) {
					if (cpr == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 设置回复标识
					json.put("id", cpr.getId());
					// 设置患者标识
					json.put("patient", cpr.getPatient());
					// 设置医生标识
					json.put("doctor", cpr.getDoctor());
					// 设置回复者姓名
					json.put("name", cpr.getName());
					// 设置回复者性别
					json.put("sex", cpr.getSex());
					// 设置回复者头像
					json.put("photo", cpr.getPhoto());
					// 设置回复内容
					json.put("content", cpr.getContent());
					String[] images = null;
					if (StringUtils.isNotEmpty(cpr.getImages())) {
						images = cpr.getImages().split(",");
					}
					// 设置回复图片
					json.put("images", images);
					// 设置回复时间
					json.put("czrq", DateUtil.dateToStrLong(cpr.getCzrq()));
					list.put(json);
				}
			}
			return write(200, "查询成功!", "list", datas, list);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 回复公共咨询
	 * @param consult 咨询标识
	 * @param content 回复内容
	 * @param images 图片标识,多图以逗号分隔
	 * @param images 图片URL,多图以逗号分隔
	 * @return
	 */
	@RequestMapping(value = "reply")
	@ResponseBody
	@ObserverRequired
	public String reply(String consult, String content, @RequestParam(required = false) String images) {
		try {
			ConsultPublic cp = consultPublicService.findByConsult(consult);
			if (cp == null) {
				return error(-1, "问题不存在或已删除!");
			} else if (!StringUtils.equals(cp.getDel(), "1")) {
				return error(-1, "问题已删除!");
			}
			ConsultPublicReply reply = new ConsultPublicReply();
			// 设置回复的咨询标识
			reply.setConsult(consult);
			// 设置回复内容
			reply.setContent(content);
			// 设置回复时间
			reply.setCzrq(new Date());
			reply.setDel("1");
			// 设置回复医生标识
			reply.setDoctor(getUID());
			Doctor doctor=doctorInfoService.findDoctorByCode(getUID());
			reply.setSex(doctor.getSex());
			// 设置回复图片URL
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			reply.setImages(images);
			if (consultPublicService.addDoctorReply(reply) != null) {
				Patient p = patientService.findByCode(cp.getPatient());
				JSONObject json = new JSONObject();
				json.put("isPublic", 1);
				String first = p.getName() + ",您好!\n您的公共咨询有新的回复";
				json.put("first", first);
				json.put("toUser", p.getCode());
				json.put("represented",p.getCode());//被代理人
				String symp = cp.getContent();
//				json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...")  : content);
				json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...")  : symp);
				String replycontent = content.length() > 50 ? content.substring(0, 50) + "..." : content;
				json.put("consult", consult);
				json.put("replycontent", replycontent);
				json.put("doctorName", doctor.getName());
				json.put("remark", "");
				//判断是否判定openId,有没有发则查找家人发送
				if(StringUtils.isNotBlank(p.getOpenid())){
					// 添加到发送队列
					pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
				}
//				else{
//					JSONObject j  = weiXinOpenIdUtils.getFamilyOpenId(p.getCode());
//					Patient member = (Patient) j.get("member");
//					if(StringUtils.isNotBlank(member.getOpenid())){
//						String first = (String) json.get("first");
//						json.remove("first");
//						json.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),member.getName())+first);
//						pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, member.getOpenid(), member.getName(), json);
//					}
//				}
				//发送代理人
				JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
				if(jsonArray!=null&&jsonArray.length()>0){
					for (int i = 0;i<jsonArray.length();i++){
						JSONObject j  = jsonArray.getJSONObject(i);
						Patient member = (Patient) j.get("member");
						JSONObject data = json;
						data.remove("toUser");
						data.put("toUser",member.getCode());
						data.remove("first");
						data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName())+first);
						pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, member.getOpenid(), p.getName(), data);
					}
				}
				// 推送消息给患者
				//pushMsgTask.put(cp.getPatient(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_PUBLIC_REPLY.P_CP_01.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_PUBLIC_REPLY.公共咨询.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_PUBLIC_REPLY.医生回复了您.name(), consult);
				return success("回复成功!");
			} else {
				return error(-1, "回复失败!");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败!");
		}
	}
}

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

@ -1,146 +0,0 @@
package com.yihu.wlyy.web.doctor.consult;
import com.yihu.wlyy.entity.consult.Evaluate;
import com.yihu.wlyy.entity.consult.EvaluateLabel;
import com.yihu.wlyy.entity.consult.EvaluateScore;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.EvaluateLabelService;
import com.yihu.wlyy.service.app.consult.EvaluateService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by 卓 on 2017/5/10.
 */
@Controller
@RequestMapping(value = "/doctor/consult/evaluate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生评价")
public class DoctorEvaluateController extends BaseController {
    @Autowired
    ConsultTeamService consultTeamService;
    @Autowired
    EvaluateService evaluateService;
    @Autowired
    EvaluateLabelService evaluateLabelService;
    /**
     * 获取评价
     * @param consult 咨询
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(@RequestParam(required = true,value="consult") String consult,@RequestParam(required = false,value="type") Integer type){
        try{
            List<Evaluate> evaluates = null;
            List<EvaluateLabel> evaluateLabels = null;
            List<EvaluateScore> evaluateScores = null;
            if(type==null){
                evaluates  =  evaluateService.getEvaluateByConsult(consult);
                evaluateLabels  =  evaluateLabelService.findByConsult(consult);
                evaluateScores = evaluateService.getEvaluateScoreByConsult(consult);
                JSONArray evaluatesJson = new JSONArray(evaluates);
                JSONArray evaluateLabelsJson = new JSONArray(evaluateLabels);
                JSONArray evaluateScoresJson = new JSONArray(evaluateScores);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("evaluate",evaluatesJson);
                jsonObject.put("label",evaluateLabelsJson);
                jsonObject.put("evaluateScore",evaluateScoresJson);
                return  write(200,"查询成功!","data",jsonObject);
            }else{
                List<Map<String,Object>> rs = evaluateService.getEvaluateByConsultAndType(consult,type);
                return  write(200,"查询成功!","list",rs);
            }
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取去重的标签
     * @return
     */
    @RequestMapping(value = "label")
    @ResponseBody
    public String label(){
        try{
            List<Map<String,Object>> result = evaluateLabelService.findDistinctLabelByLaDoctor(getUID());
            return write(200,"查询成功!","list",result);
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取医生评价列表
     * @param type
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "getDoctorSorceList")
    @ResponseBody
    public String getDoctorSorceList(@RequestParam(required = true)String type,
                                     @RequestParam(required = false)Integer page,
                                     @RequestParam(required = false)Integer size){
        try{
            JSONArray rs =evaluateService.getDoctorSorceList(getUID(),type,page,size);
            //JSONArray rs =evaluateService.getDoctorSorceList("zbqD201703150226",type,page,size);
            return  write(200,"查询成功!","data",rs);
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取医生各个类型评价数
     * @return
     */
    @RequestMapping(value = "getScoreListTitle")
    @ResponseBody
    public String  getScoreListTitle(){
        try{
            JSONArray rs =evaluateService.getScoreListTitle(getUID());
            //JSONArray rs =evaluateService.getScoreListTitle("zbqD201703150226");
            return  write(200,"查询成功!","data",rs);
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
    /**
     * 获取医生各个评分头部信息
     * @return
     */
    @RequestMapping(value = "getScoreTitle")
    @ResponseBody
    public String getScoreTitle(){
        try{
            JSONArray rs =evaluateService.getScoreTitle(getUID());
            //JSONArray rs =evaluateService.getScoreTitle("zbqD201703150226");
            return  write(200,"查询成功!","data",rs);
        }catch (Exception e){
            error(e);
            return write(-1,e.getMessage());
        }
    }
}

+ 0 - 224
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java

@ -1,224 +0,0 @@
package com.yihu.wlyy.web.doctor.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeamMember;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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.List;
import java.util.Map;
/**
 * 患者端:设备管理控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "doctor/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "患者设备管理--医生端", description = "患者设备管理--医生端")
public class DoctorDeviceController extends BaseController {
	@Autowired
	private PatientDeviceService patientDeviceService;
	@Autowired
	private AdminTeamService adminTeamService;
	private ObjectMapper  objectMapper=new ObjectMapper();
	@ApiOperation("设备保存接口--医生端")
	@RequestMapping(value = "SavePatientDevice",method = RequestMethod.POST)
	@ResponseBody
	@ObserverRequired
	public String saveDevice(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-8344-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
							  @RequestParam(value="data",required = true) String data) {
		try {
			PatientDevice device = objectMapper.readValue(data,PatientDevice.class);
			// 设置操作医生标识
			device.setDoctor(getUID());
			patientDeviceService.saveDevice(device);
			return success("设备保存成功!");
		}
		catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("患者设备列表获取--医生端")
	@RequestMapping(value = "PatientDeviceList",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceByPatient(
			@ApiParam(name="patient",value="患者code",defaultValue = "5f84f2f0f32c45e0977e3a1ea9f2d77c")
			@RequestParam(value="patient",required = true) String patient,
			@ApiParam(name="page",value="分页起始id",defaultValue = "1")
			@RequestParam(value="page",required = true) int page,
			@ApiParam(name="pagesize",value="每页条数",defaultValue = "10")
			@RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<Map<String,Object>> list = patientDeviceService.findByDoctor(patient, getUID(),page, pagesize);
			return write(200, "查询成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--医生端")
	@RequestMapping(value = "DeletePatientDevice")
	@ResponseBody
	@ObserverRequired
	public String delete(@ApiParam(name="id",value="删除设备关联ID")
						 @RequestParam(value="id",required = true) String id) {
		try {
			PatientDevice pd = patientDeviceService.findById(id);
			if(pd!=null)
			{
				if(StringUtils.isNotBlank(pd.getDoctor())&&StringUtils.equals(pd.getDoctor(), getUID())){
					List<JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
					return write(200,"","data",objects);
				}
				else if(StringUtils.isNotBlank(pd.getDoctor())&&!StringUtils.equals(pd.getDoctor(), getUID())){
					List<AdminTeam> adminTeamMembers = adminTeamService.findDoctorsTeams(pd.getDoctor(),getUID());
					boolean bo = false;
					if(adminTeamMembers!=null && adminTeamMembers.size()>0)
					{
						bo = true;
					}
					if(bo){//同行政团队
						List<JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
						return write(200,"","data",objects);
					}else{
						return error(-1, "只允许删除自己及自己行政团队绑定的设备!");
					}
				} else{
					return error(-1, "只允许删除自己及自己行政团队绑定的设备!");
				}
			}
			else{
				return error(-1, "不存在该设备!");
			}
		} catch (Exception ex) {
			return invalidUserException(ex, -1,ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--管理端")
	@RequestMapping(value = "unbindDevice")
	@ResponseBody
	@ObserverRequired
	public String deleteByAdmin(@ApiParam(name="deviceSn",value="设备SN")
						 @RequestParam(value="deviceSn",required = true) String deviceSn,
						@ApiParam(name="type",value="设备类型")
						@RequestParam(value="type",required = true) String type) {
		try{
			patientDeviceService.deleteDevices(deviceSn,type,getUID());
			return write(200,"解绑成功!");
		}catch (Exception e){
			return write(-1,e.getMessage());
		}
	}
	@ApiOperation("获取患者设备信息")
	@RequestMapping(value = "PatientDeviceInfo",method = RequestMethod.GET)
	@ResponseBody
	public String getPatientDeviceInfo(@ApiParam(name="id",value="患者设备ID",defaultValue = "34")
									   @RequestParam(value="id",required = true) String id) {
		try {
			PatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 * 批量注册接口(2.17号正式发布初始化一次没问题后可以删除)
	 * @return
     */
	@ApiOperation("批量注册接口")
	@RequestMapping(value = "registerSnInit",method = RequestMethod.GET)
	@ResponseBody
	@ObserverRequired
	public String registerSnInit(){
		try{
			String re = patientDeviceService.registerSnInit();
			if("".equals(re)){
				return  write(200,"批量注册成功");
			}
			return error(-1, re);
		}catch (Exception e){
			return error(-1,e.getMessage());
		}
	}
	@ApiOperation("单个注册接口")
	@RequestMapping(value = "registerSn",method = RequestMethod.GET)
	@ResponseBody
	@ObserverRequired
	public String registerSn(@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
							@RequestParam(value="deviceSn",required = true) String deviceSn){
		try{
			String re = patientDeviceService.registerSn(deviceSn);
			return write(200,re);
		}catch (Exception e){
			return error(-1,e.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况")
	@RequestMapping(value = "PatientDeviceIdcard",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceUser(
			@ApiParam(name="patient",value="患者code",defaultValue = "915cca0a-5b1d-11e6-8344-fa163e8aee56")
			@RequestParam(value="patient",required = true) String patient,
			@ApiParam(name="type",value="设备类型",defaultValue = "1")
			@RequestParam(value="type",required = true) String type,
			@ApiParam(name="device_sn",value="设备SN码",defaultValue = "15L000002")
			@RequestParam(value="device_sn",required = true) String deviceSn) {
		try {
			List<Map<String,String>> list = patientDeviceService.getDeviceUser(patient,deviceSn,type);
			return write(200, "获取设备绑定信息成功!", "data",list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况(管理端)")
	@RequestMapping(value = "getListByDeviceSn",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceBindUser(@ApiParam(name="type",value="设备类型",defaultValue = "1")
									@RequestParam(value="type",required = true) String type,
									@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
									@RequestParam(value="deviceSn",required = true) String deviceSn){
			JSONArray objects = patientDeviceService.getDeviceByDeviceSn(deviceSn,type);
			return write(200, "获取设备成功!", "data",objects);
	}
}

+ 0 - 860
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/discussion/DoctorDiscussionGroupController.java

@ -1,860 +0,0 @@
package com.yihu.wlyy.web.doctor.discussion;
import java.util.*;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroup;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroupMember;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.DateUtil;
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;
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.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.BaseController;
@Controller
@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;
    @Autowired
    private ConsultTeamService consultTeamService;
    /**
     * 医生创建讨论组
     *
     * @param name           讨论组名称
     * @param type           讨论组类型 1咨询 2求组
     * @param talkDoctor     讨论组医生
     * @param talkDoctorName 讨论组医生名称
     * @param doctorType     成员医生类型
     * @param patient        病人标识
     * @param patientName    病人姓名
     * @param patientInclude 病人是否加入讨论组 不传默认不加入患者
     * @return
     */
    @RequestMapping(value = "/create", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @ObserverRequired
    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 consult,
            @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.getHospitalName());
                if (StringUtils.isNotEmpty(consult)) {
                    if (type == 1) {
                        JSONObject consultTalkQk = talkGroupService.findConsultTalkGroup(consult);
                        if (consultTalkQk != null) {
                            return error(-1, "该咨询已求助过全科医生");
                        }
                    } else if (type == 2) {
                        JSONObject consultTalkQz = talkGroupService.getConsultGroup(consult);
                        if (consultTalkQz != null) {
                            return error(-1, "该咨询已有求助讨论组");
                        }
                    }
                    talkGroup.setConsultCode(consult);
                }
                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);
                if (type == 1) {
                    consultTeamService.transfer(getUID(), talkDoctor, consult);
                }
                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 consult        咨询code
     * @param patient        患者
     * @param patientName    患者姓名
     * @param patientInclude 患者是否加入
     * @return
     */
    @RequestMapping(value = "/create/members", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @ObserverRequired
    public String createTalkGroupMany(@RequestParam(required = true) String name,
                                      @RequestParam(required = true) int type,
                                      @RequestParam(required = true) String members,
                                      @RequestParam(required = false) String consult,
                                      @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.getHospitalName());
                if (StringUtils.isNotEmpty(consult)) {
                    if (type == 1) {
                        JSONObject consultTalkQk = talkGroupService.findConsultTalkGroup(consult);
                        if (consultTalkQk != null) {
                            return error(-1, "该咨询已求助过全科医生");
                        }
                    } else if (type == 2) {
                        JSONObject consultTalkQz = talkGroupService.getConsultGroup(consult);
                        if (consultTalkQz != null) {
                            return error(-1, "该咨询已有求助讨论组");
                        }
                    }
                    talkGroup.setConsultCode(consult);
                }
                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);
                        if (type == 1 && object.getInt("doctorType") == 2) {
                            if (type == 1) {
                                consultTeamService.transfer(getUID(), object.getString("doctor"), consult);
                            }
                        }
                    }
                }
                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) {
            return error(-1, "创建讨论组失败");
        }
    }
    /**
     * 获取查询对应的求助
     *
     * @param cosnult
     * @return
     */
    @RequestMapping(value = "/group/consult", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getConsultTalkGroup(@RequestParam(required = true) String cosnult) {
        try {
            JSONObject group = talkGroupService.getConsultGroup(cosnult);
            return write(200, "查询成功", "data", group);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取查询对应的求助
     *
     * @param cosnult
     * @return
     */
    @RequestMapping(value = "/group/patient_consult", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getPatientConsultTalkGroup(@RequestParam(required = true) String cosnult) {
        try {
            JSONObject group = talkGroupService.findConsultTalkGroup(cosnult);
            return write(200, "查询成功", "data", group);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取常用医生
     *
     * @return
     */
    @RequestMapping(value = "/common_doctors", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getCommonDoctors() {
        try {
            JSONArray result = talkGroupService.getCommonDoctors(getUID());
            return write(200, "查询成功", "data", result);
        } 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
    @ObserverRequired
    public String addTalkMember(
            @RequestParam(required = true) String groupCode,
            @RequestParam(required = false) String groupName,
            @RequestParam(required = true) String doctor,
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false, defaultValue = "0") int doctorType) {
        try {
            WlyyTalkGroup group = talkGroupService.findTalkGroup(groupCode);
            if (group == null) {
                return error(-1, "讨论组不存在");
            }
            if (talkGroupService.isMemberExists(groupCode, groupName)) {
                return error(-2, "成员已在该讨论组");
            }
            WlyyTalkGroupMember member = new WlyyTalkGroupMember();
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc == null) {
                return error(-1, "添加的医生的信息查询失败");
            }
            member.setGroupCode(groupCode);
            member.setGroupName(group.getName());
            member.setMemberCode(doctor);
            member.setMemberName(doc.getName());
            member.setStatus(1);
            member.setCzrq(new Date());
            member.setType(doc.getLevel());
            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
    @ObserverRequired
    public String addMembers(@RequestParam(required = true) String groupCode,
                             @RequestParam(required = false) String groupName,
                             @RequestParam(required = true) 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) {
            return error(-1, "添加成员失败!");
        }
    }
    /**
     * 移除讨论组成员
     *
     * @param groupCode  讨论组标识
     * @param memberCode 讨论组成员标识
     * @return
     */
    @RequestMapping(value = "removemember", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @ObserverRequired
    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
    @ObserverRequired
    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, "查询失败");
        }
    }
    /**
     * 根据讨论组查找咨询code
     *
     * @param groupCode
     * @return
     */
    @RequestMapping(value = "/getConsultByGroupCode", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getConsultByGroupCode(@RequestParam(required = false) String groupCode, @RequestParam(required = false) String consultCode) {
        try {
            ConsultTeam consult = null;
            if (!org.springframework.util.StringUtils.isEmpty(groupCode)) {
                consult = talkGroupService.findConsultByGroup(groupCode);
            }
            if (!org.springframework.util.StringUtils.isEmpty(consultCode)) {
                consult = consultTeamService.findByConsultCode(consultCode);
            }
            if (org.springframework.util.StringUtils.isEmpty(consultCode) && org.springframework.util.StringUtils.isEmpty(groupCode)) {
                return error(-1, "查询失败");
            }
            JSONObject json = new JSONObject();
            json.put("id", consult.getId());
            // 设置咨询标识
            json.put("consult", consult.getConsult());
            // 设置患者标识
            json.put("patient", consult.getPatient());
            // 设置患者头像
            json.put("photo", consult.getPhoto());
            // 设置咨询标识
            json.put("title", consult.getSymptoms());
            // 设置患者姓名
            json.put("name", consult.getName());
            // 设置患者年龄
            json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
            // 设置评价内容
            json.put("comment", consult.getCommentContent());
            // 设置评价星级
            json.put("star", consult.getCommentStar());
            // 设置咨询类型:1三师咨询,2家庭医生咨询 6名医咨询
            json.put("type", consult.getType());
            // 设置咨询时间
            json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
            // 咨询状态
            json.put("status", consult.getStatus());
            // 设置性别
            json.put("sex", consult.getSex());
            // 未读消息
            json.put("doctorRead", consult.getDoctorRead());
            // 设置关联指导
            json.put("guidance", consult.getGuidance());
            json.put("startId", consult.getStartMsgId());
            json.put("endId", consult.getEndMsgId());
            List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
            if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
                for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
                    json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
                    json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
                    json.put("groupCreator" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCreator());
                    json.put("groupCreatorName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCreatorName());
                    json.put("groupType" + wlyyTalkGroup.getType(), wlyyTalkGroup.getType());
                }
            }
            return write(200, "查询成功", "data", json);
        } 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", 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, "查询失败!");
        }
    }
}

+ 0 - 88
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/family/DoctorFamilyController.java

@ -1,88 +0,0 @@
package com.yihu.wlyy.web.doctor.family;
import com.yihu.wlyy.service.app.family.FamilyMemberService;
import com.yihu.wlyy.service.app.family.FamilyService;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Administrator on 2016.08.20.
 */
@Controller
@RequestMapping(value = "/doctor/family", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-家庭查询")
public class DoctorFamilyController extends WeixinBaseController {
    @Autowired
    private FamilyService familyService;
    @Autowired
    FamilyMemberService familyMemberService;
    //通過患者身份證查找患者家庭成员
    @RequestMapping(value = "/getfamilyMember")
    @ResponseBody
    public String getfamilyMember(
            String patientCode,//患者code
            String doctorCode,//医生code
            String idcard//患者身份证号
    ) {
        try {
            Map<String, JSONObject> result = new HashMap<>();
            JSONArray patients = familyService.getfamilyMember(patientCode, idcard, doctorCode);
            JSONArray patientsCustom = familyMemberService.getPatientFamilyMembers(patientCode, doctorCode,null);
            if (patients != null) {
                for(int i = 0;i < patients.length(); i++){
                    if(patients.getJSONObject(i).get("idcard") != null) {
                        result.put(patients.getJSONObject(i).getString("idcard"), patients.getJSONObject(i));
                    }
                }
            }
            if (patientsCustom != null) {
                for(int i = 0;i < patientsCustom.length(); i++){
                    if(patientsCustom.getJSONObject(i).get("idcard") != null) {
                        result.put(patientsCustom.getJSONObject(i).getString("idcard"), patientsCustom.getJSONObject(i));
                    }
                }
            }
            return write(200, "查询成功", "list", result.size() > 0 ? new JSONArray(result.values()) : new JSONArray());
        } catch (Exception e) {
            return error(-1, "查询失败!");
        }
    }
    //邀请家庭成员签约
    @RequestMapping(value = "/inviteFamilyMember")
    @ResponseBody
    public String inviteFamilyMember(
            String patient,//邀请的患者code
            String currentPatient,//患者code
            String doctor,//医生code
            String relation//关系
    ) {
        try {
            String returnCode = familyService.inviteFamilyMember(patient, currentPatient, doctor, relation);
            if ("-1".equals(returnCode)) {
                return write(-1, "邀请失败,患者已经签约");
            } else if ("-2".equals(returnCode)) {
                return write(-2, "邀请失败,医生已经邀请过该患者");
            } else if ("-3".equals(returnCode)) {
                return write(-3, "邀请失败,与患者签约的三师医生不一致");
            }
            return write(200, "查询成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "邀请失败!");
        }
    }
}

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

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

+ 0 - 370
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/followup/DoctorFollowUpController.java

@ -1,370 +0,0 @@
package com.yihu.wlyy.web.doctor.followup;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.followup.Followup;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.service.app.followup.FollowUpService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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.List;
import java.util.Map;
/**
 * 医生端:随访接口
 *
 * @author hzp add 2016-12-07
 */
@Controller
@RequestMapping(value = "/doctor/followup", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-随访接口")
public class DoctorFollowUpController extends BaseController {
    @Autowired
    private FollowUpService followUpService;
    /*************************************** 随访计划 ****************************************************************************/
    @ApiOperation("获取随访列表")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                          @RequestParam(value = "startTime", required = true) String startTime,
                          @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                          @RequestParam(value = "endTime", required = true) String endTime) {
        try {
            List<Map<String, Object>> result = followUpService.getListByDoctor(getUID(), startTime, endTime);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/list_by_team")
    @ResponseBody
    @ApiOperation(value = "查询居民随访列表")
    public String getListByPatientAndTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
                                          @RequestParam @ApiParam(value = "团队code") Long teamCode,
                                          @RequestParam @ApiParam(value = "第几页") int page,
                                          @RequestParam @ApiParam(value = "页大小") int pagesize) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "请输入需查询的居民的团队");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = followUpService.getListByPatientAndTeam(patient, teamCode, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation("获取随访列表(创建者)")
    @RequestMapping(value = "/createrList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    @ObserverRequired
    public String getCreaterList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                                 @RequestParam(value = "startTime", required = true) String startTime,
                                 @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                                 @RequestParam(value = "endTime", required = true) String endTime,
                                 @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                 @RequestParam(value = "page", required = true) String page,
                                 @ApiParam(name = "pageSize", value = "每页几行", defaultValue = "10")
                                 @RequestParam(value = "pageSize", required = true) String pageSize) {
        try {
            List<Map<String, String>> result = followUpService.getListByCreater(getUID(), startTime, endTime, page, pageSize);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增随访计划(批量)")
    @RequestMapping(value = "/addFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String addFollowupPlan(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "data", value = "随访计划列表json", defaultValue = "[{\"date\":\"2016-12-16 20:00:00\",\"type\":\"10\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"},{\"date\":\"2016-12-17 15:00:00\",\"type\":\"3\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"}]")
                                  @RequestParam(value = "data", required = true) String data) {
        try {
            Iterable<Followup> followups = followUpService.addFollowupPlan(getUID(), patient, data);
            if (followups != null) {
                for (Followup followup : followups) {
                    BusinessLogs.info(BusinessLogs.BusinessType.followup, getUID(), followup.getPatientCode(), new JSONObject(followup));
                }
            }
            return write(200, "新增随访计划成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("编辑随访计划")
    @RequestMapping(value = "/editFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String editFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id,
                                   @ApiParam(name = "planDate", value = "随访计划时间", defaultValue = "2016-12-14 20:00:00")
                                   @RequestParam(value = "planDate", required = true) String planDate,
                                   @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                   @RequestParam(value = "followupType", required = true) String followupType) {
        try {
            followUpService.editFollowupPlan(getUID(), id, planDate, followupType);
            return write(200, "编辑随访计划成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "编辑随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("开始随访记录")
    @RequestMapping(value = "/startFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String startFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                @RequestParam(value = "id", required = true) String id,
                                @ApiParam(name = "date", value = "随访时间", defaultValue = "2016-12-14 20:00:00")
                                @RequestParam(value = "date", required = true) String date,
                                @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                @RequestParam(value = "followupType", required = true) String followupType,
                                @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病】", defaultValue = "1")
                                @RequestParam(value = "followupClass", required = true) String followupClass,
                                @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                                @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus) {
        try {
            followUpService.startFollowup(id, date, followupType, followupClass, followupManagerStatus);
            return write(200, "开始随访记录成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "开始随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增临时随访记录(返回ID)")
    @RequestMapping(value = "/addFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String addFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                              @RequestParam(value = "patient", required = true) String patient,
                              @ApiParam(name = "date", value = "下次随访时间", defaultValue = "2016-12-15 20:00:00")
                              @RequestParam(value = "date", required = true) String date,
                              @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                              @RequestParam(value = "followupType", required = true) String followupType,
                              @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病】", defaultValue = "1")
                              @RequestParam(value = "followupClass", required = true) String followupClass,
                              @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                              @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus) {
        try {
            String response = followUpService.addFollowup(getUID(), patient, date, followupType, followupClass, followupManagerStatus);
            return write(200, "新增临时随访记录成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增临时随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("取消随访计划")
    @RequestMapping(value = "/cancelFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String cancelFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.cancelFollowupPlan(id);
            return write(200, "取消随访计划成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "取消随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("完成随访记录")
    @RequestMapping(value = "/finishFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String finishFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                 @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.finishFollowup(id);
            return write(200, "完成随访记录成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "完成随访记录失败!" + e.getMessage());
        }
    }
    /*********************************** 随访详情 *******************************************************************/
    @ApiOperation("获取随访信息")
    @RequestMapping(value = "/getFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                              @RequestParam(value = "id", required = true) String id) {
        try {
            Map<String, String> response = followUpService.getFollowup(id);
            return write(200, "获取随访信息成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访信息失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目列表")
    @RequestMapping(value = "/getFollowupProject", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getFollowupProject(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            List<Map<String, String>> list = followUpService.getFollowupProject(id);
            return write(200, "获取随访项目列表成功!", "data", list);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访项目列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目数据")
    @RequestMapping(value = "/getFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                         @RequestParam(value = "id", required = true) String id,
                                         @ApiParam(name = "followupProject", value = "随访项目", defaultValue = "2")
                                         @RequestParam(value = "followupProject", required = true) String followupProject) {
        try {
            Map<String, String> response = followUpService.getFollowupProjectData(id, followupProject);
            return write(200, "获取随访项目数据成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访项目数据失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存随访项目数据")
    @RequestMapping(value = "/saveFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String saveFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                          @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "followupProject", value = "随访项目", defaultValue = "2")
                                          @RequestParam(value = "followupProject", required = true) String followupProject,
                                          @ApiParam(name = "followupProjectData", value = "随访项目数据", defaultValue = "{\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}")
                                          @RequestParam(value = "followupProjectData", required = true) String followupProjectData) {
        try {
            followUpService.saveFollowupProjectData(id, followupProject, followupProjectData);
            return write(200, "保存随访项目数据成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存随访项目数据失败!" + e.getMessage());
        }
    }
    /*********************************** 电话随访 *****************************************************************/
    @ApiOperation("获取电话随访内容")
    @RequestMapping(value = "/getFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id) {
        try {
            String response = followUpService.getFollowupPhone(id);
            return write(200, "获取电话随访内容成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取电话随访内容失败!" + e.getMessage());
        }
    }
    @ApiOperation("记录电话随访内容")
    @RequestMapping(value = "/saveFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public String saveFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                    @RequestParam(value = "id", required = true) String id,
                                    @ApiParam(name = "content", value = "电话随访内容", defaultValue = "")
                                    @RequestParam(value = "content", required = true) String content) {
        try {
            followUpService.saveFollowupPhone(id, content);
            return write(200, "记录电话随访内容成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "记录电话随访内容失败!" + e.getMessage());
        }
    }
    /*************************************** 上次随访 ********************************************/
    @ApiOperation("获取上次随访")
    @RequestMapping(value = "/getLastFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getLastFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20161008001")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "followClass", value = "随访类别", defaultValue = "1")
                                  @RequestParam(value = "followClass", required = true) String followClass) {
        try {
            Map<String, String> response = followUpService.getLastFollowup(getUID(), patient, followClass);
            return write(200, "获取上次随访成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取上次随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("复制上次随访数据")
    @RequestMapping(value = "/copyFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public String copyFollowup(@ApiParam(name = "id", value = "本地随访ID", defaultValue = "")
                               @RequestParam(value = "id", required = true) Long id,
                               @ApiParam(name = "fromId", value = "拷贝随访记录ID", defaultValue = "")
                               @RequestParam(value = "fromId", required = true) Long fromId) {
        try {
            followUpService.copyFollowup(id, fromId);
            return write(200, "复制上次随访成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "复制上次随访失败!" + e.getMessage());
        }
    }
    /*************************************** 发送随访计划消息 ********************************************/
    @ApiOperation("发送随访计划消息")
    @RequestMapping(value = "/sendMessage", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String sendMessage(@ApiParam(name = "date", value = "日期", defaultValue = "2017-01-05")
                              @RequestParam(value = "date", required = true) String date) {
        try {
            followUpService.sendMessage(date);
            return write(200, "发送随访计划消息成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "发送随访计划消息失败!" + e.getMessage());
        }
    }
}

+ 0 - 89
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/followup/DoctorFollowupDrugsController.java

@ -1,89 +0,0 @@
package com.yihu.wlyy.web.doctor.followup;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.dict.DmDrugsGroupItem;
import com.yihu.wlyy.entity.followup.Followup;
import com.yihu.wlyy.entity.followup.FollowupDrugs;
import com.yihu.wlyy.service.app.followup.FollowUpService;
import com.yihu.wlyy.service.app.followup.FollowupDrugsService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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.List;
import java.util.Map;
/**
 * 医生端:随访接口
 * 
 * @author hzp add 2016-12-07
 *
 */
@Controller
@RequestMapping(value = "/doctor/followup/drugs", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-随访用药接口")
public class DoctorFollowupDrugsController extends BaseController {
	@Autowired
	private FollowupDrugsService followupDrugsService;
	@ApiOperation("获取面访用药数据")
	@RequestMapping(value = "/getFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String getFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
									@RequestParam(value="id",required = true) String id)
	{
		try {
			Map<String,Object> response = followupDrugsService.getFollowupDrugs(id);
			return write(200, "获取面访用药数据成功!","data",response);
		} catch (Exception e) {
			return invalidUserException(e, -1, "获取面访用药数据失败!"+e.getMessage());
		}
	}
	@ApiOperation("保存面访用药数据")
	@RequestMapping(value = "/saveFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	@ObserverRequired
	public String saveFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
										  @RequestParam(value="id",required = true) String id,
									      @ApiParam(name="drugsData",value="面访用药数据",defaultValue = "[]")
										  @RequestParam(value="drugsData",required = true) String drugsData)
	{
		try {
			followupDrugsService.saveFollowupDrugs(id,drugsData);
			return write(200, "保存面访用药数据成功!");
		} catch (Exception e) {
			return invalidUserException(e, -1, "保存面访用药数据失败!"+e.getMessage());
		}
	}
	@ApiOperation("获取随访类别用药列表")
	@RequestMapping(value = "/getFollowupClassDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String getFollowupClassDrugs(@ApiParam(name="followupClass",value="随访类别:1.高血压 2.糖尿病",defaultValue = "")
									@RequestParam(value="followupClass",required = true) String followupClass)
	{
		try {
			List<DmDrugsGroupItem> list = followupDrugsService.getFollowupClassDrugs(followupClass);
			return write(200, "获取随访类别用药列表成功!","data",list);
		} catch (Exception e) {
			return invalidUserException(e, -1, "获取随访类别用药列表失败!"+e.getMessage());
		}
	}
}

+ 0 - 295
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java

@ -1,295 +0,0 @@
package com.yihu.wlyy.web.doctor.health;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.patient.PatientHealthStandard;
import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.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.*;
@Controller
@RequestMapping(value = "/doctor/health_index", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-患者指标")
public class DoctorHealthController extends BaseController {
	@Autowired
	private PatientHealthIndexService healthIndexService;
	@RequestMapping(value = "recent",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("患者最近填写的健康指标")
	public String recent(@ApiParam("患者代码")
						  @RequestParam String patient) {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(patient);
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标(图表)")
	public String getHealthIndexChartByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "eb0b478fbe9245428ecf63cd7517206f")
												   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
												   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2017-05-22 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2017-06-02 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
//			JSONArray jsonArray = new JSONArray();
//			for (DevicePatientHealthIndex model : list) {
//				JSONObject modelJson = new JSONObject();
//				modelJson.put("patient", model.getUser());
//				modelJson.put("value1", model.getValue1());
//				modelJson.put("value2", model.getValue2());
//				modelJson.put("value3", model.getValue3());
//				modelJson.put("value4", model.getValue4());
//				modelJson.put("value5", model.getValue5());
//				modelJson.put("value6", model.getValue6());
//				modelJson.put("value7", model.getValue7());
//				modelJson.put("type", model.getType());
//				modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
//				modelJson.put("sortDate", DateUtil.dateToStrLong(model.getSortDate()));
//				modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//				jsonArray.put(modelJson);
//			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
											  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
											  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
											  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
											  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONArray jsonArray = new JSONArray();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonArray = new JSONArray(list);
			}else{
				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 *
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "standard",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("患者健康指标预警值查询")
	public String standard(@ApiParam("患者代码") @RequestParam String patient) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(patient);
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3体重,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	@RequestMapping(value = "standard_save",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("保存患者健康指标预警值")
	@ObserverRequired
	public String standardSave(@ApiParam("患者代码") @RequestParam String patient,
							    @ApiParam("预警值Json") @RequestParam String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(patient) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
			// 生成数据对象
			List<PatientHealthStandard> list = new ArrayList<PatientHealthStandard>();
			for (int i = 0; i < array.length(); i++) {
				JSONObject obj = array.getJSONObject(i);
				if (obj == null) {
					continue;
				}
				PatientHealthStandard standard = new PatientHealthStandard();
				standard.setDoctor(getUID());
				standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
				standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
				standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
				standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
				standard.setType(obj.getInt("type"));
				standard.setPatient(patient);
				standard.setCzrq(new Date());
				list.add(standard);
			}
			if (list.size() == 0) {
				return error(-1, "保存失败!");
			}
			// 保存数据库
			Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandard(list, patient);
			if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
				return error(-1, "保存失败!");
			}
			return write(200, "保存成功");
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "保存失败!");
		}
	}
	@RequestMapping(value = "last",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("患者最新健康指标信息")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										   @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)
			{
				map.put("xy",xy);
			}
			DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient,3);
			if(tz != null){
				map.put("tz",tz);
			}
			DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient,4);
			if(sg != null){
				map.put("sg",sg);
			}
			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "getHealthIndexHistory",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("获取患者健康指标历史记录")
	public String getHealthIndexHistory(@ApiParam(name="patient",value="患者代码",defaultValue = "P20161008001")
										 @RequestParam(value="patient",required = true) String patient,
										 @ApiParam(name="type",value="指标类型1血糖,2血压,3体重,4腰围",defaultValue = "1")
										 @RequestParam(value="type",required = true) int type,
										 @ApiParam(name="page",value="第几页",defaultValue = "0")
										 @RequestParam(value="page",required = true) int page,
										 @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										 @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<Map<String,String>> list = healthIndexService.getHealthIndexHistory(patient, type, page, pagesize);
			return write(200, "获取患者健康指标历史记录成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
}

+ 0 - 610
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java

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

+ 0 - 305
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthGuidanceController.java

@ -1,305 +0,0 @@
package com.yihu.wlyy.web.doctor.health;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.template.DoctorGuidanceTempService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 医生端:健康指导控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/health/guidance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "健康指导")
public class DoctorHealthGuidanceController extends WeixinBaseController {
	@Autowired
	private PatientHealthGuidanceService patientHealthGuidanceService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private PatientService patientService;
	@Autowired
	private ConsultService consultService;
	@Autowired
	private CommonUtil CommonUtil;
//======================
	@Autowired
	DoctorGuidanceTempService doctorGuidanceTempService;
//	=======================
	/**
	 * 获取某个健康指导
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/id")
	@ResponseBody
	public String getHealthGuidance(@RequestParam String id){
		Long idl = Long.parseLong(id);
		try{
			if(idl == null || idl < 1){
				return error(-1,"参数错误");
			}
			JSONObject guidance = patientHealthGuidanceService.findById(idl);
			return write(200,"查询成功","data",guidance);
		}catch (Exception e){
			return error(-1,"查询失败");
		}
	}
	/*/**
	 * 添加患者健康指导
	 * @param patient 患者标识
	 * @param content 指导内容
	 * @return
	 */
	/*@RequestMapping(value = "add")
	@ResponseBody
	public String add(String patient, String content, @RequestParam(required = false) String images, @RequestParam(required = false) String voice) {
		try {
			PatientHealthGuidance guidance = new PatientHealthGuidance();
			guidance.setContent(content);
			guidance.setDoctor(getUID());
			guidance.setPatient(patient);
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			guidance.setImages(images);
			if (StringUtils.isNotEmpty(voice)) {
				images = CommonUtil.copyTempVoice(voice);
			}
			guidance.setVoice(voice);
			// 保存
			if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
				Patient p = patientService.findByCode(patient);
				consultService.sendMucMessageBySingnType(getUID(),doctor.getName(),patient,content,"1",p.getName());
				BusinessLogs.info(BusinessLogs.BusinessType.guidance, patient, new JSONObject(guidance));
				return success("保存成功!");
			} else {
				return error(-1, "保存失败!");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败!");
		}
	}*/
	//  ====================修改代码========================
	/**
	 * 添加患者健康指导(modelCode不为空判断为使用模板)
	 * @param patient 患者标识
	 * @param content 指导内容
	 * @param modelCode 指导模板编码
	 * @param images   指导图片
	 * @param voice   指导语音
	 * @return
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	@ObserverRequired
	public String add(@RequestParam String patient,
					  @RequestParam String content,
					  @RequestParam(required = false) String modelCode,
					  @RequestParam(required = false) String images,
					  @RequestParam(required = false) String voice) {
		String imageUrls = "";
		String imageRow = "";
		if(StringUtils.isBlank(modelCode)) {
//			不使用模板指导,旧版手工指导
			try {
				PatientHealthGuidance guidance = new PatientHealthGuidance();
				guidance.setContent(content);
				guidance.setDoctor(getUID());
				guidance.setPatient(patient);
//				找到当前医生
				Doctor doctor = doctorService.findDoctorByCode(getUID());
				if (images==null||"".equals(images)) {
					images=null;
				}else {
					String[] imgs = images.split(",");
					for (String image : imgs) {
						if (image.contains("http://")) {
							imageUrls += image + ",";
						} else {
							try {
								imageRow += CommonUtil.copyTempImage(image)+",";
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					images = imageUrls + imageRow;
					images =  images.substring(0,images.length()-1);
				}
				/*if (StringUtils.isNotEmpty(images)) {
					images = CommonUtil.copyTempImage(images);
				}*/
				guidance.setImages(images);
				// 保存到居民端健康指导
				if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
					Patient p = patientService.findByCode(patient);
					String imcotent  = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + guidance.getImages() + "\",\"content\":\""+CommonUtil.getSubString(guidance.getContent(),0,30)+"\"}";
					consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
					BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
					return success("保存成功!");
				} else {
					return error(-1, "保存失败!");
				}
			} catch (Exception e) {
				error(e);
				return error(-1, "保存失败!");
			}
		}else{
			try{
				PatientHealthGuidance guidance = new PatientHealthGuidance();
				guidance.setContent(content);
				guidance.setDoctor(getUID());
				guidance.setPatient(patient);
				Doctor doctor = doctorService.findDoctorByCode(getUID());
				if (images==null||"".equals(images)) {
					images = null;
				}else {
					String[] imgs = images.split(",");
					for (String image : imgs) {
						if (image.contains("http://")) {
							imageUrls += image + ",";
						} else {
							try {
								imageRow += CommonUtil.copyTempImage(image)+",";
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					images = imageUrls + imageRow;
					images =  images.substring(0,images.length()-1);
				}
				guidance.setImages(images);
				// 保存
				if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
					String sendImgs = "";
					if(StringUtils.isNotBlank(images)){
						sendImgs = images;
					}
					Patient p = patientService.findByCode(patient);
					String imcotent  = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\""+CommonUtil.getSubString(guidance.getContent(),0,30)+"\"}";
					consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
					BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
					//发送成功记录模板发送次数
					doctorGuidanceTempService.countSend(modelCode);
					return success("保存成功!");
				} else {
					return error(-1, "保存失败!");
				}
			}catch (Exception e){
				error(e);
				return error(-1, "保存失败!");
			}
		}
	}
	//  ============================================
	/**
	 * 查询患者的健康指导
	 * @param patient 患者标识
	 * @param begin   开始时间
	 * @param end     结束时间
	 * @param id	  指导编码
	 * @param pagesize 展示页数
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam(required = false) String patient,
					   @RequestParam(required = false) String begin,
					   @RequestParam(required = false) String end,
					   @RequestParam String id,
					   @RequestParam String pagesize) {
		try {
			Long idl = Long.parseLong(id);
			int  page = Integer.parseInt(pagesize);
			if (StringUtils.isNotEmpty(begin)) {
				begin = begin + " 00:00:00";
			}
			if (StringUtils.isNotEmpty(end)) {
				end = end + " 23:59:59";
			}
			JSONArray array = patientHealthGuidanceService.findPatientGuidanceByDoctor(getUID(), patient, begin, end, idl, page);
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 查询患者的健康指导
	 *
	 * @param patient
	 * @param teamCode
	 * @param page
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value = "查询居民健康指导记录")
	public String list(@RequestParam @ApiParam(value = "居民code") String patient,
					   @RequestParam @ApiParam(value = "团队Code") Long teamCode,
					   @RequestParam @ApiParam(value = "第几页") int page,
					   @RequestParam @ApiParam(value = "页大小") int pagesize) {
		try {
			if (StringUtils.isEmpty(patient)) {
				return error(-1, "请输入需查询的居民");
			}
			if (teamCode == null || teamCode < 1) {
				return error(-1, "请输入需查询的居民的团队");
			}
			page = page > 0 ? page - 1 : 0;
			JSONArray result = patientHealthGuidanceService.findByPatientAndGuidanceAndTeam(patient,teamCode,page,pagesize);
			return write(200, "查询成功!", "data", result);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
}

+ 0 - 263
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthRecordController.java

@ -1,263 +0,0 @@
package com.yihu.wlyy.web.doctor.health;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
import com.yihu.wlyy.service.app.health.PatientHealthRecordService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.third.jw.JwArchivesService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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;
/**
 * 医生端:健康记录控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/health_record", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "健康记录")
public class DoctorHealthRecordController extends BaseController {
	@Autowired
	private PatientHealthRecordService patientHealthRecordService;
	@Autowired
	private JwArchivesService jwArchivesService;
	@Autowired
	private PatientService patientService;
	/**
	 * 患者最近填写的运动、用药、饮食内容
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	@ApiOperation("根据患者标志获取最近的保健记录")
	public String recent(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
									 @RequestParam(value="patient",required = true) String patient) {
		try {
			JSONObject json = patientHealthRecordService.findRecentByPatient(patient);
			if (json != null) {
				return write(200, "查询成功", "data", json);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	
	/**
	 * 运动记录查询接口
	 * @param patient 患者标识
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_sports")
	@ResponseBody
	@ApiOperation("获取患者运动记录")
	public String sports(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
							 @RequestParam(value="patient",required = true)String patient,
						 @ApiParam(name="start",value="开始时间",defaultValue = "2017-05-15 00:00:00")
						 @RequestParam(value="start",required = true)String start,
						 @ApiParam(name="end",value="结束时间",defaultValue = "2017-05-15 12:00:00")
							 @RequestParam(value="end",required = true) String end,
						 @ApiParam(name="page",value="第几页",defaultValue = "1")
							 @RequestParam(value="page",required = true) int page,
						 @ApiParam(name="pagesize",value="每页记录数",defaultValue = "10")
							 @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			//Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatient(patient, DateUtil.strToDateLong(sortDate), pagesize);
			Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatientPage(patient, start,end,page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordSports record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置运动时长(分钟)
					json.put("sports_time", record.getSportsTime());
					// 设置运动强度
					json.put("sports_type", record.getSportsTypeName());
					// 设置运动类型
					json.put("sports", record.getSportsName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	/**
	 * 用药记录查询接口
	 * @param patient 患者标识
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_medication")
	@ResponseBody
	@ApiOperation("获取患者用药记录")
	public String medication(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
								 @RequestParam(value="patient",required = true)String patient,
							 @ApiParam(name="start",value="开始")
							 	 @RequestParam(required = false) String start,
							 @ApiParam(name="end",value="结束")
								 @RequestParam(required = false) String end,
							 @ApiParam(name="page",value="第几页",defaultValue = "1")
								 @RequestParam(required = false) Integer page,
							 @ApiParam(name="sortDate",value="日期")
							 	@RequestParam(required = false) String sortDate,
							 @ApiParam(name="pagesize",value="每页记录数",defaultValue = "10")
								 @RequestParam(required = true)int pagesize) {
		try {
			Page<PatientHealthRecordMedication> data = null;
			if(!StringUtils.isEmpty(sortDate)) {
				data = patientHealthRecordService.findMedicationByPatient(patient, DateUtil.strToDateLong(sortDate),page, pagesize);
			} else {
				data = patientHealthRecordService.findMedicalByPatientPage(patient, start, end, page, pagesize);
			}
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordMedication record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 药品名称
					json.put("medicines", record.getMedicinesName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	/**
	 * 饮食记录查询接口
	 * @param patient 患者标识
	 * @param page 页码
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_diet")
	@ResponseBody
	public String diet(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
						   @RequestParam(value="patient",required = true)String patient,
					   @ApiParam(name="start",value="开始")
					   @RequestParam(required = true) String start,
					   @ApiParam(name="end",value="结束")
						   @RequestParam(required = false) String end,
					   @ApiParam(name="page",value="第几页",defaultValue = "1")
						   @RequestParam(required = true)int page,
					   @ApiParam(name="pagesize",value="每页记录数",defaultValue = "10")
						   @RequestParam(required = true)int pagesize) {
		try {
			Page<PatientHealthRecordDiet> data = patientHealthRecordService.findDietByPatientPage(patient, start,end, page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordDiet record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置饮食内容
					json.put("content", record.getContent());
					// 设置图片URL,多图以逗号分隔
					json.put("images", record.getImages());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	@RequestMapping(value = "list_medical", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("查询居民健康体检列表")
	public String medical(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
						    @RequestParam(value="patient",required = true) String patient ,
						    @ApiParam(name = "pageIndex", value = "第几页", defaultValue = "")
						    @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
						    @ApiParam(name = "pageSize", value = "每页记录数", defaultValue = "")
							@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		try{
			Patient p = patientService.findByCode(patient);
			if(p != null){
				JSONArray re = jwArchivesService.getEhrSickMedicalList(p.getIdcard(),pageIndex,pageSize);
				return write(200,"查询成功","list",re);
			}else{
				return error(-1,"患者不存在");
			}
		}catch (Exception e){
			error(e);
			return error(-1,"查询失败");
		}
	}
	@RequestMapping(value = "medical_detail", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("查询居民健康体检详情信息")
	public String medical_detail(@ApiParam(name = "medicalNo", value = "体检ID", defaultValue = "1249652")
								  @RequestParam(value="medicalNo",required = true) String medicalNo){
		try{
			JSONObject json = jwArchivesService.getEhrSickMedicalRecord(medicalNo);
			return write(200,"查询成功","medical_detail",json);
		}catch (Exception e){
			error(e);
			return error(-1,"查询失败");
		}
	}
}

+ 0 - 296
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/intervene/DoctorInterveneController.java

@ -1,296 +0,0 @@
package com.yihu.wlyy.web.doctor.intervene;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.yihu.wlyy.aop.ObserverRequired;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
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.device.PatientDevice;
import com.yihu.wlyy.entity.patient.PatientInspectionSuggest;
import com.yihu.wlyy.entity.patient.PatientSelfInspection;
import com.yihu.wlyy.entity.patient.PatientSelfInspectionItem;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.intervene.PatientInspectionService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MessageType;
import com.yihu.wlyy.web.BaseController;
/**
 * 医生干预控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/intervene", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-预防与干预")
public class DoctorInterveneController extends BaseController {
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private PatientDeviceService patientDeviceService;
	@Autowired
	private PatientInspectionService patientInspectionService;
	@Autowired
	private PushMsgTask pushMsgTask;
	/**
	 * 患者可用设备查询接口
	 * @param patient
	 * @return
	 */
	@RequestMapping(value = "devices")
	@ResponseBody
	public String devices(String patient) {
		try {
			JSONArray array = new JSONArray();
			Iterator<PatientDevice> iterator = patientDeviceService.findPatientHave(patient);
			while (iterator != null && iterator.hasNext()) {
				PatientDevice pd = iterator.next();
				if (pd == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 设置设备标识
				json.put("code", pd.getDeviceId());
				// 设置设备名称
				json.put("name", pd.getDeviceName());
				array.put(json);
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 添加患者自查接口
	 * @param type 咨询类型:1三师咨询(即时咨询),2视频咨询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param devices 建议设备信息
	 * @return
	 */
	@RequestMapping(value = "self_exam")
	@ResponseBody
	@ObserverRequired
	public String selfExam(@RequestParam(required = false) Integer type, @RequestParam(required = false) String consult, String patient, String devices) {
		try {
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			if (type == null) {
				type = 0;
			}
			// 生成自查对象
			PatientSelfInspection inspection = new PatientSelfInspection();
			// 设置自查标识
			inspection.setCode(patientInspectionService.getCode());
			// 设置咨询标识
			inspection.setConsult(consult);
			inspection.setCzrq(new Date());
			// 设置医生标识
			inspection.setDoctor(doctor.getCode());
			// 设置医生姓名
			inspection.setDoctorName(doctor.getName());
			// 设置患者标识
			inspection.setPatient(patient);
			// 设置咨询类型:1三师咨询(即时咨询),2视频咨询
			inspection.setType(type);
			inspection.setDel("1");
			// 生成自查建议项
			String title = "";
			List<PatientSelfInspectionItem> items = new ArrayList<PatientSelfInspectionItem>();
			JSONArray array = new JSONArray(devices);
			for (int i = 0; i < array.length(); i++) {
				JSONObject json = array.getJSONObject(i);
				if (json == null) {
					continue;
				}
				PatientSelfInspectionItem item = new PatientSelfInspectionItem();
				// 设置自查项说明
				item.setContent(json.getString("content"));
				item.setCzrq(inspection.getCzrq());
				// 设置设备标识
				// item.setDevice(json.getString("device"));
				// 设置设备名称
				item.setDeviceName(json.getString("device_name"));
				// 设置自查标识
				item.setInspection(inspection.getCode());
				items.add(item);
				if (title.length() == 0) {
					title = json.getString("device_name");
				} else {
					title += "、" + json.getString("device_name");
				}
			}
			// 设置标题
			inspection.setTitle(title);
			if (items.isEmpty()) {
				return error(-1, "保存失败!");
			}
			// 保存到数据库
			patientInspectionService.save(inspection, items);
			// 推送消息给患者
			pushMsgTask.put(patient, MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.P_SI_01.name(), MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.体测提醒.name(), MessageType.MESSAGE_TYPE_PATIENT_SELF_INSPECTION.您有新的体测提醒.name(), inspection.getCode());
			return success("保存成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败!");
		}
	}
	/**
	 * 添加检查建议接口
	 * @param type 咨询类型:1三师咨询(即时咨询),2视频咨询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param suggest 检查建议
	 * @return
	 */
	@RequestMapping(value = "inspection")
	@ResponseBody
	@ObserverRequired
	public String inspection(int type, String consult, String patient, String suggest) {
		try {
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			PatientInspectionSuggest pis = new PatientInspectionSuggest();
			// 设置咨询标识
			pis.setConsult(consult);
			pis.setCzrq(new Date());
			// 设置医生标识
			pis.setDoctor(getUID());
			// 设置医生姓名
			pis.setDoctorName(doctor.getName());
			pis.setDel("1");
			// 设置患者标识
			pis.setPatient(patient);
			// 设置咨询类型:1三师咨询(即时咨询),2视频咨询
			pis.setType(type);
			// 设置建议内容
			pis.setContent(suggest);
			// 保存到数据库
			PatientInspectionSuggest temp = patientInspectionService.save(pis);
			// 推送消息给患者
			pushMsgTask.put(patient, MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.P_IS_01.name(), MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.检查检验.name(), MessageType.MESSAGE_TYPE_PATIENT_INSPECTION_SUGGEST.您有新的检查检验建议.name(), String.valueOf(temp.getId()));
			return success("保存成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败!");
		}
	}
	/**
	 * 患者检查建议查询接口
	 * @param patient
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "inspection_list")
	@ResponseBody
	public String inspection(String patient, long id, int pagesize) {
		try {
			Page<PatientInspectionSuggest> list = patientInspectionService.findPatientSuggestByDoctor(getUID(), patient, id, pagesize);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientInspectionSuggest suggest : list) {
					if (suggest == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", suggest.getId());
					json.put("content", suggest.getContent());
					json.put("czrq", DateUtil.dateToStrLong(suggest.getCzrq()));
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 查询指定患者的体测提醒
	 * @param patient
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "self_exam_list")
	@ResponseBody
	public String selfExamList(String patient, long id, int pagesize) {
		try {
			Page<PatientSelfInspection> list = patientInspectionService.findPatientByDoctor(getUID(), patient, id, pagesize);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientSelfInspection psi : list) {
					if (psi == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", psi.getId());
					json.put("code", psi.getCode());
					json.put("title", psi.getTitle());
					json.put("type", psi.getType());
					json.put("czrq", DateUtil.dateToStrLong(psi.getCzrq()));
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
	/**
	 * 查询体检提醒信息
	 * @param inspection 提醒标识
	 * @return
	 */
	@RequestMapping(value = "self_exam_info")
	@ResponseBody
	public String selfExamInfo(String inspection) {
		try {
			List<PatientSelfInspectionItem> list = patientInspectionService.findSelfExamInfo(inspection);
			JSONArray array = new JSONArray();
			if (list != null) {
				for (PatientSelfInspectionItem psii : list) {
					if (psii == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 设备名称
					json.put("deviceName", psii.getDeviceName());
					// 提醒说明
					json.put("content", psii.getContent());
					array.put(json);
				}
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
}

+ 0 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/web/doctor/medical/DoctorMedicalRecordController.java


이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.