Kaynağa Gözat

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

huangwenjie 7 yıl önce
ebeveyn
işleme
9fe665c74d
94 değiştirilmiş dosya ile 4840 ekleme ve 1093 silme
  1. 97 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLJobConfig.java
  2. 43 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDict.java
  3. 52 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDictJob.java
  4. 3 1
      common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionLog.java
  5. 1 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/config/SpringSecurityConfig.java
  6. 110 6
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/DeviceHealthIndexController.java
  7. 9 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndex.java
  8. 199 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndexVO.java
  9. 23 2
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/WlyyPatientDeviceVO.java
  10. 7 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/repository/DeviceHealthIndexDao.java
  11. 111 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/device/PatientHealthStandard.java
  12. 6 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/SignFamilyDao.java
  13. 4 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/WlyyPatientDeviceDao.java
  14. 253 11
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/DeviceHealthIndexService.java
  15. 3 1
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/WlyyPatientDeviceService.java
  16. 34 5
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list.jsp
  17. 147 5
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list_js.jsp
  18. 2 1
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/patientDevice_list_js.jsp
  19. 6 26
      patient-co/patient-co-doctor-assistant/pom.xml
  20. 5 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/Application.java
  21. 3 1
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/MvcConfig.java
  22. 1 1
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/war/ServletInitializer.java
  23. 9 0
      patient-co/patient-co-figure-label/pom.xml
  24. 8 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/FigureLabelApplication.java
  25. 2 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/config/db/WlyyJpa.java
  26. 445 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/BaseController.java
  27. 231 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/JobController.java
  28. 65 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/AgeConvert.java
  29. 43 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/BirthConvert.java
  30. 4 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/Convert.java
  31. 98 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/ConvertHelper.java
  32. 14 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/HealthConditionConvert.java
  33. 36 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/SexConvert.java
  34. 66 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLJobConfigDao.java
  35. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictDao.java
  36. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictJobDao.java
  37. 7 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/Extracter.java
  38. 22 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/MysqlExtracter.java
  39. 143 7
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/job/Mysql2ESJob.java
  40. 80 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/DataModel.java
  41. 0 31
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/ExtractModel.java
  42. 30 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/SaveModel.java
  43. 5 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/ExtractService.java
  44. 390 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/JobService.java
  45. 37 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2ES.java
  46. 12 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2Hbase.java
  47. 7 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/ConstantUtil.java
  48. 124 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/IdCardUtil.java
  49. 121 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/QuartzHelpers.java
  50. 17 5
      patient-co/patient-co-figure-label/src/main/resources/application-dev.yml
  51. 1 1
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java
  52. 9 2
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PatientConfirmReceiptJob.java
  53. 2 2
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionDao.java
  54. 3 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionLogDao.java
  55. 6 6
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  56. 66 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionLogService.java
  57. 4 4
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  58. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java
  59. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientHealthGuidanceDao.java
  60. 4 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientReservationDao.java
  61. 115 81
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/DoctorInfoService.java
  62. 64 37
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/consult/ConsultTeamService.java
  63. 13 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java
  64. 46 9
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/family/FamilyMemberService.java
  65. 1 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/followup/FollowUpService.java
  66. 21 15
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthGuidanceService.java
  67. 178 6
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  68. 69 48
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/physicalExamination/PhysicalExaminationRemindService.java
  69. 18 4
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java
  70. 20 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionInfoService.java
  71. 58 14
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionNoticesService.java
  72. 31 18
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionService.java
  73. 11 6
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/reservation/PatientReservationService.java
  74. 180 168
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  75. 34 21
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/PatientRemindService.java
  76. 236 186
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java
  77. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java
  78. 9 41
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/jimeiJkEdu/JMJkEduArticleService.java
  79. 33 35
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/survey/ManagerQuestionnaireService.java
  80. 13 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java
  81. 56 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/iot/IotDeviceService.java
  82. 36 19
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/task/RemindExpensesTask.java
  83. 14 24
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultPublicController.java
  84. 17 17
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java
  85. 5 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/prescription/PrescriptionInfoController.java
  86. 32 36
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/survey/ManagerQuestionnaireController.java
  87. 82 65
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/booking/PatientBookingController.java
  88. 54 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java
  89. 8 4
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java
  90. 3 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/iot/IotMonitoringHealthController.java
  91. 9 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/vo/HealthEduArticlePatientModel.java
  92. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/iot/IotDeviceController.java
  93. 81 85
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/zysoft/BookingController.java
  94. 1 1
      patient-co/patient-co-wlyy/src/main/resources/application-test.yml

+ 97 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLJobConfig.java

@ -0,0 +1,97 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_job_config")
public class FLJobConfig extends IdEntity {
    private String jobName;
    private String jobClass;
    private String sql;
    private Integer sqlFieldType;
    private String sqlFieldValue;
    private String sqlField;
    private String quartzCron;
    private String status;
    private String del;
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobClass() {
        return jobClass;
    }
    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public Integer getSqlFieldType() {
        return sqlFieldType;
    }
    public void setSqlFieldType(Integer sqlFieldType) {
        this.sqlFieldType = sqlFieldType;
    }
    public String getSqlFieldValue() {
        return sqlFieldValue;
    }
    public void setSqlFieldValue(String sqlFieldValue) {
        this.sqlFieldValue = sqlFieldValue;
    }
    public String getSqlField() {
        return sqlField;
    }
    public void setSqlField(String sqlField) {
        this.sqlField = sqlField;
    }
    public String getQuartzCron() {
        return quartzCron;
    }
    public void setQuartzCron(String quartzCron) {
        this.quartzCron = quartzCron;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
}

+ 43 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDict.java

@ -0,0 +1,43 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_label_dict")
public class FLlabelDict extends IdEntity {
    private String parentCode;
    private String labelName;
    private String labelCode;
    public String getParentCode() {
        return parentCode;
    }
    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
}

+ 52 - 0
common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDictJob.java

@ -0,0 +1,52 @@
package com.yihu.figure_label.entity;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by lith on 2018/03/07.
 */
@Entity
@Table(name = "fl_label_dict_job")
public class FLlabelDictJob extends IdEntity {
    private Long jobId;
    private String labelType;
    private String sql;
    private String convertClazz;
    public Long getJobId() {
        return jobId;
    }
    public void setJobId(Long jobId) {
        this.jobId = jobId;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public String getSql() {
        return sql;
    }
    public void setSql(String sql) {
        this.sql = sql;
    }
    public String getConvertClazz() {
        return convertClazz;
    }
    public void setConvertClazz(String convertClazz) {
        this.convertClazz = convertClazz;
    }
}

+ 3 - 1
common/common-entity/src/main/java/com/yihu/wlyy/entity/patient/prescription/PrescriptionLog.java

@ -27,7 +27,9 @@ public class PrescriptionLog extends IdEntity {
        pay("支付", 5),
        expressage("配送", 6),
        finish("已完成", 7),
        sf("顺丰对接", 8);
        sf("顺丰对接", 8),
        patientConfirm("居民确认收药", 9),
        jobConfirm("系统确认收药", 10);
        private String name;
        private int value;

+ 1 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/config/SpringSecurityConfig.java

@ -39,6 +39,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
                "/admin/device/toExcel",
                "/admin/patientDevice/toExcel",
                "/admin/healthIndex/toExcel",
                "/admin/healthIndex/getExcelByFilter",
                "/admin/static/prescription/toExcel",
                "/admin/static/wechat/listToExcel",
                "/admin/static/wechat/hosipitaTotalToExcel",

+ 110 - 6
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/DeviceHealthIndexController.java

@ -1,23 +1,25 @@
package com.yihu.wlyy.controller.manager.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.device.entity.DeviceHealthIndex;
import com.yihu.wlyy.device.entity.DeviceHealthIndexExportVO;
import com.yihu.wlyy.device.entity.DeviceHealthIndexVO;
import com.yihu.wlyy.service.manager.device.DeviceHealthIndexService;
import jxl.Workbook;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/12/5.
@ -38,10 +40,17 @@ public class DeviceHealthIndexController extends BaseController{
            @RequestParam(value = "date",required = false) String date,
            @RequestParam(value = "idcard",required = false) String idcard,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "indexType",required = false) String indexType,
            @RequestParam(value = "indexTypeMin1",required = false) Integer indexTypeMin1,
            @RequestParam(value = "indexTypeMax1",required = false) Integer indexTypeMax1,
            @RequestParam(value = "indexTypeMin2",required = false) Integer indexTypeMin2,
            @RequestParam(value = "indexTypeMax2",required = false) Integer indexTypeMax2,
            @RequestParam(value = "doctorName",required = false) String doctorName,
            @RequestParam(value = "page",required = false) Integer page,
            @RequestParam(value = "rows",required = false) Integer pageSize){
        try{
            Page<DeviceHealthIndex> deviceHealthIndexes = healthIndexService.searchList(deviceSn,date, idcard, userName, page, pageSize);
            Page<DeviceHealthIndexVO> deviceHealthIndexes = healthIndexService.searchList(deviceSn,date, idcard, userName, indexType,page, pageSize,indexTypeMin1, indexTypeMax1, indexTypeMin2,indexTypeMax2,doctorName);
            return write(200,"操作成功",page,pageSize,deviceHealthIndexes);
        }catch (Exception ex){
            error(ex);
@ -65,7 +74,47 @@ public class DeviceHealthIndexController extends BaseController{
            error(ex);
        }
    }
    
    /**
     * 按筛选条件导出居民体征数据报表
     * @param deviceSn 设备sn码
     * @param date 查询日期
     * @param idcard 居民身份证号
     * @param userName 居民姓名
     * @param indexType 体征类别
     * @param response
     * @return
     */
//    @ResponseBody
    @RequestMapping(value="getExcelByFilter",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public  String exportList(
            @RequestParam(value = "deviceSn",required = false) String deviceSn,
            @RequestParam(value = "date",required = false) String date,
            @RequestParam(value = "idcard",required = false) String idcard,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "indexType",required = false) String indexType,
            @RequestParam(value = "indexTypeMin1",required = false) Double indexTypeMin1,
            @RequestParam(value = "indexTypeMax1",required = false) Double indexTypeMax1,
            @RequestParam(value = "indexTypeMin2",required = false) Double indexTypeMin2,
            @RequestParam(value = "indexTypeMax2",required = false) Double indexTypeMax2,
            @RequestParam(value = "doctorName",required = false) String doctorName,
            HttpServletResponse response){
        try {
            List<DeviceHealthIndexVO> deviceHealthIndexes = healthIndexService.getExcelByFilter(deviceSn,date, idcard, userName, indexType,indexTypeMin1,indexTypeMax1,indexTypeMin2,indexTypeMax2,doctorName);
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="+ new String( "patientHealthIndexDataList.xls"));
            OutputStream os = response.getOutputStream();
            this.writePatientHealth(os,deviceHealthIndexes);
            write(200, "操作成功!");
            Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("status", 200);
            map.put("msg", "操作成功!");
            return write(200, "操作成功");
        }catch (Exception ex){
            error(ex);
            return null;
        }
    }
    
    public void addHeader(WritableSheet ws) throws WriteException {
        
@ -76,6 +125,16 @@ public class DeviceHealthIndexController extends BaseController{
            i++;
        }
    }
    public void addPatientHealthHeader(WritableSheet ws) throws WriteException {
        String[] header = {"SN码","创建日期","身份证号","姓名","数据类型","value1","value2","value3","value4","value5","value6","value7"};
        int i = 0;
        for (String h : header) {
            addCell(ws, 0, i, h);//表名,行,列,header
            i++;
        }
    }
    
    public void write(WritableWorkbook wwb, List ls) throws Exception {
        try {
@ -101,9 +160,54 @@ public class DeviceHealthIndexController extends BaseController{
            throw e;
        }
    }
    public void writePatientHealth(WritableWorkbook wwb, List ls) throws Exception {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            WritableSheet ws;
            ws = wwb.createSheet("sheet",1);
            addPatientHealthHeader(ws);
            int i = 1;
            for (DeviceHealthIndexVO m : (List<DeviceHealthIndexVO>) ls) {
                String type = "未知";
                if (m.getType()==1){
                    type = "血糖";
                }else if (m.getType()==2){
                    type = "血压";
                }else if (m.getType()==3){
                    type = "体重";
                }else if (m.getType()==4){
                    type = "腰围";
                }
                addCell(ws, i, 0, m.getDeviceSn(),"");
                addCell(ws, i, 1, format.format(m.getCzrq()),"");
                addCell(ws, i, 2, m.getIdcard(),"");
                addCell(ws, i, 3, m.getUserName(),"");
                addCell(ws, i, 4, type,"");
                addCell(ws, i, 5, m.getValue1(),"");
                addCell(ws, i, 6, m.getValue2(),"");
                addCell(ws, i, 7, m.getValue3(),"");
                addCell(ws, i, 8, m.getValue4(),"");
                addCell(ws, i, 9, m.getValue5(),"");
                addCell(ws, i, 10, m.getValue6(),"");
                addCell(ws, i, 11, m.getValue7(),"");
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }
    public void write(OutputStream os, List ls) throws Exception{
        write(Workbook.createWorkbook(os), ls);
    }
    public void writePatientHealth(OutputStream os, List ls) throws Exception{
        writePatientHealth(Workbook.createWorkbook(os), ls);
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column,  String data) throws WriteException {
        Label label = new Label(column ,row, data);

+ 9 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndex.java

@ -25,6 +25,7 @@ public class DeviceHealthIndex {
    private int type;
    private String user;
    private String userName;
    private Integer status;
    private String value1;
    private String value2;
    private String value3;
@ -202,4 +203,12 @@ public class DeviceHealthIndex {
        this.value7 = value7;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 199 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndexVO.java

@ -0,0 +1,199 @@
package com.yihu.wlyy.device.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
/**
 * Created by yww on 2016/12/5.
 * 体征数据表
 */
public class DeviceHealthIndexVO {
    private Long id;
    private Date czrq;
    private String del;
    private String deviceSn;
    private String idcard;
    private String intervene;
    private Date recordDate;
    private Date sortDate;
    private int type;
    private String user;
    private String userName;
    private Integer status;
    private String value1;
    private String value2;
    private String value3;
    private String value4;
    private String value5;
    private String value6;
    private String value7;
    private String healthStandard;
    public DeviceHealthIndexVO() {
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getIntervene() {
        return intervene;
    }
    public void setIntervene(String intervene) {
        this.intervene = intervene;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getRecordDate() {
        return recordDate;
    }
    public void setRecordDate(Date recordDate) {
        this.recordDate = recordDate;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getSortDate() {
        return sortDate;
    }
    public void setSortDate(Date sortDate) {
        this.sortDate = sortDate;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getValue1() {
        return value1;
    }
    public void setValue1(String value1) {
        this.value1 = value1;
    }
    public String getValue2() {
        return value2;
    }
    public void setValue2(String value2) {
        this.value2 = value2;
    }
    public String getValue3() {
        return value3;
    }
    public void setValue3(String value3) {
        this.value3 = value3;
    }
    public String getValue4() {
        return value4;
    }
    public void setValue4(String value4) {
        this.value4 = value4;
    }
    public String getValue5() {
        return value5;
    }
    public void setValue5(String value5) {
        this.value5 = value5;
    }
    public String getValue6() {
        return value6;
    }
    public void setValue6(String value6) {
        this.value6 = value6;
    }
    public String getValue7() {
        return value7;
    }
    public void setValue7(String value7) {
        this.value7 = value7;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getHealthStandard() {
        return healthStandard;
    }
    public void setHealthStandard(String healthStandard) {
        this.healthStandard = healthStandard;
    }
}

+ 23 - 2
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/WlyyPatientDeviceVO.java

@ -1,5 +1,7 @@
package com.yihu.wlyy.device.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
@ -23,6 +25,8 @@ public class WlyyPatientDeviceVO {
	private String doctorName;
	private String hospital;
	private String hospitalName;
	private String doctorHealthName;
	private String doctorHealth;
	
	public Integer getId() {
		return id;
@ -103,11 +107,12 @@ public class WlyyPatientDeviceVO {
	public void setUserIdcard(String userIdcard) {
		this.userIdcard = userIdcard;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
@ -143,4 +148,20 @@ public class WlyyPatientDeviceVO {
	public void setHospitalName(String hospitalName) {
		this.hospitalName = hospitalName;
	}
	public String getDoctorHealthName() {
		return doctorHealthName;
	}
	public void setDoctorHealthName(String doctorHealthName) {
		this.doctorHealthName = doctorHealthName;
	}
	public String getDoctorHealth() {
		return doctorHealth;
	}
	public void setDoctorHealth(String doctorHealth) {
		this.doctorHealth = doctorHealth;
	}
}

+ 7 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/repository/DeviceHealthIndexDao.java

@ -1,11 +1,18 @@
package com.yihu.wlyy.device.repository;
import com.yihu.wlyy.device.entity.DeviceHealthIndex;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by yww on 2016/12/5.
 */
public interface DeviceHealthIndexDao extends PagingAndSortingRepository<DeviceHealthIndex,Long>,JpaSpecificationExecutor<DeviceHealthIndex> {
    // 查询带未读数量的所有健康咨询列表
//    @Query("SELECT a FROM device.wlyy_patient_health_index a, wlyy.wlyy_patient b WHERE a.user = b.code")
//    Page<DeviceHealthIndex> findList(String deviceSn,String startTime,String endTime,String idcard,String userName,String indexType,Integer indexTypeMin1,Integer indexTypeMax1,Integer indexTypeMin2,Integer indexTypeMax2, Pageable pageRequest);
}

+ 111 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/device/PatientHealthStandard.java

@ -0,0 +1,111 @@
package com.yihu.wlyy.entity.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 患者健康指标预警值
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_standard")
public class PatientHealthStandard extends IdEntity {
	/**
	 *
	 */
	private static final long serialVersionUID = -8343925049051333359L;
	// 患者标识
	private String patient;
	// 健康指标类型:1血糖,2血压,3体重,4腰围
	private Integer type;
	// 最低安全值(血糖餐前\收缩压\体重\腰围)
	private Double minValue1;
	// 最高安全值(血糖餐前\收缩压\体重\腰围)
	private Double maxValue1;
	// 最低安全值(血糖餐后\舒张压)
	private Double minValue2;
	// 最高安全值(血糖餐后\舒张压)
	private Double maxValue2;
	// 设置医生
	private String doctor;
	// 设置时间
	private Date czrq;
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	@Column(name = "min_value_1")
	public Double getMinValue1() {
		return minValue1;
	}
	public void setMinValue1(Double minValue) {
		this.minValue1 = minValue;
	}
	@Column(name = "max_value_1")
	public Double getMaxValue1() {
		return maxValue1;
	}
	public void setMaxValue1(Double maxValue) {
		this.maxValue1 = maxValue;
	}
	@Column(name = "min_value_2")
	public Double getMinValue2() {
		return minValue2;
	}
	public void setMinValue2(Double minValue) {
		this.minValue2 = minValue;
	}
	@Column(name = "max_value_2")
	public Double getMaxValue2() {
		return maxValue2;
	}
	public void setMaxValue2(Double maxValue) {
		this.maxValue2 = maxValue;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
}

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

@ -48,4 +48,10 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
    @Query(" from SignFamily a where a.patient = ?1 and a.type = ?2 and (a.status=-3 or a.status=-4)  order by a.id desc")
    List<SignFamily> findLastJySignByPatient(String patient, int type);
    @Query("select a.patient from SignFamily a where (a.doctorName like ?1 or a.doctorHealthName like ?1) and a.status > 0")
    String[] findByDoctorName(String doctorName);
    @Query("select a.patient from SignFamily a where a.hospital=?1 and a.status > 0")
    String[] findByHospital(String hospital);
}

+ 4 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/WlyyPatientDeviceDao.java

@ -1,10 +1,14 @@
package com.yihu.wlyy.repository;
import com.yihu.wlyy.entity.WlyyPatientDevice;
import com.yihu.wlyy.entity.device.PatientHealthStandard;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by yww on 2016/12/7.
 */
public interface WlyyPatientDeviceDao extends PagingAndSortingRepository<WlyyPatientDevice,Integer> {
    @Query("select a from PatientHealthStandard a where a.patient = ?1 and a.type = ?2")
    PatientHealthStandard findByPatientType(String patient, int type);
}

+ 253 - 11
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/DeviceHealthIndexService.java

@ -2,20 +2,32 @@ package com.yihu.wlyy.service.manager.device;
import com.yihu.wlyy.device.entity.DeviceHealthIndex;
import com.yihu.wlyy.device.entity.DeviceHealthIndexExportVO;
import com.yihu.wlyy.device.entity.DeviceHealthIndexVO;
import com.yihu.wlyy.device.repository.DeviceHealthIndexDao;
import com.yihu.wlyy.entity.Doctor;
import com.yihu.wlyy.entity.Patient;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.entity.device.PatientHealthStandard;
import com.yihu.wlyy.repository.DoctorDao;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.repository.SignFamilyDao;
import com.yihu.wlyy.repository.WlyyPatientDeviceDao;
import com.yihu.wlyy.util.DateTimeUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.query.BaseDeviceJpaService;
import org.apache.commons.lang3.StringUtils;
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.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
/**
@ -30,19 +42,44 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
    private PatientDao patientDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyPatientDeviceDao wlyyPatientDeviceDao;
    @Autowired
    private DeviceHealthIndexDao deviceHealthIndexDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    public Page<DeviceHealthIndex> searchList(String deviceSn,String date,String idcard,String userName,Integer page,Integer pageSize)throws Exception{
    public Page<DeviceHealthIndexVO> searchList(String deviceSn,String date,String idcard,String userName,String indexType,Integer page,Integer pageSize,
    Integer indexTypeMin1,Integer indexTypeMax1,Integer indexTypeMin2,Integer indexTypeMax2,String doctorName)throws Exception{
        if (page == null){
            page = 1;
        }
        if(pageSize == null){
            pageSize = 15;
        }
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        User loginUser = (User) request.getSession().getAttribute("userInfo");
//        HttpServletRequest request = ServletActionContext.getRequest();
//        HttpSession session = request.getSession();
        Pageable pageRequest = new PageRequest(page-1,pageSize);
        StringBuilder filter = new StringBuilder();
        //1、管理员  2、医生 0、其他
        if(loginUser.getType()==2){
            Doctor doctor = doctorDao.findByCode(loginUser.getCode());
            String[] codes =signFamilyDao.findByHospital(doctor.getHospital());
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }else {
                return new PageImpl<DeviceHealthIndexVO>(new ArrayList<>(), pageRequest, 0);
            }
        }
        if(!StringUtils.isEmpty(deviceSn)){
            filter.append("deviceSn="+deviceSn+";");
        }
@ -66,23 +103,167 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }else {
                return new PageImpl<DeviceHealthIndex>(new ArrayList<>(), pageRequest, 0);
                return new PageImpl<DeviceHealthIndexVO>(new ArrayList<>(), pageRequest, 0);
            }
        }
        //根据医生名称过滤居民
        if(!StringUtils.isEmpty(doctorName)){
            String[] codes = signFamilyDao.findByDoctorName("%"+doctorName+"%");
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }else {
                return new PageImpl<DeviceHealthIndexVO>(new ArrayList<>(), pageRequest, 0);
            }
        }
        if(!StringUtils.isEmpty(indexType)){
            filter.append("type="+indexType+";");
        }
        if("1".equals(indexType)||"2".equals(indexType)||"4".equals(indexType)){
            if(indexTypeMin1!=null){
                filter.append("value1>="+indexTypeMin1+";");
            }
            if(indexTypeMax1!=null){
                filter.append("value1<="+indexTypeMax1+";");
            }
            if(indexTypeMin2!=null){
                filter.append("value2>="+indexTypeMin2+";");
            }
            if(indexTypeMax2!=null){
                filter.append("value2<="+indexTypeMax2+";");
            }
        }else{
            if(indexTypeMin1!=null){
                filter.append("value3>="+indexTypeMin1+";");
            }
            if(indexTypeMax1!=null){
                filter.append("value3<="+indexTypeMax1+";");
            }
            if(indexTypeMin2!=null){
                filter.append("value4>="+indexTypeMin2+";");
            }
            if(indexTypeMax2!=null){
                filter.append("value4<="+indexTypeMax2+";");
            }
        }
        List<DeviceHealthIndex> list = (List<DeviceHealthIndex>)search("", filter.toString(), "-czrq", page, pageSize);
        long count = 0;
        String regex = "(\\w{3})(\\w+)(\\w{3})";
        List<DeviceHealthIndexVO> listTemp = new ArrayList<>();
        if(list !=null && list.size()>0){
            count = getCount(filter.toString());
            for (DeviceHealthIndex info : list){
                Patient patient = findPatient(info.getUser());
                info.setUserName(patient== null?"":patient.getName());
                if(StringUtils.isNotBlank(info.getIdcard())){
                    info.setIdcard(info.getIdcard().replaceAll(regex, "$1****$3"));
                DeviceHealthIndexVO bean = new DeviceHealthIndexVO();
                BeanUtils.copyProperties(info, bean);
//                BeanUtils.copyProperties(bean, info);
                Patient patient = findPatient(bean.getUser());
                bean.setUserName(patient== null?"":patient.getName());
                if(StringUtils.isNotBlank(bean.getIdcard())){
                    bean.setIdcard(bean.getIdcard().replaceAll(regex, "$1****$3"));
                }
                bean.setHealthStandard(gethealthStandard(info.getType(),info.getUser()).toString());
                listTemp.add(bean);
            }
        }
        return new PageImpl<DeviceHealthIndex>(list,pageRequest,count);
        return new PageImpl<DeviceHealthIndexVO>(listTemp,pageRequest,count);
    }
    public List<DeviceHealthIndexVO> getExcelByFilter(String deviceSn,String date,String idcard,
                                                String userName,String indexType,Double indexTypeMin1,Double indexTypeMax1,Double indexTypeMin2,Double indexTypeMax2,String doctorName)throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        User loginUser = (User) request.getSession().getAttribute("userInfo");
        StringBuilder filter = new StringBuilder();
        //1、管理员  2、医生 0、其他
        if(loginUser.getType()==2){
            Doctor doctor = doctorDao.findByCode(loginUser.getCode());
            String[] codes =signFamilyDao.findByHospital(doctor.getHospital());
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }
        }
        if(!StringUtils.isEmpty(deviceSn)){
            filter.append("deviceSn="+deviceSn+";");
        }
        if(!StringUtils.isEmpty(idcard)){
            filter.append("idcard="+idcard+";");
        }
        if(!StringUtils.isEmpty(date)){
            Date startTimeTemp  =  DateTimeUtil.simpleDateParse(date);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(startTimeTemp);
            calendar.set(Calendar.HOUR,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            calendar.set(Calendar.MILLISECOND,999);
            Date endTimeTemp = calendar.getTime();
            filter.append("czrq>=" + DateTimeUtil.utcDateTimeFormat(startTimeTemp)+ ";");
            filter.append("czrq<=" + DateTimeUtil.utcDateTimeFormat(endTimeTemp)+ ";");
        }
        if(!StringUtils.isEmpty(userName)){
            String[] codes = patientDao.findByName(userName);
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }
        }
        //根据医生名称过滤居民
        if(!StringUtils.isEmpty(doctorName)){
            String[] codes = signFamilyDao.findByDoctorName("%"+doctorName+"%");
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }
        }
        if(!StringUtils.isEmpty(indexType)){
            filter.append("type="+indexType+";");
        }
        if("1".equals(indexType)||"2".equals(indexType)||"4".equals(indexType)){
            if(indexTypeMin1!=null){
                filter.append("value1>="+indexTypeMin1+";");
            }
            if(indexTypeMax1!=null){
                filter.append("value1<="+indexTypeMax1+";");
            }
            if(indexTypeMin2!=null){
                filter.append("value2>="+indexTypeMin2+";");
            }
            if(indexTypeMax2!=null){
                filter.append("value2<="+indexTypeMax2+";");
            }
        }else{
            if(indexTypeMin1!=null){
                filter.append("value3>="+indexTypeMin1+";");
            }
            if(indexTypeMax1!=null){
                filter.append("value3<="+indexTypeMax1+";");
            }
            if(indexTypeMin2!=null){
                filter.append("value4>="+indexTypeMin2+";");
            }
            if(indexTypeMax2!=null){
                filter.append("value4<="+indexTypeMax2+";");
            }
        }
        List<DeviceHealthIndex> list = (List<DeviceHealthIndex>)search(filter.toString());
        String regex = "(\\w{3})(\\w+)(\\w{3})";
        List<DeviceHealthIndexVO> listTemp = new ArrayList<>();
        if(list !=null && list.size()>0){
            for (DeviceHealthIndex info : list){
                DeviceHealthIndexVO bean = new DeviceHealthIndexVO();
                BeanUtils.copyProperties(info, bean);
//                BeanUtils.copyProperties(bean, info);
                Patient patient = findPatient(bean.getUser());
                bean.setUserName(patient== null?"":patient.getName());
                if(StringUtils.isNotBlank(bean.getIdcard())){
                    bean.setIdcard(bean.getIdcard().replaceAll(regex, "$1****$3"));
                }
                bean.setHealthStandard(gethealthStandard(info.getType(),info.getUser()).toString());
                listTemp.add(bean);
            }
        }
        return listTemp;
    }
    //查询居民姓名
@ -109,4 +290,65 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
        list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper(DeviceHealthIndexExportVO.class));
        return list ;
	}
    public JSONObject gethealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = SystemConf.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = SystemConf.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = SystemConf.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            json.put("minValueSZY", minValueSZY);
            json.put("maxValueSZY", maxValueSZY);
            json.put("minValueSSY", minValueSSY);
            json.put("maxValueSSY", maxValueSSY);
        }
        return json;
    }
}

+ 3 - 1
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/WlyyPatientDeviceService.java

@ -145,7 +145,9 @@ public class WlyyPatientDeviceService extends BaseJpaService<WlyyPatientDevice,W
                "s.doctor as doctor," +
                "d.czrq as czrq," +
                "s.hospital_name as hospitalName," +
                "s.hospital as hospital " +
                "s.hospital as hospital," +
                "s.doctor_health_name as doctorHealthName,"+
                "s.doctor_health as doctorHealth "+
                "FROM " +
                "wlyy_sign_family s," +
                "wlyy_patient_device d," +

+ 34 - 5
patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list.jsp

@ -11,11 +11,14 @@
<head>
	<%@ include file="../head/page_head.jsp" %>
	<title>设备管理</title>
	<style>
		.dl-line{float: left;padding:10px 10px 8px;line-height: 1}
	</style>
</head>
<body>
<div id="div_wrapper">
	<!-- 检索条件 -->
	<div class="m-retrieve-area f-h50 f-dn f-pr m-form-inline" data-role-form style='display: block;'>
	<div class="m-retrieve-area f-dn f-pr m-form-inline" data-role-form style='display: block;'>
		<div class="m-form-group f-mt10">
			<div class="m-form-control f-ml15">
@ -30,12 +33,38 @@
			<div class="m-form-control f-ml15">
				<input type="text" id="inp_user_name" placeholder="请输入居民姓名" class="f-ml10" data-attr-scan="userName"/>
			</div>
			<sec:authorize url="/admin/healthIndex/list">
			<div id="btn_search" class="l-button u-btn u-btn-primary u-btn-small f-ib f-vam  f-ml10" >
				<span>查询</span>
			<div class="m-form-control f-ml15">
				<input type="text" id="inp_index_type" placeholder="血糖/血压/体重/腰围" class="f-ml10" data-attr-scan="indexType"/>
			</div>
			<sec:authorize url="/admin/healthIndex/list">
				<div id="btn_search" class="l-button u-btn u-btn-primary u-btn-small f-ib f-vam  f-ml10" >
					<span>查询</span>
				</div>
			</sec:authorize>
			<sec:authorize url="/admin/healthIndex/getExcelByFilter">
				<div id="btn_excel" class="l-button u-btn u-btn-primary u-btn-small f-ib f-vam  f-ml10" >
					<span>导出</span>
				</div>
			</sec:authorize>
			<div class="m-form-control f-ml15">
				<input type="text" id="inp_doctor_name" placeholder="请输入医生/健管师名称" class="f-ml10" data-attr-scan="doctorName"/>
			</div>
			<div id="select-list" class="f-mt10" style="display: none">
				<div class="m-form-control f-ml15">
					<input type="text" id="search-min-1" placeholder="" class="f-ml10" data-attr-scan="indexTypeMin1"/>
				</div>
				<span class="dl-line">-</span>
				<div class="m-form-control">
					<input type="text" id="search-max-1" placeholder="" data-attr-scan="indexTypeMax1"/>
				</div>
				<div class="m-form-control f-ml15">
					<input type="text" id="search-min-2" placeholder="" class="f-ml10" data-attr-scan="indexTypeMin2"/>
				</div>
				<span class="dl-line">-</span>
				<div class="m-form-control">
					<input type="text" id="search-max-2" placeholder="" data-attr-scan="indexTypeMax2"/>
				</div>
			</div>
		</div>
	</div>
	<!-- 列表 -->

+ 147 - 5
patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list_js.jsp

@ -28,6 +28,7 @@
			retrieve = {
				$element: $('.m-retrieve-area'),
				$searchBtn: $('#btn_search'),
                $btnExport: $('#btn_excel'),
				$addBtn: $('#btn_add'),
@ -35,11 +36,21 @@
				$czrd: $("#inp_czrq"),
				$idcard: $("#inp_idcard"),
				$userName: $("#inp_user_name"),//人员姓名
                $indexType: $("#inp_index_type"),//指标类型
                $searchMin1:$("#search-min-1"),
                $searchMax1:$("#search-max-1"),
                $searchMin2:$("#search-min-2"),
                $searchMax2:$("#search-max-2"),
                $doctorName:$("#inp_doctor_name"),
				init: function () {
					this.$element.show();
					this.$element.attrScan();
					window.form = this.$element;
					this.$deviceCode.ligerTextBox({width: 200});
                    this.$searchMax1.ligerTextBox({width: 150});
                    this.$searchMin1.ligerTextBox({width: 150});
                    this.$searchMax2.ligerTextBox({width: 150});
                    this.$searchMin2.ligerTextBox({width: 150});
					this.$czrd.ligerDateEditor({
						format: "yyyy-MM-dd",
						showTime: false,
@ -49,14 +60,107 @@
					});
					this.$idcard.ligerTextBox({width: 150});
					this.$userName.ligerTextBox({width: 150});
                    this.$doctorName.ligerTextBox({width: 150});
					this.bindEvents();
                    this.typeBox = this.$indexType.ligerComboBox({
                        width: 150,
                        data: [
                            {text: '血糖', typeId: '1'},
                            {text: '血压', typeId: '2'},
                            {text: '体重', typeId: '3'},
                            {text: '腰围', typeId: '4'}
                        ],
//                        initIsTriggerEvent: false,
                        valueField: 'typeId',
                        onSelected: function (value,name) {
                            if(value){
                                var valueNum1='value1';
                                var valueNum2='value2';
                                if(value==3){
                                    valueNum1='value3';
                                    valueNum2='value4';
                                }
                                $("#search-max-1").attr('placeholder',name+valueNum1+"最大值");
                                $("#search-min-1").attr('placeholder',name+valueNum1+'最小值');
                                $("#search-max-1").val('');
                                $("#search-min-1").val('');
                                $("#select-list").show();
                                $("#search-max-2").attr('placeholder',name+valueNum2+"最大值");
                                $("#search-min-2").attr('placeholder',name+valueNum2+'最小值');
                                $("#search-max-2").val('');
                                $("#search-min-2").val('');
                                $("#select-list").show();
                            }
                        }
                    });
				},
				bindEvents: function () {
					var self = this;
					self.$searchBtn.click(function () {
						master.grid.options.newPage = 1;
						master.reloadGrid();
					});
                        master.grid.options.newPage = 1;
                        master.reloadGrid();
                    });
                    self.$btnExport.click(function () {
                        var myform = $("<form></form>");
                        myform.attr('method','post')
                        myform.attr('action',ctx + '/admin/healthIndex/getExcelByFilter');
                        self.$element.attrScan();
                        var values = self.$element.Fields.getValues();
                        //设备SN码
                        var deviceSn = $("<input type='hidden' name='deviceSn' />")
                        deviceSn.attr('value',$("#inp_device_code").val());
                        //查询日期
                        var date = $("<input type='hidden' name='date' />")
                        date.attr('value',$("#inp_czrq").val());
                        //身份证号
                        var idcard = $("<input type='hidden' name='idcard' />")
                        idcard.attr('value',$("#inp_idcard").val());
                        //居民姓名
                        var userName = $("<input type='hidden' name='userName' />")
                        userName.attr('value',$("#inp_user_name").val());
                        //居民姓名
                        var doctorName = $("<input type='hidden' name='doctorName' />")
                        doctorName.attr('value',$("#inp_doctor_name").val());
                        //血糖/血压/体重/腰围
                        var indexType = $("<input type='hidden' name='indexType' />")
                        indexType.attr('value',$("#inp_index_type_val").val());
                        //指标1最小值
                        var indexTypeMin1 = $("<input type='hidden' name='indexTypeMin1' />")
                        indexTypeMin1.attr('value',$("#search-min-1").val());
                        //指标1最大值
                        var indexTypeMax1 = $("<input type='hidden' name='indexTypeMax1' />")
                        indexTypeMax1.attr('value',$("#search-max-1").val());
                        //指标2最小值
                        var indexTypeMin2 = $("<input type='hidden' name='indexTypeMin2' />")
                        indexTypeMin2.attr('value',$("#search-min-2").val());
                        //指标2最大值
                        var indexTypeMax2 = $("<input type='hidden' name='indexTypeMax2' />")
                        indexTypeMax2.attr('value',$("#search-max-2").val());
                        myform.append(deviceSn);
                        myform.append(date);
                        myform.append(idcard);
                        myform.append(userName);
                        myform.append(doctorName);
                        myform.append(indexType);
                        myform.append(indexTypeMin1);
                        myform.append(indexTypeMax1);
                        myform.append(indexTypeMin2);
                        myform.append(indexTypeMax2);
                        myform.appendTo('body').submit(); //must add this line for higher html spec
                    });
					//隐藏操作
                    self.$indexType.change(function(obj){
                        if(!obj.target.value){
                            $("#search-max-1").val('');
                            $("#search-min-1").val('');
                            $("#select-list").hide();
                            $("#search-max-2").val('');
                            $("#search-min-2").val('');
                            $("#select-list").hide();
                        }
                    });
				}
			};
			master = {
@ -91,8 +195,45 @@
									}
								}
							},
							{display: 'value1', name: 'value1', width: '5%', align: "center"},
							{display: 'value2', name: 'value2', width: '5%', align: "center"},
							{display: 'value1', name: 'value1', width: '5%', align: "center",
                                render: function (row) {
                                    var standard = typeof(row.healthStandard)=='object'?row.healthStandard:JSON.parse(row.healthStandard)
                                    if(row.type==1){
                                        if(row.value1>standard.minValueBefore&&row.value1<standard.maxValueBefore){
                                            return row.value1;
                                        }else {
                                            return "<span style='color:red;'>"+row.value1+"</span>";
                                        }
                                    }else if(row.type==2){
                                        if(row.value1>standard.minValueSSY&&row.value1<standard.maxValueSSY){
                                            return row.value1;
                                        }else {
                                            return "<span style='color:red;'>"+row.value1+"</span>";
                                        }
                                    }
                                }
                            },
							{display: 'value2', name: 'value2', width: '5%', align: "center",
                                render: function (row) {
                                    var standard = typeof(row.healthStandard)=='object'?row.healthStandard:JSON.parse(row.healthStandard)
                                    if(row.type==1){
                                        if(row.value2>standard.minValueAfter&&row.value2<standard.maxValueAfter){
                                            return row.value2;
                                        }else {
                                            return "<span style='color:red;'>"+row.value2+"</span>";
                                        }
                                    }else if(row.type==2){
                                        if(row.value2>standard.minValueSZY&&row.value2<standard.maxValueSZY){
                                            return row.value2;
                                        }else {
                                            return "<span style='color:red;'>"+row.value2+"</span>";
                                        }
                                    }
                                }
                            },
							{display: 'value3', name: 'value3', width: '5%', align: "center"},
							{display: 'value4', name: 'value4', width: '5%', align: "center"},
							{display: 'value5', name: 'value5', width: '5%', align: "center"},
@ -106,6 +247,7 @@
				reloadGrid: function (msg) {
					retrieve.$element.attrScan();
					var values = retrieve.$element.Fields.getValues();
                    values.indexType = retrieve.typeBox.getValue();
					reloadGrid.call(this, values);
				},
			};

+ 2 - 1
patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/patientDevice_list_js.jsp

@ -94,9 +94,10 @@
							{display: 'SIM码', name: 'sim', width: '5%', align: "left"},
                            {display: '社区', name: 'hospitalName', width: '10%', align: "left"},
                            {display: '医生', name: 'doctorName', width: '5%', align: "left"},
                            {display: '健管师', name: 'doctorHealthName', width: '5%', align: "left"},
							{display: '居民姓名', name: 'userName', width: '5%', align: "center"},
							{
								display: '绑定按键', name: 'userType', width: '10%', align: "center",
								display: '绑定按键', name: 'userType', width: '5%', align: "center",
								render: function (row) {
									if (row.userType == "-1") {
										return ""

+ 6 - 26
patient-co/patient-co-doctor-assistant/pom.xml

@ -84,10 +84,6 @@
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
@ -110,9 +106,15 @@
        <!-- spring start -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
@ -131,28 +133,6 @@
            <artifactId>spring-jms</artifactId>
        </dependency>
        <!-- spring end -->
        <!--activemq start-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-spring</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-jaas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-camel</artifactId>
        </dependency>
        <!--activemq end-->
        <!--Swagger start -->
        <dependency>
            <groupId>io.springfox</groupId>

+ 5 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/Application.java

@ -1,13 +1,18 @@
package com.yihu.wlyy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.context.ApplicationContext;
/**
 * Created by chenweida on 2017/7/28.
 */
@SpringBootApplication
@EnableAutoConfiguration(exclude = {
        RedisRepositoriesAutoConfiguration.class
})
public class Application {
    public static ApplicationContext ctx = null;

+ 3 - 1
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/MvcConfig.java

@ -7,7 +7,7 @@ import com.yihu.wlyy.interceptors.UserAgentFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@ -42,6 +42,8 @@ public class MvcConfig extends WebMvcConfigurerAdapter {
        logger.info("init doctorInterceptor,patientInterceptor");
    }
    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();

+ 1 - 1
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/war/ServletInitializer.java

@ -2,7 +2,7 @@ package com.yihu.wlyy.config.war;//package com.yihu.wlyy.config.war;
import com.yihu.wlyy.Application;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
 * Created by Administrator on 2016.10.14.

+ 9 - 0
patient-co/patient-co-figure-label/pom.xml

@ -78,5 +78,14 @@
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-data-es-starter</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
    </dependencies>
</project>

+ 8 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/FigureLabelApplication.java

@ -8,17 +8,23 @@ import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDa
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
 * Created by chenweida on 2018/3/5.
 */
@SpringBootApplication
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager")
@EnableAutoConfiguration(exclude = {
        ElasticsearchAutoConfiguration.class,
//        ElasticsearchAutoConfiguration.class,
        ElasticsearchRepositoriesAutoConfiguration.class,
        ElasticsearchDataAutoConfiguration.class,
//        ElasticsearchDataAutoConfiguration.class,
        RedisRepositoriesAutoConfiguration.class
})
@ComponentScan({"com.yihu.wlyy"})
public class FigureLabelApplication {
    public static ApplicationContext ctx = null;

+ 2 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/config/db/WlyyJpa.java

@ -31,7 +31,7 @@ import java.util.Properties;
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager",
        basePackages = {"com.yihu.wlyy.repository"})   //设置Repository所在位置
        basePackages = {"com.yihu.wlyy.figure.label.dao"})   //设置Repository所在位置
public class WlyyJpa {
    @Autowired
@ -84,7 +84,7 @@ public class WlyyJpa {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.wlyy.entity");
        emfb.setPackagesToScan("com.yihu.figure_label.entity");
        emfb.setPersistenceUnitName("wlyy");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);

+ 445 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/BaseController.java

@ -0,0 +1,445 @@
package com.yihu.wlyy.figure.label.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.IdEntity;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	protected HttpServletRequest request;
	public String getOpenid() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("openid");
			
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 获取用户ID
	 * @return
	 */
	public long getId() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getLong("id");
		} catch (Exception e) {
			return 0;
		}
	}
	public String getIMEI() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("imei");
		} catch (Exception e) {
			return null;
		}
	}
	
	public String getToken() {
		try {
			String userAgent = request.getHeader("userAgent");
			if(StringUtils.isEmpty(userAgent)){
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("token");
		} catch (Exception e) {
			return null;
		}
	}
	public void error(Exception e) {
		logger.error(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	public void warn(Exception e) {
		logger.warn(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	/**
	 * 返回接口处理结果
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String error(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 接口处理成功
	 * @param msg
	 * @return
	 */
	public String success(String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", 200);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, List<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, list);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONObject value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param total 总数
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, int total, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put("total", total);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Object value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			// 是否为第一页
			map.put("isFirst", list.isFirst());
			// 是否为最后一页
			map.put("isLast", list.isLast());
			// 总条数
			map.put("total", list.getTotalElements());
			// 总页数
			map.put("totalPages", list.getTotalPages());
			map.put(key, list.getContent());
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 *
	 *
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", page.isFirst());
			// 是否为最后一页
			json.put("isLast", page.isLast());
			// 总条数
			json.put("total", page.getTotalElements());
			// 总页数
			json.put("totalPages", page.getTotalPages());
			json.put(key, array);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Map<?, ?> value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, String value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, IdEntity entity) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, entity);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", isFirst);
			// 是否为最后一页
			json.put("isLast", isLast);
			// 总条数
			json.put("total", total);
			// 总页数
			json.put("totalPages", totalPages);
			json.put(key, values);
			return json.toString();
		} catch (Exception e) {
			logger.error("BaseController:", e.getMessage());
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	public String trimEnd(String param, String trimChars) {
		if (param.endsWith(trimChars)) {
			param = param.substring(0, param.length() - trimChars.length());
		}
		return param;
	}
	/**
	 * 无效用户消息返回
	 * @param e
	 * @param defaultCode
	 * @param defaultMsg
	 * @return
	 */
	public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
		try {
			// if (e instanceof UndeclaredThrowableException) {
			// UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
			// InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
			// if (iue != null) {
			// return error(iue.getCode(), iue.getMsg());
			// }
			// }
			return error(defaultCode, defaultMsg);
		} catch (Exception e2) {
			return null;
		}
	}
}

+ 231 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/JobController.java

@ -0,0 +1,231 @@
package com.yihu.wlyy.figure.label.controller;
import com.yihu.wlyy.figure.label.service.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * 启动job
 */
@RestController
@RequestMapping(value = "/job", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "定时任务控制器")
public class JobController extends BaseController{
    private Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private JobService jobService;
    /**
     * 启动任务
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID立即单个任务")
    @RequestMapping(value = "startNowById", method = RequestMethod.GET)
    public String startNowById(
            @ApiParam(name = "id", value = "任务ID", required = true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startNowById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的全部的数据")
    @RequestMapping(value = "productDataByOneDay", method = RequestMethod.GET)
    public String productDataByOneDay( @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day) {
        try {
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的增量数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的增量数据(包含头尾)")
    @RequestMapping(value = "productDataByDayToDayAndId", method = RequestMethod.GET)
    public String productDataByDayToDayAndId( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                              @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end,
                                              @ApiParam(name = "ids", value = "任务ids多个逗号分割")@RequestParam(value = "ids", required = true)String ids) {
        try {
            jobService.productDataByDayToDayAndId(start,end,ids);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天增量数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天增量数据")
    @RequestMapping(value = "productDataByOneDayWithId", method = RequestMethod.GET)
    public String productDataByOneDayWithId(
            @ApiParam(name = "day", value = "yyyy-MM-dd")@RequestParam(value = "day", required = true)String day,
            @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去到现在的全部的数据
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去到现在的全部的数据")
    @RequestMapping(value = "productDataByDayAndId", method = RequestMethod.GET)
    public String productDataByDayAndId(
            @ApiParam(name = "day", value = "距离今天的天数(如果是要生成昨天的数据,day=1)")@RequestParam(value = "day", required = true) int day,
            @ApiParam(name="id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "启动单个任务")
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(
            @ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true) String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止任务
     *
     * @param id id
     * @return
     */
    @ApiOperation(value = "停止单个任务")
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(@ApiParam(name="id",value="任务id",required=true)@RequestParam(value = "id", required = true)String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止所有任务
     *
     * @return
     */
    @ApiOperation(value = "停止所有任务")
    @RequestMapping(value = "stopAll", method = RequestMethod.GET)
    public String stopAll() {
        try {
            jobService.stopAll();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动所有任务
     *
     * @return
     */
    @ApiOperation(value = "启动所有任务")
    @RequestMapping(value = "startAll", method = RequestMethod.GET)
    public String startAll() {
        try {
            jobService.startAll();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "清除緩存")
    @RequestMapping(value = "cleanCache", method = RequestMethod.GET)
    public String cleanCache() {
        try {
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的某个指标的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的某个指标的数据(包含头尾)没有休眠时间")
    @RequestMapping(value = "productDataByDayToDayAndIdNoSleep", method = RequestMethod.GET)
    public String productDataByDayToDayAndIdNoSleep( @ApiParam(name = "start", value = "yyyy-MM-dd")@RequestParam(value = "start", required = true)String start,
                                                     @ApiParam(name = "end", value = "yyyy-MM-dd")@RequestParam(value = "end", required = true)String end,
                                                     @ApiParam(name = "id", value = "任务id")@RequestParam(value = "id", required = true)String id,
                                                     @ApiParam(name = "sleepTime", value = "任务间隔时间(秒)")@RequestParam(value = "sleepTime", required = true)Long sleepTime) {
        try {
            jobService.productDataByDayToDayAndIdNoSleep(start,end,id,sleepTime);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 65 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/AgeConvert.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
@Component
public class AgeConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        if(CollectionUtils.isEmpty(flLabelDictList)){
            return saveModels;
        }
        FLlabelDict one = flLabelDictList.get(0);
        Map<String,String> map = new HashMap<>();
        flLabelDictList.forEach(
                fLlabelDict -> {
                    map.put(fLlabelDict.getLabelCode(),fLlabelDict.getLabelName());
                }
        );
        models.forEach(
                model -> {
                    int age = IdCardUtil.getAgeForIdcard(model.getIdcard());
                    String labelCode = getAgeLabelCode(age);
                    SaveModel saveModel = new SaveModel();
                    saveModel.setLabelType(one.getParentCode());
                    saveModel.setLabelCode(labelCode);
                    saveModel.setLabeName(map.get(labelCode));
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
    /**
     * fl_label_dict配置的code
     * @param age
     * @return
     */
    public String getAgeLabelCode(int age) {
        if (age <= 6) {
            return "10";
        }else if(age <=18){
            return "11";
        }else if(age <=30){
            return "12";
        }else if(age <=50){
            return "13";
        }else if(age <=65){
            return "14";
        }else{
            return "15";
        }
    }
}

+ 43 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/BirthConvert.java

@ -0,0 +1,43 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BirthConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        if(CollectionUtils.isEmpty(flLabelDictList)){
            return saveModels;
        }
        FLlabelDict fLlabelDict = flLabelDictList.get(0);
        models.forEach(
                model -> {
                    String birth = null;
                    try {
                        birth  = IdCardUtil.getBirthdayForIdcard(model.getIdcard());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SaveModel saveModel = new SaveModel();
                    saveModel.setIdcard(model.getIdcard());
                    saveModel.setLabelCode(fLlabelDict.getLabelCode());
                    saveModel.setLabelType(fLlabelDict.getParentCode());
                    saveModel.setLabeName(fLlabelDict.getLabelName());
                    saveModel.setLabelValue(birth);
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 4 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/Convert.java

@ -1,6 +1,8 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
@ -11,5 +13,5 @@ import java.util.List;
 */
public interface Convert {
    List<SaveModel> convert(List<ExtractModel> extractModels);
    List<SaveModel> convert(List<DataModel> modelList,List<FLlabelDict> flLabelDictList);
}

+ 98 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/ConvertHelper.java

@ -0,0 +1,98 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2017/6/5.
 * 维度的key值转换器
 */
@Component
@Scope("prototype")
public class ConvertHelper {
    private Logger logger = LoggerFactory.getLogger(ConvertHelper.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FLLabelDictDao flLabelDictDao;
    /**
     * 进行具体标签生成转换
     * @return
     * @throws Exception
     */
    public List<SaveModel> convert(List<DataModel> dataModels, FLlabelDictJob fLlabelDictJob) throws Exception {
        List<SaveModel> saveModels = new ArrayList<>();
            //不需要转换
            if(StringUtils.isEmpty(fLlabelDictJob.getConvertClazz()) || StringUtils.isEmpty(fLlabelDictJob.getSql())){
                return generateSaveModleWithOutConvert(dataModels);
            }
            List<FLlabelDict> flLabelDictList = jdbcTemplate.query(fLlabelDictJob.getSql(),new BeanPropertyRowMapper(FLlabelDict.class));
            try {
                Object obj = Class.forName(fLlabelDictJob.getConvertClazz()).newInstance();
                Method method = obj.getClass().getMethod("convert",List.class,List.class);
                saveModels = (List<SaveModel>)method.invoke(obj,dataModels,flLabelDictList);
            } catch (Exception e) {
                logger.error("customized class or convert(List<DataModel> modelList,List<FLlabelDict> flLabelDictList) method not found:" + fLlabelDictJob.getConvertClazz());
                return saveModels;
            }
        return saveModels;
    }
    public List<SaveModel> generateSaveModleWithOutConvert(List<DataModel> dataModels){
        List<SaveModel> saveModels = new ArrayList<>();
        dataModels.forEach(
                dataModel -> {
                    SaveModel saveModel = new SaveModel();
                    saveModel.setIdcard(dataModel.getIdcard());
                    saveModel.setLabelType(dataModel.getParentCode());
                    saveModel.setLabelCode(dataModel.getLabelCode());
                    saveModel.setLabeName(dataModel.getLabelName());
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 14 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/HealthConditionConvert.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
public class HealthConditionConvert implements Convert {
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        return null;
    }
}

+ 36 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/SexConvert.java

@ -0,0 +1,36 @@
package com.yihu.wlyy.figure.label.convert;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.*;
public class SexConvert implements Convert{
    @Override
    public List<SaveModel> convert(List<DataModel> models,List<FLlabelDict> flLabelDictList) {
        List<SaveModel> saveModels = new ArrayList<>();
        FLlabelDict one = flLabelDictList.get(0);
        Map<String,String> map = new HashMap<>();
        flLabelDictList.forEach(
                fLlabelDict -> {
                    map.put(fLlabelDict.getLabelCode(),fLlabelDict.getLabelName());
                }
        );
        models.forEach(
                model -> {
                    String sex = IdCardUtil.getSexForIdcard(model.getIdcard());
                    SaveModel saveModel = new SaveModel();
                    saveModel.setLabelType(one.getParentCode());
                    saveModel.setLabelCode(sex);
                    saveModel.setLabeName(map.get(sex));
                    saveModel.setCreateTime(DateFormatUtils.format(new Date(), ConstantUtil.date_format));
                    saveModels.add(saveModel);
                }
        );
        return saveModels;
    }
}

+ 66 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLJobConfigDao.java

@ -0,0 +1,66 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLJobConfigDao extends PagingAndSortingRepository<FLJobConfig, String>, JpaSpecificationExecutor<FLJobConfig> {
    /**
     * 根据id和状态查询job配置
     * @param id
     * @param status
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.id=?1 and a.status=?2 and a.del='1'")
    FLJobConfig findByIdAndStatus(Long id, String status);
    /**
     * 查询所有的job配置
     * @param status
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.status=?1 and a.del='1'")
    List<FLJobConfig> findByAll(String status);
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Query(" FROM FLJobConfig a WHERE a.id=?1 and a.del='1'")
    FLJobConfig findById(Long id);
    /**
     * 更新job的状态(状态为启动或停止)
     * @param id
     * @param status
     * @return
     */
    @Modifying
    @Query(" update FLJobConfig a set a.status=?2 where a.id=?1 ")
    int updateStatus(Long id, String status);
    /**
     * 删除job(0 正常 1 删除)
     * @param id
     * @return
     */
    @Modifying
    @Query(" update FLJobConfig a set a.del = 1 where a.id=?1 ")
    int deleteJob(Long id);
    /**
     * 更新job的状态(状态为启动或停止)
     * @param id
     * @param value
     * @return
     */
    @Modifying
    @Query(" update FLJobConfig a set a.sqlFieldValue=?2 where a.id=?1 ")
    int updateSqlFildeValue(Long id, String value);
}

+ 29 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictDao.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLlabelDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLLabelDictDao extends PagingAndSortingRepository<FLlabelDict, String>, JpaSpecificationExecutor<FLlabelDict> {
    /**
     * 根据父类标签查询字典信息
     * @param parentCode
     * @return
     */
    @Query(" FROM FLlabelDict a WHERE a.parentCode=?1")
    FLlabelDict findByParentCode(String parentCode);
    /**
     * 根据父类code和标签code查询标签字典信息
     * @param parentCode
     * @param labelCode
     * @return
     */
    @Query(" FROM FLlabelDict a WHERE a.parentCode=?1 and labelCode = ?2")
    FLlabelDict findByParentCodeAndLabelCode(String parentCode,String labelCode);
}

+ 29 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictJobDao.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.figure.label.dao;
import com.yihu.figure_label.entity.FLlabelDictJob;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FLLabelDictJobDao extends PagingAndSortingRepository<FLlabelDictJob, String>, JpaSpecificationExecutor<FLlabelDictJob> {
    /**
     * 根据jobId查询
     * @param jobId
     * @return
     */
    @Query(" FROM FLlabelDictJob a WHERE a.jobId=?1")
    FLlabelDictJob findByJobId(Long jobId);
    /**
     * 根据标签类型查询
     * @param type
     * @return
     */
    @Query(" FROM FLlabelDictJob a WHERE a.labelType=?1")
    FLlabelDictJob findByLabelType(String type);
}

+ 7 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/Extracter.java

@ -1,6 +1,7 @@
package com.yihu.wlyy.figure.label.extract;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.model.DataModel;
import java.util.List;
@ -14,5 +15,9 @@ public interface Extracter {
     *
     * @return
     */
    List<ExtractModel> extract();
//    List<ExtractModel> extract();
    List<DataModel> extractDataByJobConfigsql(String sql);
}

+ 22 - 2
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/MysqlExtracter.java

@ -1,6 +1,12 @@
package com.yihu.wlyy.figure.label.extract;
import com.yihu.wlyy.figure.label.model.ExtractModel;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.model.DataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@ -10,8 +16,22 @@ import java.util.List;
 */
@Component
public class MysqlExtracter implements Extracter {
    @Override
    private Logger logger = LoggerFactory.getLogger(MysqlExtracter.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
   /* @Override
    public List<ExtractModel> extract() {
        return null;
    }*/
    @Override
    public List<DataModel> extractDataByJobConfigsql(String sql) {
        List<DataModel> datas = jdbcTemplate.query(sql,new BeanPropertyRowMapper(DataModel.class));
        logger.info("job get data counts:" + datas.size());
        return datas;
    }
}

+ 143 - 7
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/job/Mysql2ESJob.java

@ -1,11 +1,30 @@
package com.yihu.wlyy.figure.label.job;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.yihu.figure_label.entity.FLJobConfig;
import com.yihu.figure_label.entity.FLlabelDict;
import com.yihu.figure_label.entity.FLlabelDictJob;
import com.yihu.wlyy.figure.label.controller.JobController;
import com.yihu.wlyy.figure.label.convert.ConvertHelper;
import com.yihu.wlyy.figure.label.dao.FLJobConfigDao;
import com.yihu.wlyy.figure.label.dao.FLLabelDictDao;
import com.yihu.wlyy.figure.label.dao.FLLabelDictJobDao;
import com.yihu.wlyy.figure.label.extract.MysqlExtracter;
import com.yihu.wlyy.figure.label.model.DataModel;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.storage.Store2ES;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2018/3/7.
@ -14,15 +33,132 @@ import org.springframework.stereotype.Component;
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中,但是这时有空闲的线程,那么马上又会执行,这样一来就会存在同一job被并行执行
public class Mysql2ESJob implements Job {
    private Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private FLJobConfigDao flJobConfigDao;
    @Autowired
    private FLLabelDictJobDao flLabelDictJobDao;
    @Autowired
    private MysqlExtracter mysqlExtracter;
    @Autowired
    private ConvertHelper convertHelper;
    @Autowired
    Store2ES store2ES;
    private FLJobConfig flJobConfig;
    private Long flJobConfigId;
    private String sqlFiledValue;
    private String sqlFiledCondition;
    private String finalSql;
    private List<DataModel> dataModelList;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap paramsMap = context.getJobDetail().getJobDataMap();
        initParams(paramsMap);
        //根据obconfig里配置的sql提取数据
        extract();
        //数据转换
        List<SaveModel> list = new ArrayList<>();
        list = convert();
        //数据保存
        boolean bool = save(list);
        //增量存储成功后,修改增量的czrq时间为当前时间
        if (bool) {
            this.flJobConfigDao.updateSqlFildeValue(this.flJobConfigId, DateFormatUtils.format(new Date(), ConstantUtil.date_format));
        }
    }
    public void initParams(JobDataMap paramsMap){
        this.flJobConfigId = (Long)paramsMap.get("jobConfig");
        this.flJobConfig = flJobConfigDao.findById(this.flJobConfigId);
        this.sqlFiledValue = (String)paramsMap.get(this.flJobConfig.getSqlField().toString());
        //没有传增量值,以数据库配置的默认值为查询条件
        if(StringUtils.isEmpty(this.sqlFiledValue)){
            this.sqlFiledValue = this.flJobConfig.getSqlFieldValue();
        }
        this.sqlFiledCondition = paramsMap.getString("sqlFiledCondition");
        //1抽取数据
        String sql = this.flJobConfig.getSql();
        String sqlFiled = this.flJobConfig.getSqlField();
        this.finalSql = getJobConfigSql(sql,sqlFiled,sqlFiledCondition,sqlFiledValue);
    }
        //1.1数据转换
        // 如果表fl_label_dict_job中有配置convert_clazz就进行数据转换获取标签
    /**
     * 提取数据,按数据库中配置的增量条件提取
     */
    public void extract(){
        this.dataModelList = mysqlExtracter.extractDataByJobConfigsql(this.finalSql);
    }
    /**
     * 转换
     */
    public List<SaveModel> convert(){
        List<SaveModel> list = new ArrayList<>();
        FLlabelDictJob fLlabelDictJob = flLabelDictJobDao.findByJobId(this.flJobConfigId);
        try {
            list = convertHelper.convert(this.dataModelList, fLlabelDictJob);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return list;
    }
        //2数据保存
    /**
     * 保存
     * @param list
     */
    public boolean save(List<SaveModel> list){
        boolean bool = true;
        try {
            store2ES.save(list);
        }catch (Exception e){
            logger.error("save to elasticsearch failed,convet data count:" + list.size());
            bool = false;
        }
        return bool;
    }
    /**
     * 拼凑获取增量数据的sql
     * @param sql
     * @param sqlFiledValue
     * @return
     */
    public String getJobConfigSql(String sql,String sqlFiled,String sqlFiledCondition,String sqlFiledValue){
        StringBuilder result = new StringBuilder();
        result.append(sql).append(" ");
        if(StringUtils.isEmpty(sqlFiledCondition)){
            return result.toString();
        }
        if (sqlFiledValue.contains(",") && sql.contains("where")) {
            String[] sqlFiledValues = sqlFiledValue.split(",");
            result.append("and ").append(sqlFiled).append(sqlFiledCondition).append("\'"+sqlFiledValues[1]+"\'").append(sqlFiledCondition).append("\'"+sqlFiledValues[0]+"\'");
        }else if(sql.contains("where")){
            result.append("and ").append(sqlFiled).append(sqlFiledCondition).append("\'"+sqlFiledValue+"\'");
        }else {
            result.append("where ").append(sqlFiled).append(sqlFiledCondition).append("\'"+sqlFiledValue+"\'");
        }
        return result.toString();
    }
}

+ 80 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/DataModel.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.figure.label.model;
/**
 * jboConfig配置里sql查询出的数据
 */
public class DataModel {
    private String idcard;
    private String sex;
    private String parentCode;
    private String labelName;
    private String labelCode;
    private String convertClazz;
    private String jobId;
    private String patient;
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getParentCode() {
        return parentCode;
    }
    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
    public String getConvertClazz() {
        return convertClazz;
    }
    public void setConvertClazz(String convertClazz) {
        this.convertClazz = convertClazz;
    }
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
}

+ 0 - 31
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/ExtractModel.java

@ -1,31 +0,0 @@
package com.yihu.wlyy.figure.label.model;
/**
 * Created by chenweida on 2018/3/7.
 */
public class ExtractModel {
    /**
     *  身份证
     */
    private String idcard;
    /**
     * 数据
     */
    private String data;
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }
}

+ 30 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/SaveModel.java

@ -1,9 +1,15 @@
package com.yihu.wlyy.figure.label.model;
import io.searchbox.annotations.JestId;
/**
 * Created by chenweida on 2018/3/7.
 */
public class SaveModel {
    @JestId
    private String id;
    /**
     * 身份证
     */
@ -16,10 +22,17 @@ public class SaveModel {
     * 标签code
     */
    private String labelCode;
    /**
     * 标签名称
     */
    private String labeName;
    /**
     * 标签值,仅当标签只有一个分类的时候才有此值,比如生日,体重等
     */
    private String labelValue;
    /**
     * 创建时间
     */
@ -37,6 +50,15 @@ public class SaveModel {
        return labelType;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
@ -57,6 +79,14 @@ public class SaveModel {
        this.labeName = labeName;
    }
    public String getLabelValue() {
        return labelValue;
    }
    public void setLabelValue(String labelValue) {
        this.labelValue = labelValue;
    }
    public String getCreateTime() {
        return createTime;
    }

+ 5 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/ExtractService.java

@ -0,0 +1,5 @@
package com.yihu.wlyy.figure.label.service;
public class ExtractService {
}

+ 390 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/JobService.java

@ -0,0 +1,390 @@
package com.yihu.wlyy.figure.label.service;
import com.yihu.figure_label.entity.FLJobConfig;
import com.yihu.wlyy.figure.label.dao.FLJobConfigDao;
import com.yihu.wlyy.figure.label.util.IdCardUtil;
import com.yihu.wlyy.figure.label.util.QuartzHelpers;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class JobService {
    @Value("${JobService.sleepTime}")
    private Integer sleepTime;
    @Autowired
    private IdCardUtil idCardUtil;
    @Autowired
    private FLJobConfigDao flJobConfigDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private QuartzHelpers quartzHelpers;
    @Transactional
    public void stopById(String id) throws Exception {
        FLJobConfig flJobConfig = flJobConfigDao.findByIdAndStatus(Long.valueOf(id), "1");
        if (flJobConfig != null) {
            for (int j = 1; j <= 2; j++) {
                quartzHelpers.removeJob(flJobConfig.getId() + "-" + j);
                flJobConfigDao.updateStatus(flJobConfig.getId(),"0") ;;
            }
        } else {
            throw new Exception("任务已经停止");
        }
    }
    @Transactional
    public void startById(String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findByIdAndStatus(Long.valueOf(id), "0");
        if (FLJobConfig != null) {
            startOneJob(FLJobConfig);
        } else {
            throw new Exception("任务已经启动");
        }
    }
    @Transactional
    public void stopAll() throws Exception {
        List<FLJobConfig> FLJobConfigs = flJobConfigDao.findByAll("1");
        if (FLJobConfigs != null && FLJobConfigs.size() > 0) {
            for (FLJobConfig FLJobConfig : FLJobConfigs) {
                for (int j = 1; j <= 2; j++) {
                    quartzHelpers.removeJob(FLJobConfig.getId() + "-" + j);
                    flJobConfigDao.updateStatus(FLJobConfig.getId(),"0") ;;
                }
            }
        } else {
            throw new Exception("任务已经全部停止");
        }
    }
    @Transactional
    public void startAll() throws Exception {
        List<FLJobConfig> FLJobConfigs = flJobConfigDao.findByAll("0");
        if (FLJobConfigs != null && FLJobConfigs.size() > 0) {
            for (FLJobConfig FLJobConfig : FLJobConfigs) {
                startOneJob(FLJobConfig);
            }
        } else {
            throw new Exception("任务已经全部启动");
        }
    }
    /**
     * 启动单个任务
     *
     * @param FLJobConfig
     * @throws Exception
     */
    @Transactional
    public void startOneJob(FLJobConfig FLJobConfig) throws Exception {
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("jobConfig", flJobConfigVO.getId());
        //表里设置的增量查询类型和增量查询初始值,如果值没有配置,以当前时间为准
        if(!StringUtils.isEmpty(flJobConfigVO.getSqlFieldValue())){
            params.put(flJobConfigVO.getSqlField(),flJobConfigVO.getSqlFieldValue());
        }else{
            params.put(flJobConfigVO.getSqlField(), DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }
        params.put("sqlFiledCondition", ">");
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            //往quartz框架添加任务
            quartzHelpers.addJob(getRightClass(FLJobConfig), FLJobConfig.getQuartzCron(), FLJobConfig.getId().toString(), params);
            flJobConfigDao.updateStatus(FLJobConfig.getId(), "1");//设置任务状态是启动 }
        }
    }
    public void startNowById(String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findOne(id);
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<>();
        params.put("jobConfig", flJobConfigVO.getId());
        if(!StringUtils.isEmpty(flJobConfigVO.getSqlFieldValue())){
            params.put(flJobConfigVO.getSqlField(),flJobConfigVO.getSqlFieldValue());
        }else{
            params.put(flJobConfigVO.getSqlField(), DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }
        params.put("sqlFiledCondition", ">");
        //往quartz框架添加任务
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            Thread.sleep(sleepTime);
        }
    }
    public static String getYesterday(Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public void productDataByOneDay(String yesterday) throws Exception {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<FLJobConfig> FLJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(FLJobConfig.class));
        for (FLJobConfig FLJobConfig : FLJobConfigs) {
            FLJobConfig flJobConfig = new FLJobConfig();
            BeanUtils.copyProperties(FLJobConfig, flJobConfig);
            Map<String, Object> params = new HashMap<>();
            params.put("jobConfig", flJobConfig.getId().toString());
            //往quartz框架添加任务
            params.put("sqlFiledValue", daybefore+","+yesterday);
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                Thread.sleep(sleepTime);
            }
        }
    }
    /**
     * @param FLJobConfig
     * @return
     * @throws ClassNotFoundException
     */
    private Class getRightClass(FLJobConfig FLJobConfig) throws ClassNotFoundException {
        return Class.forName(FLJobConfig.getJobClass());
    }
    public void productDataByOneDayWithId(String yesterday, String id) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        FLJobConfig FLJobConfig = flJobConfigDao.findById(Long.valueOf(id));
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        //往quartz框架添加任务
        params.put("sqlFiledValue", daybefore + "," + yesterday);
        params.put("sqlFiledCondition", "<");
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            Thread.sleep(sleepTime);
        }
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception {
        FLJobConfig FLJobConfig = flJobConfigDao.findById(Long.valueOf(id));
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        for (int i = 1; i <= day; i++) {
            //往quartz框架添加任务
            params.put("sqlFiledValue",  getYesterday(0 - i - 1)+","+getYesterday(0 - i));
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                Thread.sleep(sleepTime);
            }
        }
    }
    public void productDataByDayToDay(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDay(getYesterday(i, startDate));
        }
    }
    public static String getYesterday(Integer day, Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.add(Calendar.DAY_OF_MONTH, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    public void productDataByDayToDayAndId(String start, String end, String ids) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        String [] idStr=ids.split(",");
        for (int i = 0; i < day; i++) {
            for(String id:idStr){
                productDataByOneDayWithId(getYesterday(i, startDate), id);
            }
        }
    }
    //================================================没有休眠时间=============================================================
    public void productDataByDayToDayAndIdNoSleep(String start, String end, String id,Long sleepTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
        if (startDate.after(endDate)) {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            productDataByOneDayWithIdNoSleep(getYesterday(i, startDate), id,sleepTime);
        }
    }
    public void productDataByOneDayWithIdNoSleep(String yesterday, String id,Long sleepTime) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        FLJobConfig FLJobConfig = flJobConfigDao.findById(Long.valueOf(id));
        if (FLJobConfig == null) {
            throw new Exception("id不存在");
        }
        FLJobConfig flJobConfigVO = new FLJobConfig();
        BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
        Map<String, Object> params = new HashMap<>();
        params.put("jobConfig", flJobConfigVO.getId().toString());
        //往quartz框架添加任务
        params.put("sqlFiledValue", daybefore + "," + yesterday);
        params.put("sqlFiledCondition", "<");
        if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
            quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
        }
        Thread.sleep(sleepTime * 1000L);
    }
    public void productDataByOneDayNoSleep(String yesterday,Long sleepTime) throws Exception {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<FLJobConfig> FLJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(FLJobConfig.class));
        for (FLJobConfig FLJobConfig : FLJobConfigs) {
            FLJobConfig flJobConfigVO = new FLJobConfig();
            BeanUtils.copyProperties(FLJobConfig, flJobConfigVO);
            Map<String, Object> params = new HashMap<>();
            params.put("jobConfig", flJobConfigVO.getId().toString());
            //往quartz框架添加任务
            params.put("sqlFiledValue", daybefore + "," + yesterday);
            params.put("sqlFiledCondition", "<");
            if (!StringUtils.isEmpty(FLJobConfig.getJobClass())) {
                quartzHelpers.startNow(getRightClass(FLJobConfig), FLJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            }
            Thread.sleep(sleepTime * 1000L);
        }
    }
   /* public void startCleanCacheJob() throws Exception {
        if (!quartzHelper.isExistJob(CacheCleanJob.jobKey)) {
            quartzHelper.addJob(CacheCleanJob.class, CacheCleanJob.cron, CacheCleanJob.jobKey, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopCleanCacheJob() throws Exception {
        if (quartzHelper.isExistJob(CacheCleanJob.jobKey)) {
            quartzHelper.removeJob(CacheCleanJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }*/
}

+ 37 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2ES.java

@ -0,0 +1,37 @@
package com.yihu.wlyy.figure.label.storage;
import com.yihu.base.es.config.ElastricSearchHelper;
import com.yihu.wlyy.figure.label.model.SaveModel;
import com.yihu.wlyy.figure.label.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class Store2ES implements Storager {
    @Autowired
    private ElastricSearchHelper elastricSearchHelper;
    @Override
    public void save(List<SaveModel> modelList) {
        List<Object> list = new ArrayList<>();
        int saveCount = 0;
        for(SaveModel saveModel:modelList){
            list.add(saveModel);
            //防止内存溢出,一次性存储10W条
            if(list.size() >= 100000){
                elastricSearchHelper.save(ConstantUtil.figure_label_es_index, ConstantUtil.figure_label_es_type, list);
                list.clear();
                saveCount ++;
            }else if(modelList.size() - saveCount * 100000 == list.size()){
                //剩余的零头
                elastricSearchHelper.save(ConstantUtil.figure_label_es_index, ConstantUtil.figure_label_es_type, list);
            }
        }
    }
}

+ 12 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2Hbase.java

@ -0,0 +1,12 @@
package com.yihu.wlyy.figure.label.storage;
import com.yihu.wlyy.figure.label.model.SaveModel;
import java.util.List;
public class Store2Hbase implements Storager {
    @Override
    public void save(List<SaveModel> modelList) {
    }
}

+ 7 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/ConstantUtil.java

@ -0,0 +1,7 @@
package com.yihu.wlyy.figure.label.util;
public class ConstantUtil {
    public static final String figure_label_es_index = "figure_label_index";
    public static final String figure_label_es_type = "figure_label_type";
    public static final String date_format = "yyyy-MM-dd HH:mm:ss";
}

+ 124 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/IdCardUtil.java

@ -0,0 +1,124 @@
package com.yihu.wlyy.figure.label.util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.Calendar;
/***
 * 根据居民身份证提取相对应的信息
 */
@Component
public class IdCardUtil {
    /**
     * 根据身份证的号码算出当前身份证持有者的性别
     * 1 女 2 男 3未知
     *
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard(String idCard){
        if(StringUtils.isEmpty(idCard)){
            return "未知";
        }
        try {
            String sex = "2";
            if (idCard.length() == 18) {
                if (Integer.parseInt(idCard.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                    sex = "1";
                } else {
                    sex = "2";
                }
            } else if (idCard.length() == 15) {
                String usex = idCard.substring(14, 15);// 用户的性别
                if (Integer.parseInt(usex) % 2 == 0) {
                    sex = "1";
                } else {
                    sex = "2";
                }
            }
            return sex;
        } catch (Exception e) {
            return "1";
        }
    }
    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @param
     * @throws Exception
     */
    public static int getAgeForIdcard(String idCard) {
        int age = 0;
        if(StringUtils.isEmpty(idCard)){
            return age;
        }
        try {
            if (org.springframework.util.StringUtils.isEmpty(idCard)) {
                return age;
            }
            String birth = "";
            if (idCard.length() == 18) {
                birth = idCard.substring(6, 14);
            } else if (idCard.length() == 15) {
                birth = "19" + idCard.substring(6, 12);
            } else {
                return age;
            }
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4, 6));
            int day = Integer.valueOf(birth.substring(6));
            Calendar cal = Calendar.getInstance();
            age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
                age--;
            }
            return age;
        } catch (Exception e) {
            return 0;
        }
    }
    /**
     * 身份证提取出身日期
     * @param idCard
     * @return
     * @throws Exception
     */
    public static String getBirthdayForIdcard(String idCard) throws Exception {
        if(StringUtils.isEmpty(idCard)){
            return "";
        }
        String year = "";
        String month = "";
        String day = "";
        if (idCard.length() == 18) {
            year = idCard.substring(6,10);
            month = idCard.substring(10,12);
            day = idCard.substring(12,14);
        } else if (idCard.length() == 15) {
            year = "19" + idCard.substring(6,8);
            month = idCard.substring(8,10);
            day = idCard.substring(10,12);
        }
        StringBuilder birthday = new StringBuilder();
        birthday.append(year).append("-");
        birthday.append(month).append("-");
        birthday.append(day);
        return birthday.toString();
    }
    public static void main(String args[]) throws Exception {
        System.out.println(getBirthdayForIdcard("411321198004273615"));
        System.out.println(getBirthdayForIdcard("440253850213582"));
//        System.out.println(getSexForIdcard("411321198004273615"));
//        System.out.println(getAgeForIdcard("411321198004273615"));
    }
}

+ 121 - 0
patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/QuartzHelpers.java

@ -0,0 +1,121 @@
package com.yihu.wlyy.figure.label.util;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@Component
public class QuartzHelpers {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private Scheduler scheduler = null;
    @PostConstruct
    public void init() {
        try {
//            SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
            scheduler = schedulerFactoryBean.getScheduler();
            scheduler.clear();
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public void addJob(Class jobClass, String cronString, String jobKey,
                       Map<String, Object> params) throws Exception {
        if (!CronExpression.isValidExpression(cronString)) {
            throw new Exception("cronExpression is not a valid Expression");
        }
        try {
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity("job-id:" + jobKey, "job-group:" + jobKey)
                    .build();
            JobDataMap jobDataMap = job.getJobDataMap();
            jobDataMap.putAll(params);
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("trigger-name:" + jobKey, "trigger-group:" + jobKey)
                    .withSchedule(
                            CronScheduleBuilder
                                    .cronSchedule(cronString)
                                    //——以错过的第一个频率时间立刻开始执行
                                    //——重做错过的所有频率周期后
                                    //——当下一次触发频率发生时间大于当前时间后,再按照正常的Cron频率依次执行
                                    .withMisfireHandlingInstructionIgnoreMisfires()
                    )
                    .build();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public void removeJob(String jobKeyString) throws Exception {
        TriggerKey triggerKey = new TriggerKey("trigger-name:" + jobKeyString, "trigger-group:" + jobKeyString);
        JobKey jobName = new JobKey("job-id:" + jobKeyString, "job-group:" + jobKeyString);
        scheduler.pauseTrigger(triggerKey);// 停止触发器
        scheduler.unscheduleJob(triggerKey);// 移除触发器
        scheduler.deleteJob(jobName);// 删除任务
    }
    public boolean isExistJob(String jobKey) throws SchedulerException {
        JobKey jk = new JobKey("job-id:" + jobKey, "job-group:" + jobKey);
        if (scheduler.checkExists(jk)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 立即执行任务。
     *
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startNow(Class jobClass, String id, Map<String, Object> params) throws Exception {
        startAt(new Date(), jobClass, id, params);
    }
    /**
     * 在指定时间点执行。
     *
     * @param time
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startAt(Date time, Class jobClass, String id, Map<String, Object> params) throws Exception {
        JobDetail job = JobBuilder.newJob(jobClass).withIdentity("job-id:" + id, "job-group:" + id).build();
        JobDataMap jobDataMap = job.getJobDataMap();
        if (null != params) jobDataMap.putAll(params);
        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger-id:" + id, "trigger-group:" + id)
                .startAt(time)
                .withSchedule(
                        simpleSchedule()
                                .withIntervalInSeconds(10)
                                .withRepeatCount(0)
                                .withMisfireHandlingInstructionIgnoreMisfires()
                )
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }
}

+ 17 - 5
patient-co/patient-co-figure-label/src/main/resources/application-dev.yml

@ -3,12 +3,24 @@ spring:
  profiles: dev
  datasource:
#    wlyy:
#      url: jdbc:mysql://172.19.103.85/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
#      username: linzhou
#      password: linzhou
    wlyy:
      url: jdbc:mysql://172.19.103.85/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: linzhou
      password: linzhou
      url: jdbc:mysql://172.19.103.77/figure_lable?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: root
      password: 123456
  data:
    elasticsearch:
      cluster-nodes-jest: http://172.19.103.45:9200,http://172.19.103.68:9200  #多个逗号分割
      repositories:
        enabled: true
quartz:
  namespace: patient-co-figure-label ##quartz的命名空间,名称一样实现消费负载
  overwriteExistingJobs: false ##是否覆盖job
  overwriteExistingJobs: false ##是否覆盖job
JobService:
  sleepTime: 40000

+ 1 - 1
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java

@ -84,7 +84,7 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
            //同步智业字典 每晚1点同步
            if (!quartzHelper.isExistJob("zy_dict_job")) {
                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("zy_dict_job");
               // quartzHelper.addJob(ZyDictJob.class, trigger, "zy_dict_job", new HashMap<String, Object>());
                quartzHelper.addJob(ZyDictJob.class, trigger, "zy_dict_job", new HashMap<String, Object>());
                logger.info("zy_dict_job job success");
            } else {
                logger.info("zy_dict_job job exist");

+ 9 - 2
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/PatientConfirmReceiptJob.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.physicalExamination.PatientPhysicalExaminationDao;
import com.yihu.wlyy.repository.prescription.PrescriptionDao;
import com.yihu.wlyy.service.app.physicalExamination.PatientPhysicalExaminationService;
import com.yihu.wlyy.service.app.prescription.PrescriptionLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
@ -54,6 +55,8 @@ public class PatientConfirmReceiptJob implements Job {
    private PatientPhysicalExaminationDao examinationDao;
    @Autowired
    private PatientPhysicalExaminationService examinationService;
    @Autowired
    private PrescriptionLogService payLogService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
@ -63,17 +66,20 @@ public class PatientConfirmReceiptJob implements Job {
            String jobRunning = systemDictDao.findByDictNameAndCode("JOB_RUNNING","PatientConfirmReceiptJob");
            if("1".equals(jobRunning)) {
                List<Prescription> list = new ArrayList<>();
                //1.找出状态是已支付未完成且取药方式不是健管师配送的续方
                //1.找出状态是已发药未完成且取药方式不是健管师配送的续方
                List<Prescription> PrescriptionList = prescriptionDao.findUndelivered();
                for (Prescription prescription : PrescriptionList) {
                    String patient = prescription.getPatient();
                    Patient user = patientDao.findByCode(patient);
                    //2.取出延长收货的次数及支付时间
                    int extendCount = prescription.getExtendCount();
                    Integer extendCount = prescription.getExtendCount();
                    Date payTime = prescription.getPayTime();
                    if (payTime != null) {
                        //3.根据延长收货次数确定确认收货时间
                        Date today = new Date();
                        if (extendCount == null){
                            extendCount = 0;
                        }
                        Date confirm = DateUtil.getPreDays(payTime, ((extendCount + 1) * 7));
                        //4.计算现在到预计自动确认收货时间差值
                        long days = DateUtil.getDays(today,payTime);
@ -90,6 +96,7 @@ public class PatientConfirmReceiptJob implements Job {
                        if (result >= 0) {
                            prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.finish.getValue());
                            list.add(prescription);
                            payLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.jobConfirm.getValue(), 1, 0);
                            //发送自动确认提醒
                            sendWechatTemplate(2,patient,prescription.getCode());
                        }

+ 2 - 2
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionDao.java

@ -29,7 +29,7 @@ public interface PrescriptionDao extends PagingAndSortingRepository<Prescription
    @Query("update Prescription p set p.jwPayStatus=1 where p.code=?1")
    void updatejwPayStatus(String prescriptionCode);
    //查询居民已支付未完成且为自取及快递的续方
    @Query("from Prescription p where p.status >= 50 and p.status< 100 and p.dispensaryType in (1,2) ")
    //查询居民已发药未完成且为自取及快递的续方
    @Query("from Prescription p where p.status >= 60 and p.status< 100 and p.dispensaryType in (1,2) ")
    List<Prescription> findUndelivered();
}

+ 3 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/prescription/PrescriptionLogDao.java

@ -14,4 +14,7 @@ import java.util.List;
public interface PrescriptionLogDao extends PagingAndSortingRepository<PrescriptionLog, Long>, JpaSpecificationExecutor<PrescriptionLog> {
    @Query("select l.status,l.createTime from PrescriptionLog l where l.prescriptionCode=?1 and l.type in ?2 order by createTime desc")
    List<PrescriptionLog> findPrescriptionLogsByPrescriptionCode(String prescriptionCode, Integer[] types);
    @Query(" from PrescriptionLog l where l.prescriptionCode=?1 and l.status = ?2 ")
    List<PrescriptionLog> findByPrescriptionCodeAndStutas(String prescriptionCode, int status);
}

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

@ -859,9 +859,9 @@ public class DoctorInfoService extends BaseService {
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", newD.getName());
            if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
                data.put("remark", newD.getName() + "医生将专门为您提供优质健康服务");
                data.put("remark", newD.getName() + "健管师将专门为您提供优质健康服务");
            } else {
                data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
            }
        } else {
            data.put("toUser", patient);
@ -873,9 +873,9 @@ public class DoctorInfoService extends BaseService {
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", newD.getName());
            if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
                data.put("remark", newD.getName() + "医生将专门为您提供优质的健康服务");
                data.put("remark", newD.getName() + "健管师将专门为您提供优质的健康服务");
            } else {
                data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
            }
        }
@ -1012,9 +1012,9 @@ public class DoctorInfoService extends BaseService {
        data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
        data.put("keyword1", newD.getName());
        if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
            data.put("remark", newD.getName() + "医生将专门为您提供优质的健康服务");
            data.put("remark", newD.getName() + "健管师将专门为您提供优质的健康服务");
        } else {
            data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
            data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
        }
        if (StringUtils.isNotBlank(p.getOpenid())) {

+ 66 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionLogService.java

@ -0,0 +1,66 @@
package com.yihu.wlyy.service.app.prescription;
import com.yihu.wlyy.entity.patient.prescription.Prescription;
import com.yihu.wlyy.entity.patient.prescription.PrescriptionLog;
import com.yihu.wlyy.repository.prescription.PrescriptionLogDao;
import com.yihu.wlyy.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2017/7/27.
 */
@Service
public class PrescriptionLogService extends BaseService {
    @Autowired
    private PrescriptionLogDao prescriptionLogDao;
    /**
     * 根据处方code 和 types查询处方的流程日志 时间倒叙
     *
     * @param prescriptionCode 处方code
     * @param status           需要查询的status
     * @return
     */
    public List<PrescriptionLog> findPrescriptionLogsByPrescriptionCode(String prescriptionCode, Integer[] status) {
        return prescriptionLogDao.findPrescriptionLogsByPrescriptionCode(prescriptionCode, status);
    }
    /**
     * 添加日志
     *
     * @param prescription
     * @param type         类型: 1智业对接 2易联众对接  3创建处方 4 审核  5付款 6 配送 7完成
     * @param flag         1成功 0失败
     * @param userType     1 患者 2医生
     */
    public void addLog(Prescription prescription, Integer type, Integer flag, Integer userType) {
        PrescriptionLog log = null;
        List<PrescriptionLog> prescriptionLogs = prescriptionLogDao.findByPrescriptionCodeAndStutas(prescription.getCode(), prescription.getStatus());
        if (prescriptionLogs == null || prescriptionLogs.size() == 0) {
            log = new PrescriptionLog();
        } else {
            log = prescriptionLogDao.findOne(prescriptionLogs.get(0).getId());
        }
        log.setStatus(prescription.getStatus());
        log.setType(type);
        log.setCode(getCode());
        log.setCreateTime(new Date());
        log.setFlag(flag);
        log.setHospital(prescription.getHospital());
        log.setHospitalName(prescription.getHospitalName());
        log.setPrescriptionCode(prescription.getCode());
        if (userType == 1) {
            log.setUserCode(prescription.getParentCode());
            log.setUserName(prescription.getPatientName());
        } else {
            log.setUserCode(prescription.getDoctor());
            log.setUserName(prescription.getDoctorName());
        }
        log.setUserType(userType);
        prescriptionLogDao.save(log);
    }
}

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

@ -1827,9 +1827,9 @@ public class FamilyContractService extends BaseService {
                data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
                data.put("keyword1", docHealth.getName());
                if (StringUtils.isEmpty(signFamily.getDoctor()) || docHealth.getCode().equals(signFamily.getDoctor())) {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                } else {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                }
                wxMessages.add(data);
            } else {
@ -1843,9 +1843,9 @@ public class FamilyContractService extends BaseService {
                data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
                data.put("keyword1", docHealth.getName());
                if (StringUtils.isEmpty(signFamily.getDoctor()) || docHealth.getCode().equals(signFamily.getDoctor())) {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                } else {
                    data.put("remark", docHealth.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                    data.put("remark", docHealth.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                }
                wxMessages.add(data);
                try {

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

@ -60,7 +60,7 @@ public interface DevicePatientHealthIndexDao
	List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Pageable pageRequest);
	@Query("SELECT a FROM DevicePatientHealthIndex a where a.user = ?1 and a.del = '1' order by a.recordDate desc ")
	Iterable<DevicePatientHealthIndex> findRecentByPatient(String patient);
	List<DevicePatientHealthIndex> findRecentByPatient(String patient);
	@Query("select DATE_FORMAT(a.recordDate,'%Y-%m-%d') from DevicePatientHealthIndex a where a.user = ?1 and a.recordDate >= ?2 and a.recordDate <= ?3 and a.del = '1' group by DATE_FORMAT(a.recordDate,'%Y-%m-%d') order by DATE_FORMAT(a.recordDate,'%Y-%m-%d') desc")
	List<String> findDateList(String patient, Date start, Date end, Pageable pageRequest);

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

@ -55,6 +55,6 @@ public interface PatientHealthGuidanceDao extends PagingAndSortingRepository<Pat
    @Query("SELECT count(a) from PatientHealthGuidance a WHERE  a.patient=?2 and a.doctor=?1 ")
    Integer findbydoctorAndPatient(String doctor, String patientCode);
    @Query("select b.name, b.photo, a.id, substring(a.content, 1, 50) as content, a.createTime,b.level,b.code,a.adminTeamCode from PatientHealthGuidance a, Doctor b where a.doctor = b.code and a.patient = ?1 and a.adminTeamCode = ?2 and a.del = '1'")
    @Query("select b.name, b.photo, a.id, substring(a.content, 1, 50) as content, a.createTime,b.level,b.code,a.adminTeamCode,a.readStatus from PatientHealthGuidance a, Doctor b where a.doctor = b.code and a.patient = ?1 and a.adminTeamCode = ?2 and a.del = '1'")
    Page<Object> findByPatientAndTeamCode(String patient, Long teamCode, Pageable pageable);
}

+ 4 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientReservationDao.java

@ -22,10 +22,11 @@ public interface PatientReservationDao extends PagingAndSortingRepository<Patien
	PatientReservation findByCode(String code);
	List<PatientReservation> findByPatient(String patient, Pageable page);
	List<PatientReservation> findByPatientAndAdminTeamCode(String patient,Long teamCode,Pageable page);
//	List<PatientReservation> findByPatient(String patient, Pageable page);
//	List<PatientReservation> findByPatientAndAdminTeamCode(String patient,Long teamCode,Pageable page);
	Page<Object> findByPatient(String patient, Pageable page);
	Page<Object>  findByPatientAndAdminTeamCode(String patient,Long teamCode,Pageable page);
	List<PatientReservation> findByDoctor(String doctor,Pageable page);
	@Query("select count(1) from PatientReservation a where a.doctor = ?1 and a.patient=?2 ")

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

@ -15,6 +15,7 @@ import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.WlyyPatientSick;
import com.yihu.wlyy.entity.patient.prescription.Prescription;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.address.CityDao;
import com.yihu.wlyy.repository.address.ProvinceDao;
import com.yihu.wlyy.repository.address.TownDao;
@ -26,6 +27,7 @@ import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientSickDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.prescription.PrescriptionDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
@ -133,6 +135,8 @@ public class DoctorInfoService extends BaseService {
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
     * 获取医生的签约病人
@ -876,63 +880,79 @@ public class DoctorInfoService extends BaseService {
        Patient p = patientDao.findByCode(patient);
        JSONObject data = new JSONObject();
        if (StringUtils.isNotEmpty(oldDoctorCode)) {
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsbg");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(p.getName()==null?"":p.getName()));
            String remark = templateConfig.getRemark();
            String keyword3 = templateConfig.getKeyword3();
            data.put("toUser", patient);
            data.put("represented",patient);//被代理人
            data.put("doctor", newD.getCode());
            data.put("doctorName", newD.getName());
            data.put("first", p.getName() + ",您好!您签约团队的健康管理师已变更,您的新健管师信息如下:");
            data.put("keyword3", "家庭医生-健康管理师");
//            data.put("first", p.getName() + ",您好!您签约团队的健康管理师已变更,您的新健管师信息如下:");
            data.put("first", first);
//            data.put("keyword3", "家庭医生-健康管理师");
            data.put("keyword3", keyword3);
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", newD.getName());
            if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
                data.put("remark", newD.getName() + "医生将专门为您提供优质健康服务");
                remark = remark.replace("key1",(newD.getName()==null?"":newD.getName()+"健管师将专门"));
                data.put("remark", remark);
//                data.put("remark", newD.getName() + "健管师将专门为您提供优质健康服务");
            } else {
                data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                remark = remark.replace("key1",newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,");
                data.put("remark", remark);
//                data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
            }
        } else {
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxz");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(p.getName()==null?"":p.getName()));
            String remark = templateConfig.getRemark();
            String keyword3 = templateConfig.getKeyword3();
            data.put("toUser", patient);
            data.put("represented",patient);//被代理人
            data.put("doctor", newD.getCode());
            data.put("doctorName", newD.getName());
            data.put("first", p.getName() + ",您好!您的签约团队已为您新增一位健康管理师,医生信息如下:");
            data.put("keyword3", "家庭医生-健康管理师");
            data.put("first", first);
//            data.put("first", p.getName() + ",您好!您的签约团队已为您新增一位健康管理师,医生信息如下:");
//            data.put("keyword3", "家庭医生-健康管理师");
            data.put("keyword3", keyword3);
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", newD.getName());
            if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
                data.put("remark", newD.getName() + "医生将专门为您提供优质的健康服务");
//                data.put("remark", newD.getName() + "健管师将专门为您提供优质的健康服务");
                remark.replace("key1",(newD.getName()==null?"":newD.getName()));
                data.put("remark", remark);
            } else {
                data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxzqk");
                remark = templateConfig.getRemark();
                remark.replace("key1",(newD.getName()==null?"":newD.getName())).replace("key2",(signFamily.getDoctorName()==null?"":signFamily.getDoctorName()));
//                data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                data.put("remark", remark);
            }
        }
        //判断是否判定openId,有没有发则查找家人发送
        if (StringUtils.isNotBlank(p.getOpenid())) {
            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, p.getOpenid(), p.getName(), data);
        }
//        else {
//            JSONObject json = weiXinOpenIdUtils.getFamilyOpenId(p.getCode());
//            Patient member = (Patient) json.get("member");
//            if (StringUtils.isNotBlank(member.getOpenid())) {
//                String first = (String) data.get("first");
//                data.remove("first");
//                data.put("first", weiXinOpenIdUtils.getTitleMes(p, json.getInt("relation"), member.getName()) + first);
//                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), member.getName(), data);
//
//            }
//        }
        //发送代理人
        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
        if(jsonArray!=null&&jsonArray.length()>0){
            String first = (String) data.get("first");
            for (int i = 0;i<jsonArray.length();i++){
                JSONObject j  = jsonArray.getJSONObject(i);
                Patient member = (Patient) j.get("member");
                JSONObject json = data;
                json.remove("toUser");
                json.put("toUser",member.getCode());
                json.remove("first");
                json.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName())+first);
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
        }else {
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                String first = (String) data.get("first");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    JSONObject json = data;
                    json.remove("toUser");
                    json.put("toUser", member.getCode());
                    json.remove("first");
                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
                }
            }
        }
    }
@ -1032,49 +1052,53 @@ public class DoctorInfoService extends BaseService {
        Patient p = patientDao.findByCode(patient);
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxz");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(p.getName()==null?"":p.getName()));
        String remark = templateConfig.getRemark();
        String keyword3 = templateConfig.getKeyword3();
        JSONObject data = new JSONObject();
        data.put("toUser", patient);
        data.put("represented",patient);//被代理人
        data.put("doctor", newD.getCode());
        data.put("doctorName", newD.getName());
        data.put("first", p.getName() + ",您好!您的签约团队已为您新增一位健康管理师,医生信息如下:");
        data.put("keyword3", "家庭医生-健康管理师");
        data.put("first", first);
        data.put("keyword3", keyword3);
        /*data.put("first", p.getName() + ",您好!您的签约团队已为您新增一位健康管理师,医生信息如下:");
        data.put("keyword3", "家庭医生-健康管理师");*/
        data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
        data.put("keyword1", newD.getName());
        if (StringUtils.isEmpty(signFamily.getDoctor()) || signFamily.getDoctorHealth().equals(signFamily.getDoctor())) {
            data.put("remark", newD.getName() + "医生将专门为您提供优质的健康服务");
//            data.put("remark", newD.getName() + "健管师将专门为您提供优质的健康服务");
            remark.replace("key1",(newD.getName()==null?"":newD.getName()));
            data.put("remark", remark);
        } else {
            data.put("remark", newD.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
            templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxzqk");
            remark = templateConfig.getRemark();
            remark.replace("key1",(newD.getName()==null?"":newD.getName())).replace("key2",(signFamily.getDoctorName()==null?"":signFamily.getDoctorName()));
            data.put("remark", remark);
//            data.put("remark", newD.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
        }
        if (StringUtils.isNotBlank(p.getOpenid())) {
            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, p.getOpenid(), p.getName(), data);
        }
//        else {
//            JSONObject json = weiXinOpenIdUtils.getFamilyOpenId(p.getCode());
//            Patient member = (Patient) json.get("member");
//
//            if (StringUtils.isNotBlank(member.getOpenid())) {
//                String first = (String) data.get("first");
//                data.remove("first");
//                data.put("first", weiXinOpenIdUtils.getTitleMes(p, json.getInt("relation"), member.getName()) + first);
//                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), member.getName(), data);
//            }
//        }
        //发送代理人
        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
        if(jsonArray!=null&&jsonArray.length()>0){
            String first = (String) data.get("first");
            for (int i = 0;i<jsonArray.length();i++){
                JSONObject j  = jsonArray.getJSONObject(i);
                Patient member = (Patient) j.get("member");
                JSONObject json = data;
                json.remove("toUser");
                json.put("toUser",member.getCode());
                json.remove("first");
                json.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName())+first);
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
        }else {
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                first = (String) data.get("first");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    JSONObject json = data;
                    json.remove("toUser");
                    json.put("toUser", member.getCode());
                    json.remove("first");
                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
                }
            }
        }
        return 1;
@ -1258,37 +1282,47 @@ public class DoctorInfoService extends BaseService {
        try{
            Patient p = patientDao.findByCode(patient);
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(p.getName()==null?"":p.getName()));
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(newD.getName()==null?"":newD.getName()));
            String keyword3 = templateConfig.getKeyword3();
            JSONObject data = new JSONObject();
            data.put("toUser", patient);
            data.put("represented",patient);//被代理人
            data.put("doctor", newD.getCode());
            data.put("doctorName", newD.getName());
            data.put("keyword3", "家庭医生-全科医生");
//            data.put("keyword3", "家庭医生-全科医生");
            data.put("keyword3", keyword3);
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", newD.getName());
            if (StringUtils.isEmpty(signFamily.getDoctorHealth()) || signFamily.getDoctor().equals(signFamily.getDoctorHealth())) {
//            data.put("first", p.getName() + ",您签约团队的全科医生已变更,您的新全科医生信息如下:");
            data.put("first", first);
            data.put("remark", remark);
            /*if (StringUtils.isEmpty(signFamily.getDoctorHealth()) || signFamily.getDoctor().equals(signFamily.getDoctorHealth())) {
                data.put("remark", newD.getName() + "医生将继续为您提供优质健康服务");
            } else {
                data.put("remark", newD.getName() + "医生将继续为您提供优质健康服务");
            }
            }*/
            if (StringUtils.isNotBlank(p.getOpenid())) {
                data.put("first", p.getName() + ",您签约团队的全科医生已变更,您的新全科医生信息如下:");
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, p.getOpenid(), p.getName(), data);
            }
            //发送代理人
            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 json = data;
                    json.remove("toUser");
                    json.put("toUser",member.getCode());
                    json.remove("first");
                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) json.get("relation"), p.getName()) + p.getName() + ",您好!您签约团队的全科医生已变更,您的新全科医生信息如下:");
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
            }else {
                //发送代理人
                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 json = data;
                        json.remove("toUser");
                        json.put("toUser", member.getCode());
                        json.remove("first");
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) json.get("relation"), p.getName()) + p.getName() + ",您好!您签约团队的全科医生已变更,您的新全科医生信息如下:");
                        pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), json);
                    }
                }
            }
        }catch (Exception e){

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

@ -18,6 +18,7 @@ import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.prescription.*;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.entity.zydict.ZyIvPhysicDict;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
@ -32,6 +33,7 @@ import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.prescription.*;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
@ -162,6 +164,8 @@ public class ConsultTeamService extends ConsultService {
    
    @Autowired
    private PrescriptionFollowupContentService prescriptionFollowupContentService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    Map<Integer, String> relations = new HashMap<>();
@ -758,6 +762,7 @@ public class ConsultTeamService extends ConsultService {
            consult.put("patient", patient);
            consult.put("patientName", p.getName());
            consult.put("patientPhoto", p.getPhoto());
            consult.put("total", result.getTotalElements());
            array.put(consult);
        }
@ -2398,36 +2403,45 @@ public class ConsultTeamService extends ConsultService {
            endName = p.getName();
            if (consultTeam.getType() == 2||consultTeam.getType()==8) {
                String openId = p.getOpenid();
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zxpj");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(endName==null?"":endName));
                String keyword1 = templateConfig.getKeyword1();
                JSONObject json = new JSONObject();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                json.put("keyword1", "医生评价");
                json.put("keyword1", keyword1);
                json.put("keyword2", sdf.format(new Date()));
                json.put("toUser", p.getCode());
                json.put("represented",p.getCode());//被代理人
                json.put("remark", "");
                json.put("consult", consult);
                String first = endName + ",您好!您有1条";;
//                String first = endName + ",您好!您有1条";;
                if(consultTeam.getType()==8){
                    first += "续方";
//                    first += "续方";
                    first = first.replace("key2","续方");
                }else {
                    first = first.replace("key2","");
                }
                first += "咨询已结束,请及时对咨询医生进行评价。";
//                first += "咨询已结束,请及时对咨询医生进行评价。";
                json.put("first", first);
                if(StringUtils.isNotBlank(p.getOpenid())){
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.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(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    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(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                        }
                    }
                }
            }
@ -2436,40 +2450,53 @@ public class ConsultTeamService extends ConsultService {
                Patient p = patientDao.findByCode(consultTeam.getPatient());
                String name = p.getName();
                String openId = p.getOpenid();
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zxpj");
                if (endOperator.equals("admin")) {
                    templateConfig = templateConfigDao.findByScene("template_doctor_survey","zxcspj");
                }
                String first = templateConfig.getFirst();
                first = first.replace("key1",(name==null?"":name));
                String keyword1 = templateConfig.getKeyword1();
                JSONObject json = new JSONObject();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                json.put("keyword1", "医生评价");
                json.put("keyword1", keyword1);
                json.put("keyword2", sdf.format(new Date()));
                json.put("toUser", p.getCode());
                json.put("represented",p.getCode());//被代理人
                json.put("remark", "");
                json.put("consult", consult);
                String first = name + ",您好!您有1条";;
//                String first = name + ",您好!您有1条";;
                if(consultTeam.getType()==8){
                    first += "续方";
//                    first += "续方";
                    first  = first.replace("key2","续方");
                }else {
                    first  = first.replace("key2","");
                }
                if (endOperator.equals("admin")) {
                /*if (endOperator.equals("admin")) {
                    first += "咨询超时未回复,系统自动关闭,请及时对咨询医生进行评价。";
                }else {
                    first += "咨询已结束,请及时对咨询医生进行评价。";
                }
                }*/
                json.put("first", first);
                if(StringUtils.isNotBlank(p.getOpenid())){
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.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(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    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(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                        }
                    }
                }

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

@ -766,7 +766,8 @@ public class PatientDeviceService extends BaseService {
     * @param page
     * @param pageSize
     */
    public List<com.alibaba.fastjson.JSONObject> searchPatient(String name,Integer page,Integer pageSize){
    public List<com.alibaba.fastjson.JSONObject> searchPatient(String name,Integer page,Integer pageSize,String idcards){
        Object o[] = null;
        StringBuffer sql = new StringBuffer("SELECT p.code,p.name,p.address,p.idcard,p.sex,GROUP_CONCAT(label_name) labelName,t.doctor_name doctorName ");
        sql.append("FROM ( SELECT DISTINCT f.* FROM wlyy_patient_device d, wlyy_sign_family f ");
        sql.append("WHERE f.`status` > 0 AND f.patient = d.`user` ) t, wlyy_patient p LEFT JOIN ");
@ -775,8 +776,17 @@ public class PatientDeviceService extends BaseService {
        if(StringUtils.isNotBlank(name)){
            sql.append(" and (p.`name` like '%"+name+"%' or t.doctor_name like '%"+name+"%') ");
        }
        sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex LIMIT ?,? ");
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),new Object[]{(page-1)*pageSize,pageSize});
        if(StringUtils.isNotBlank(idcards)){
            idcards = "'"+idcards.replaceAll(",","','")+"'";
            sql.append(" and p.idcard in ("+idcards+") ");
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex ");
            o = new Object[]{};
        }else {
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex LIMIT ?,? ");
            o = new Object[]{(page-1)*pageSize,pageSize};
        }
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),o);
        list.forEach(json->{
            json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(json.get("idcard"))));
        });

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

@ -6,10 +6,12 @@ import com.yihu.wlyy.entity.patient.PatientFamilyTemp;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.invitation.PatientInvitationLog;
import com.yihu.wlyy.entity.security.AccessToken;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.PatientFamilyTempDao;
import com.yihu.wlyy.repository.patient.PatientInvitationLogDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.common.SMSService;
@ -69,6 +71,8 @@ public class FamilyMemberService extends BaseService {
    private String appSecret;
    @Value("${wechat.accId}")
    private String accId;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @PostConstruct
    public void init() {
@ -1027,16 +1031,29 @@ public class FamilyMemberService extends BaseService {
                    if(StringUtils.isNotBlank(p.getOpenid())){
                        //发送添加成功消息模板
                        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xzcy");
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(p.getName()==null?"":p.getName())).replace("key1",(m.getName()==null?"":m.getName()));
                        String remark = templateConfig.getRemark();
                        remark = remark.replace("key1",(m.getName()==null?"":m.getName()))
                                .replace("key2",(relations.get(temp.getFamilyRelation())==null?"":relations.get(temp.getFamilyRelation())));
                        String keyword1 = templateConfig.getKeyword1();
                        JSONObject json = new JSONObject();
                        json.put("first", p.getName() + ",您好!"+m.getName()+"已加入到您的家庭成员。");
                        json.put("keyword1", "添加家人申请成功");
                        json.put("first", first);
//                        json.put("first", p.getName() + ",您好!"+m.getName()+"已加入到您的家庭成员。");
                        json.put("keyword1", keyword1);
//                        json.put("keyword1", "添加家人申请成功");
                        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                        json.put("remark", remark);
//                        json.put("keyword3", m.getName());
//                        json.put("keyword4", relations.get(temp.getFamilyRelation()));
                        json.put("remark",
                        /*json.put("remark",
                                "家人:"+m.getName()+"\n"+
                                "家庭关系:"+relations.get(temp.getFamilyRelation())+"\n"+
                                "点击查看家人。");
                                "点击查看家人。");*/
                        System.out.println("-----sendMes----:openId "+p.getOpenid()+"-----access_token-----:"+access_token+"--json--");
                        //此消息为定向推送,无需家人代收
                        pushMsgTask.putWxMsg(access_token, 13, p.getOpenid(), p.getName(), json);
@ -1052,10 +1069,18 @@ public class FamilyMemberService extends BaseService {
                Patient p = patientDao.findByCode(temp.getPatient());
                Patient m = patientDao.findByCode(temp.getFamilyMember());
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xzcysb");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(p.getName()==null?"":p.getName())).replace("key1",(m.getName()==null?"":m.getName()));
                String keyword1 = templateConfig.getKeyword1();
                //发送添加成功消息模板
                JSONObject json = new JSONObject();
                json.put("first", p.getName() + ",您好!"+m.getName()+"拒绝了您的家人申请。");
                json.put("keyword1", "添加家人申请失败");
                json.put("first", first);
//                json.put("first", p.getName() + ",您好!"+m.getName()+"拒绝了您的家人申请。");
//                json.put("keyword1", "添加家人申请失败");
                json.put("keyword1", keyword1);
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark"," ");
                System.out.println("-----sendMes----:openId "+p.getOpenid()+"-----access_token-----:"+access_token+"--json--");
@ -1214,15 +1239,27 @@ public class FamilyMemberService extends BaseService {
            patientFamilyTempDao.save(temp);
        }
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xzcysq");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(m.getName()==null?"":m.getName())).replace("key2",(p.getName()==null?"":p.getName()));
        String remark = templateConfig.getRemark();
        remark = remark.replace("key1",(p.getName()==null?"":p.getName()))
                .replace("key2",(relations.get(relation)==null?"":relations.get(relation)))
                .replace("br","\n");
        String keyword1 = templateConfig.getKeyword1();
        JSONObject json = new JSONObject();
        json.put("first", m.getName() + ",您好!" + p.getName() + "向您发起添加家人申请,添加成功后,对方可使用您的账号,为您处理各类健康服务。");
//        json.put("first", m.getName() + ",您好!" + p.getName() + "向您发起添加家人申请,添加成功后,对方可使用您的账号,为您处理各类健康服务。");
        json.put("first", first);
        json.put("keyword1", "添加家人申请");
        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
        json.put("remark", remark);
//        json.put("keyword3", p.getName());
//        json.put("keyword4", relations.get(relation));
        json.put("remark", "申请人:"+p.getName()+"\n"+
       /* json.put("remark", "申请人:"+p.getName()+"\n"+
                "家庭关系:"+relations.get(relation)+"\n"+
                "点击立即处理。");
                "点击立即处理。");*/
        json.put("member", member);
        //此消息为定向推送,无需家人代收
        pushMsgTask.putWxMsg(access_token, 12, m.getOpenid(), m.getName(), json);

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

@ -333,6 +333,7 @@ public class FollowUpService extends BaseService {
                followup.put("followupPlanDate", objArr[13] != null ? DateUtil.dateToStrLong((Date) objArr[13]) : "");
                followup.put("followupNextDate", objArr[14] != null ? DateUtil.dateToStrLong((Date) objArr[14]) : "");
                followup.put("prescriptionCode", objArr[17]);
                followup.put("total", result.getTotalElements());
                array.put(followup);
            }
        }

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

@ -4,10 +4,12 @@ import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientHealthGuidanceDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
@ -55,6 +57,8 @@ public class PatientHealthGuidanceService extends BaseService {
	@Autowired
	private PushMsgTask pushMsgTask;
	@Autowired
	private WechatTemplateConfigDao templateConfigDao;
	public JSONObject findById(Long id){
		PatientHealthGuidance guidance = patientHealthGuidanceDao.findOne(id);
@ -155,23 +159,23 @@ public class PatientHealthGuidanceService extends BaseService {
			if(StringUtils.isNotEmpty(openId)){
				// 推送消息到微信端
				pushMsgTask.putWxMsg(accessToken, 4, openId, patient.getName(), json);
			}
			//发送代理人
			JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(),patient.getOpenid());
			if(jsonArray!=null&&jsonArray.length()>0){
				for (int i = 0;i<jsonArray.length();i++){
					JSONObject j  = jsonArray.getJSONObject(i);
					Patient member = (Patient) j.get("member");
					JSONObject data = json;
					data.remove("toUser");
					data.put("toUser",member.getCode());
					//String first = (String) json.get("first");
					data.remove("first");
					data.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
					pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 4, member.getOpenid(), patient.getName(), data);
			}else {
				//发送代理人
				JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
				if (jsonArray != null && jsonArray.length() > 0) {
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject j = jsonArray.getJSONObject(i);
						Patient member = (Patient) j.get("member");
						JSONObject data = json;
						data.remove("toUser");
						data.put("toUser", member.getCode());
						//String first = (String) json.get("first");
						data.remove("first");
						data.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
						pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 4, member.getOpenid(), patient.getName(), data);
					}
				}
			}
		}
		return guidance;
	}
@ -262,6 +266,8 @@ public class PatientHealthGuidanceService extends BaseService {
				json.put("content", temp[3]);
				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
				json.put("adminTeamCode", temp[7]);
				json.put("readStatus", temp[8]);
				json.put("total", result.getTotalElements());
				array.put(json);
			}
		}

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

@ -26,6 +26,7 @@ import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.third.iot.IotDeviceService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.NameValuePair;
@ -228,7 +229,8 @@ public class PatientHealthIndexService extends BaseService {
                " ORDER BY " +
                " a.record_date DESC " +
                "LIMIT 0,1 ";
        List<Map<String, Object>> devicePatient = jdbcTemplate.queryForList(sql, patient, type);
//        List<Map<String, Object>> devicePatient = jdbcTemplate.queryForList(sql, patient, type);
        List<Map<String, Object>> devicePatient = findDataByPatient(sql, patient, type);
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> device : devicePatient) {
            String time = device.get("record_date") == null ? null : device.get("record_date").toString();
@ -429,7 +431,8 @@ public class PatientHealthIndexService extends BaseService {
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,dateString);
        if (list != null && list.size() > 0) {
            obj.put("type", 1);
            obj.put("czrq", date);
@ -639,6 +642,171 @@ public class PatientHealthIndexService extends BaseService {
        }
    }
    /**
     * 查询最近的一条体征数据
     * @param sql
     * @param patient
     * @param type
     * @return
     */
    public List<Map<String, Object>> findDataByPatient(String sql,String patient,Integer type){
        if(iotDeviceService.isUploadIot()){
            List<Map<String, Object>> re = new ArrayList<>();
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndType(patient,type,1);
            if(list!=null&&list.size()>0){
                re.add(indexToMap(list.get(0)));
            }
            return re;
        }else {
            return jdbcTemplate.queryForList(sql, patient, type);
        }
    }
    /**
     * 患者最近填写的健康指标
     * @param patient
     * @return
     */
    public List<DevicePatientHealthIndex> findRecentByPatientIterable(String patient){
        if(iotDeviceService.isUploadIot()){
            return iotDeviceService.findByPatientAndType(patient,null,1000);
        }else {
            return patientHealthIndexDao.findRecentByPatient(patient);
        }
    }
    /**
     * 根据患者标志获取健康指标
     * @param patient
     * @param type
     * @return
     */
    public DevicePatientHealthIndex findLastByPatienIot(String patient,Integer type){
        if(iotDeviceService.isUploadIot()){
            DevicePatientHealthIndex index = null;
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndType(patient,type,1);
            if(list!=null&&list.size()>0){
                index = list.get(0);
            }
            return index;
        }else {
            return findLastByPatien(patient,type);
        }
    }
    /**
     * 查询指标记录
     * @param patient
     * @param startDate
     * @param endDate
     * @param page
     * @param size
     * @return
     */
    public List<String> findDateListIot(String patient,Date startDate,Date endDate, Integer page, Integer size,String start, String end){
        if(iotDeviceService.isUploadIot()){
            List<String> re = new ArrayList<>();
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, null,page, size, null, start, end);
            if(list!=null&&list.size()>0){
                list.forEach(one->{
                    re.add(DateUtil.dateToStrShort(one.getRecordDate()));
                });
            }
            return re;
        }else {
            return patientHealthIndexDao.findDateList(patient,startDate,endDate,page,size);
        }
    }
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param type
     * @param size
     * @param gi_type
     * @param begin
     * @param end
     * @return
     */
    public List<Map<String, Object>> findByPatientAndTime(String sql,String patient,Integer type,Integer size,Integer gi_type, String begin, String end){
        if(iotDeviceService.isUploadIot()){
            List<Map<String, Object>> re = new ArrayList<>();
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, type,1, size, gi_type, begin, end);
            if(list!=null&&list.size()>0){
                list.forEach(one->{
                    re.add(indexToMap(one));
                });
            }
            return re;
        }else {
            return jdbcTemplate.queryForList(sql);
        }
    }
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param date
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient, String date){
        String begin = date +" 00:00:00";
        String end= date +" 23:59:59";
        if(iotDeviceService.isUploadIot()){
            List<Map<String, Object>> re = new ArrayList<>();
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, 1,1, 100, null, begin, end);
            if(list!=null&&list.size()>0){
                list.forEach(one->{
                    re.add(indexToMap(one));
                });
            }
            return re;
        }else {
            return jdbcTemplate.queryForList(sql);
        }
    }
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient,Integer type,Integer page,Integer size, String begin,String end){
        if(iotDeviceService.isUploadIot()){
            List<Map<String, Object>> re = new ArrayList<>();
            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, type,page, size, null, begin, end);
            if(list!=null&&list.size()>0){
                list.forEach(one->{
                    re.add(indexToMap(one));
                });
            }
            return re;
        }else {
            return jdbcTemplate.queryForList(sql);
        }
    }
    /**
     * 转map
     * @param index
     * @return
     */
    private Map<String, Object> indexToMap(DevicePatientHealthIndex index){
        Map<String, Object> map = new HashedMap();
        map.put("value1",index.getValue1());
        map.put("value2",index.getValue2());
        map.put("value3",index.getValue3());
        map.put("value4",index.getValue4());
        map.put("value5",index.getValue5());
        map.put("value6",index.getValue6());
        map.put("value7",index.getValue7());
        map.put("device_sn",index.getDeviceSn());
        map.put("record_date",index.getRecordDate());
        return map;
    }
    /********************************************物联网 end***********************************************************/
@ -1177,7 +1345,8 @@ public class PatientHealthIndexService extends BaseService {
        sql = sql + conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = findByPatientAndTime(sql,patient,type,1000,gi_type,begin,end);
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            json.put("id", map.get("id"));
@ -1464,7 +1633,8 @@ public class PatientHealthIndexService extends BaseService {
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,type,pageRequest.getOffset(),pageRequest.getPageSize(),start,end);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
@ -1519,7 +1689,8 @@ public class PatientHealthIndexService extends BaseService {
        {
            PageRequest pageRequest = new PageRequest(page, pageSize);
            //根据时间过滤排序
            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            List<String> dateList = findDateListIot(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize(), start, end);
            if (dateList != null && dateList.size() > 0) {
                for (String dateString : dateList) {
                    com.alibaba.fastjson.JSONObject obj = getPatientXT_Json(patient, dateString);
@ -1564,7 +1735,8 @@ public class PatientHealthIndexService extends BaseService {
     */
    public JSONArray findRecentByPatient(String patient) {
        JSONArray array = new JSONArray();
        Iterable<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
//        List<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
        List<DevicePatientHealthIndex> iterable = findRecentByPatientIterable(patient);
        if (iterable != null) {
            Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
            while (iterator != null && iterator.hasNext()) {

+ 69 - 48
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/physicalExamination/PhysicalExaminationRemindService.java

@ -6,10 +6,12 @@ import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientRemindRecords;
import com.yihu.wlyy.entity.patient.PatientTeamRemindRecord;
import com.yihu.wlyy.entity.patient.vo.PatientVO;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientRemindRecordsDao;
import com.yihu.wlyy.repository.patient.PatientTeamRemindRecordDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.task.PushMsgTask;
@ -62,6 +64,8 @@ public class PhysicalExaminationRemindService extends BaseService {
    private DoctorDao doctorDao;
    @Autowired
    private PatientTeamRemindRecordDao patientTeamRemindRecordDao;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
     * 单个提醒居民按钮
@ -335,37 +339,46 @@ public class PhysicalExaminationRemindService extends BaseService {
        Boolean flag = true;
        // 推送消息给微信端
        String url = "jkda/html/jiankangtijian.html?openid=" + patient.getOpenid() +"&toUser="+patient.getCode()+"&toName=" + patient.getName();
        String first = "您的家庭医生" + doctName + "提醒,您可以到签约社区进行65岁以上老年人的免费健康体检啦~";
//        String first = "您的家庭医生" + doctName + "提醒,您可以到签约社区进行65岁以上老年人的免费健康体检啦~";
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(doctName==null?"":doctName));
        String remark = templateConfig.getRemark();
        String keyword1 = templateConfig.getKeyword1();
        JSONObject json = new org.json.JSONObject();
        json.put("first",first);
        json.put("url",url);
        json.put("keyword1", "健康体检");
        json.put("keyword1", keyword1);
//        json.put("keyword1", "健康体检");
        json.put("keyword2", format.format(new Date()));
        json.put("remark", "为了您和您的家庭医生了解您近期的健康状况,请及时到您签约的社区体检哟~(如已体检请忽略)");
//        json.put("remark", "为了您和您的家庭医生了解您近期的健康状况,请及时到您签约的社区体检哟~(如已体检请忽略)");
        json.put("remark", remark);
        if (StringUtils.isNotBlank(patient.getOpenid())) {
            pushMsgTask.putWxMsg(accessToken, 11, patient.getOpenid(), patient.getName(), json);
            flag = false;
        }
        //发送代理人
        JSONArray jsonArray = openIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                org.json.JSONObject j = jsonArray.getJSONObject(i);
                Patient member = (Patient) j.get("member");
                int start = url.indexOf("&toUser=");
                int end = url.indexOf("&", start + 1);
                String touser = url.substring(start, end);
                url = url.replace(touser, "&toUser=" + member.getCode());
                json.remove("first");
                try {
                    json.put("first", openIdUtils.getTitleMes(patient, j.isNull("relation") ? 1 : j.getInt("relation"), patient.getName())+first);
                    json.put("url", url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (StringUtils.isNotBlank(member.getOpenid())) {
                    pushMsgTask.putWxMsg(accessToken, 11, member.getOpenid(), patient.getName(), json);
                    flag = false;
        }else {
            //发送代理人
            JSONArray jsonArray = openIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    org.json.JSONObject j = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    int start = url.indexOf("&toUser=");
                    int end = url.indexOf("&", start + 1);
                    String touser = url.substring(start, end);
                    url = url.replace(touser, "&toUser=" + member.getCode());
                    json.remove("first");
                    try {
                        json.put("first", openIdUtils.getTitleMes(patient, j.isNull("relation") ? 1 : j.getInt("relation"), patient.getName()) + first);
                        json.put("url", url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (StringUtils.isNotBlank(member.getOpenid())) {
                        pushMsgTask.putWxMsg(accessToken, 11, member.getOpenid(), patient.getName(), json);
                        flag = false;
                    }
                }
            }
        }
@ -396,11 +409,18 @@ public class PhysicalExaminationRemindService extends BaseService {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String accessToken = accessTokenUtils.getAccessToken();
        Boolean flag = true;
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(doctName==null?"":doctName));
        String remark = templateConfig.getRemark();
        String keyword1 = templateConfig.getKeyword1();
        // 推送消息给微信端
        JSONObject json = new org.json.JSONObject();
        json.put("keyword1", "健康体检");
        json.put("keyword1", keyword1);
        json.put("keyword2", format.format(new Date()));
        json.put("remark", "为了您和您的家庭医生了解您近期的健康状况,请及时到您签约的社区体检哟~(如已体检请忽略)");
//        json.put("remark", "为了您和您的家庭医生了解您近期的健康状况,请及时到您签约的社区体检哟~(如已体检请忽略)");
        json.put("remark", remark);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
@ -409,7 +429,7 @@ public class PhysicalExaminationRemindService extends BaseService {
        List<Patient> patients = patientDao.findExaminationRemind(teamId, yesteryear);
        for (Patient patient : patients) {
            String url = "jkda/html/jiankangtijian.html?openid=" + patient.getOpenid() +"&toUser="+patient.getCode()+"&toName=" + patient.getName();
            String first = "您的家庭医生" + doctName + "提醒,您可以到签约社区进行65岁以上老年人的免费健康体检啦~";
//            String first = "您的家庭医生" + doctName + "提醒,您可以到签约社区进行65岁以上老年人的免费健康体检啦~";
            json.put("first",first);
            json.put("url",url);
            String mobile = patient.getMobile();
@ -420,27 +440,28 @@ public class PhysicalExaminationRemindService extends BaseService {
            if (StringUtils.isNotBlank(patient.getOpenid())) {
                pushMsgTask.putWxMsg(accessToken, 11, patient.getOpenid(), patient.getName(), json);
                flag = false;
            }
            //发送代理人
            JSONArray jsonArray = openIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    org.json.JSONObject j = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    int start = url.indexOf("&toUser=");
                    int end = url.indexOf("&", start + 1);
                    String touser = url.substring(start, end);
                    url = url.replace(touser, "&toUser=" + member.getCode());
                    json.remove("first");
                    try {
                        json.put("first", openIdUtils.getTitleMes(patient, j.isNull("relation") ? 1 : j.getInt("relation"), patient.getName())+first);
                        json.put("url", url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (StringUtils.isNotBlank(member.getOpenid())) {
                        pushMsgTask.putWxMsg(accessToken, 11, member.getOpenid(), patient.getName(), json);
                        flag = false;
            }else {
                //发送代理人
                JSONArray jsonArray = openIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        org.json.JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        int start = url.indexOf("&toUser=");
                        int end = url.indexOf("&", start + 1);
                        String touser = url.substring(start, end);
                        url = url.replace(touser, "&toUser=" + member.getCode());
                        json.remove("first");
                        try {
                            json.put("first", openIdUtils.getTitleMes(patient, j.isNull("relation") ? 1 : j.getInt("relation"), patient.getName()) + first);
                            json.put("url", url);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (StringUtils.isNotBlank(member.getOpenid())) {
                            pushMsgTask.putWxMsg(accessToken, 11, member.getOpenid(), patient.getName(), json);
                            flag = false;
                        }
                    }
                }
            }

+ 18 - 4
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prenatalInspector/PrenatalInspectorPreCardService.java

@ -11,9 +11,11 @@ import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlan;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPlanLibrary;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorPreCard;
import com.yihu.wlyy.entity.patient.prenatal.PrenatalInspectorRecord;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.health.repository.DevicePatientHealthIndexDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
@ -75,6 +77,8 @@ public class PrenatalInspectorPreCardService extends BaseService {
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private SMSService smsService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
//    public
@ -940,18 +944,28 @@ public class PrenatalInspectorPreCardService extends BaseService {
            String name = patient.getName();
            String openId = patient.getOpenid();
            String mobile = patient.getMobile();
            String first = name + ",您好!您和您的宝宝需要进行产检啦~请及时预约产检,如已预约,请忽略";
//            String first = name + ",您好!您和您的宝宝需要进行产检啦~请及时预约产检,如已预约,请忽略";
            String url = "wdyy/html/appointment-register.html?openid=" + openId + "&toUser=" + code + "&toName=" + name;
            PrenatalInspectorPlan plan = prenatalInspectorPlanDao.findOne(prenatalId);
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","cjtx");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(name==null?"":name));
            String remark = templateConfig.getRemark();
            String keyword1 = templateConfig.getKeyword1();
            String keyword2 = templateConfig.getKeyword2();
            keyword2 = keyword2.replace("key1",DateUtil.getStringDateShort()).replace("key2",plan.getCheckItem()).replace("br","\n");
            org.json.JSONObject json = new org.json.JSONObject();
            //产检提醒
            json.put("remark", "产检内容以医生实际检查为准。点击进行预约");
//            json.put("remark", "产检内容以医生实际检查为准。点击进行预约");
            json.put("remark", remark);
            json.put("first", first);
            json.put("url", url);
            json.put("keyword1", "产检提醒");
            String keyword2 = DateUtil.getStringDateShort() + "\n产检内容:" + plan.getCheckItem();
            json.put("keyword1", keyword1);
//            String keyword2 = DateUtil.getStringDateShort() + "\n产检内容:" + plan.getCheckItem();
            json.put("keyword2", keyword2);
            if (StringUtils.isNotEmpty(openId) && !("undefined".equals(openId))) {
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 18, openId, name, json);

+ 20 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionInfoService.java

@ -735,7 +735,7 @@ public class PrescriptionInfoService extends BaseService {
        return 1;
    }
    public List<Map<String, Object>> getDoctorPrescription(Integer teamCode, String state, String diseases, String startDate, String endDate, String nameKeyword, String patient, Integer page, Integer size) {
    public List<Map<String, Object>> getDoctorPrescription(Integer teamCode, String state, String diseases, String startDate, String endDate, String nameKeyword, String patient, Integer page, Integer size,String isPcim) {
        StringBuffer pre_sql = new StringBuffer("SELECT " +
                " p.`name`, " +
                " TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, " +
@ -758,11 +758,11 @@ public class PrescriptionInfoService extends BaseService {
                    " WHERE s.prescription_code = pr.code " +
                    " AND s.health_problem = ?");
            params.add(diseases);
            setSQL(pre_sql, params, teamCode, state, startDate, endDate, nameKeyword, patient, page, size);
            setSQL(pre_sql, params, teamCode, state, startDate, endDate, nameKeyword, patient, page, size, isPcim);
        } else {
            //查询所有疾病类型表
            pre_sql.append(" WHERE 1=1 ");
            setSQL(pre_sql, params, teamCode, state, startDate, endDate, nameKeyword, patient, page, size);
            setSQL(pre_sql, params, teamCode, state, startDate, endDate, nameKeyword, patient, page, size, isPcim);
        }
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(pre_sql.toString(), params.toArray());
@ -775,14 +775,29 @@ public class PrescriptionInfoService extends BaseService {
        return rs;
    }
    public void setSQL(StringBuffer pre_sql, List<Object> params, Integer teamCode, String state, String startDate, String endDate, String nameKeyword, String patient, Integer page, Integer size) {
    public void setSQL(StringBuffer pre_sql, List<Object> params, Integer teamCode, String state, String startDate, String endDate, String nameKeyword, String patient, Integer page, Integer size, String isPcim) {
        if (teamCode != null && teamCode > 0) {
            pre_sql.append(" AND pr.admin_team_id =?");
            params.add(teamCode);
        }
        if (StringUtils.isNotBlank(state)) {
            pre_sql.append(" AND pr.status IN (" + state + ") ");
            //不是pcim新改的用原来的接口-2018.03.09
            if (StringUtils.isNotBlank(isPcim) && "0".equals(isPcim)){
                pre_sql.append(" AND pr.status IN (" + state + ") ");
            }else if (StringUtils.isNotBlank(isPcim) && "1".equals(isPcim)){
                //如果是pcim新改的则状态搜索改变
                //待审核和已完成
                if ("0".equals(state)  || "100".equals(state)){
                    pre_sql.append(" AND pr.status IN (" + state + ") ");
                }else if ("-1".equals(state)){
                    //已取消
                    pre_sql.append(" AND pr.status < (-1) ");
                }else if ("1".equals(state)){
                    //已完成
                    pre_sql.append(" AND pr.status > 0 AND pr.status <100 ");
                }
            }
        }
        if (StringUtils.isNotBlank(startDate)) {
            pre_sql.append(" AND pr.create_time >= ? ");

+ 58 - 14
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionNoticesService.java

@ -1,7 +1,9 @@
package com.yihu.wlyy.service.app.prescription;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
@ -29,6 +31,8 @@ public class PrescriptionNoticesService extends BaseService {
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    private static final Logger LOGGER = LoggerFactory.getLogger(PrescriptionNoticesService.class);
@ -64,9 +68,16 @@ public class PrescriptionNoticesService extends BaseService {
        if (type == 1) {
            switch (status) {
                case 0:
                    first = name + "您好,你的续方申请医生已审核。";
                    WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_audit","xfbtg");
                    first = templateConfig.getFirst();
                    first = first.replace("key1",(name==null?"":name));
                    remark = templateConfig.getRemark();
                    String keyword1 = templateConfig.getKeyword1();
                    /*first = name + "您好,你的续方申请医生已审核。";
                    remark = "您可点击消息查看详情,修改续方信息后重新提交。";
                    sendJson.put("keyword1", "审核不通过");
                    sendJson.put("keyword1", "审核不通过");*/
                    sendJson.put("keyword1", keyword1);
                    sendJson.put("keyword2", doctName);
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
@ -90,9 +101,16 @@ public class PrescriptionNoticesService extends BaseService {
                    }
                    break;
                case 1:
                    first = name + "您好,你的续方申请医生已审核。";
                    templateConfig = templateConfigDao.findByScene("template_doctor_audit","xftg");
                    first = templateConfig.getFirst();
                    first = first.replace("key1",(name==null?"":name));
                    remark = templateConfig.getRemark();
                    String keyword = templateConfig.getKeyword1();
                    /*first = name + "您好,你的续方申请医生已审核。";
                    remark = "您可点击消息查看详情并完成支付。";
                    sendJson.put("keyword1", "审核通过");
                    sendJson.put("keyword1", "审核通过");*/
                    sendJson.put("keyword1", keyword);
                    sendJson.put("keyword2", doctName);
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
@ -116,9 +134,16 @@ public class PrescriptionNoticesService extends BaseService {
                    }
                    break;
                case 2:
                    first = name + "您好,您的续方申请医生已修改处方清单并审核。";
                    templateConfig = templateConfigDao.findByScene("template_doctor_audit","tztg");
                    first = templateConfig.getFirst();
                    first = first.replace("key1",(name==null?"":name));
                    remark = templateConfig.getRemark();
                    String keyword2 = templateConfig.getKeyword1();
                    /*first = name + "您好,您的续方申请医生已修改处方清单并审核。";
                    remark = "您可点击消息查看详情并完成支付。";
                    sendJson.put("keyword1", "审核通过");
                    sendJson.put("keyword1", "审核通过");*/
                    sendJson.put("keyword1", keyword2);
                    sendJson.put("keyword2", doctName);
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
@ -143,9 +168,15 @@ public class PrescriptionNoticesService extends BaseService {
                    break;
            }
        } else if (type == 2) {
            first = name + "您好,您的续方订单已完成配药,请尽快致社区医院取药。";
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xfqy");
            first = templateConfig.getFirst();
            first = first.replace("key1",(name==null?"":name));
            String keyword1 = templateConfig.getKeyword1();
//            first = name + "您好,您的续方订单已完成配药,请尽快致社区医院取药。";
            remark = "";
            sendJson.put("keyword1", "续方订单取药");
            sendJson.put("keyword1", keyword1);
//            sendJson.put("keyword1", "续方订单取药");
            sendJson.put("keyword2", dateFormat.format(new Date()));
            sendJson.put("first", first);
            sendJson.put("remark", remark);
@ -169,11 +200,17 @@ public class PrescriptionNoticesService extends BaseService {
            }
        }
        if (type == 3) {
            first = name + "您好,您的续方订单配送员" + doctName + "已顺利取药,续方状态变更为配送中。";
            remark = "您可点击消息查看详情。";
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xfqy");
            first = templateConfig.getFirst();
            remark = templateConfig.getRemark();
            first = first.replace("key1",(name==null?"":name)).replace("key2",doctName);
            String keyword3 = templateConfig.getKeyword3();
           /* first = name + "您好,您的续方订单配送员" + doctName + "已顺利取药,续方状态变更为配送中。";
            remark = "您可点击消息查看详情。";*/
            sendJson.put("keyword1", doctName);
            sendJson.put("keyword2", dateFormat.format(new Date()));
            sendJson.put("keyword3", "续方状态");
            sendJson.put("keyword3", keyword3);
            sendJson.put("first", first);
            sendJson.put("remark", remark);
            sendJson.put("url", url);//带参数的模板跳转链接
@ -196,9 +233,16 @@ public class PrescriptionNoticesService extends BaseService {
            }
        }
        if (type == 4) {
            first = name + ",您好!您的续方订单已成功配送。";
            remark = "感谢您的使用。";
            sendJson.put("keyword1", "续方申请");
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_service","xfwc");
            first = templateConfig.getFirst();
            remark = templateConfig.getRemark();
            first = first.replace("key1",(name==null?"":name));
            String keyword1 = templateConfig.getKeyword1();
//            first = name + ",您好!您的续方订单已成功配送。";
//            remark = "感谢您的使用。";
//            sendJson.put("keyword1", "续方申请");
            sendJson.put("keyword1", keyword1);
            sendJson.put("keyword2", doctName);//审核医生姓名 开处方的医生(团队长?)
            sendJson.put("keyword3", ordenTime);//订单完成时间
            sendJson.put("first", first);

+ 31 - 18
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionService.java

@ -83,6 +83,8 @@ public class PrescriptionService extends BaseService {
    private MessageService messageService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PrescriptionLogService payLogService;
    //健康问题 高血压
    private static final String gxy = "HP0093";
    //健康问题 糖尿病
@ -117,19 +119,30 @@ public class PrescriptionService extends BaseService {
            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
            if (type == 1){
                int status = prescription.getStatus();
                if (!(status>=60 && status <100)){
                    result.put("code",-1);
                    result.put("msg","该订单未发药,不能确认收药");
                    return  result;
                }
                //直接更改状态为已完成
                prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.finish.getValue());
                payLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.patientConfirm.getValue(), 1, 1);
                prescription.setFinishTime(new Date());
            }else if (type == 2){
                //不更改状态只添加延长收药时间
                int extendCount = prescription.getExtendCount();
                if (extendCount>=1){
                Integer extendCount = prescription.getExtendCount();
                if (extendCount !=null && extendCount>=1){
                    result.put("code",-1);
                    result.put("msg","每笔订单只能延长一次");
                   return  result;
                }
                if (extendCount ==null){
                    prescription.setExtendCount(1);
                }else {
                    prescription.setExtendCount(prescription.getExtendCount()+1);
                }
                prescription.setExtendTime(new Date());
                prescription.setExtendCount(prescription.getExtendCount()+1);
            }
            prescriptionDao.save(prescription);
        } catch (Exception e) {
@ -640,7 +653,7 @@ public class PrescriptionService extends BaseService {
        }
        return rsMap;
    }
    
    /**
     * 根据居民CODE,时间轴,就诊类型查询用药记录
     * @param patientCode 居民CODE
@ -649,25 +662,25 @@ public class PrescriptionService extends BaseService {
     * @return
     */
    public String findPatientMedicationRecords(String patientCode, String timeline, String type) throws Exception{
        
        Integer totalCount = 0;
        
        String RECIPE_NO = "";//符合规则基卫处方医嘱号
        
        Patient patient = patientDao.findByCode(patientCode);
        
        if(patient == null){
            throw new Exception("未找到居民!");
        }
        
        String medicationRecords = "";
        
        Date timeLineDate = DateUtil.strToDateShort(timeline);
        Date startTime = DateUtil.setDateTime(timeLineDate,-25);
        Date endTime = DateUtil.setDateTime(timeLineDate,25);
        
        com.alibaba.fastjson.JSONObject re = jwPrescriptionService.getRecipeMasterList(patientCode,DateUtil.dateToStrShort(startTime),DateUtil.dateToStrShort(endTime));
        
        totalCount = re.getInteger("totalCount");
        if(totalCount>0){
            com.alibaba.fastjson.JSONArray pres = re.getJSONArray("list");
@ -677,7 +690,7 @@ public class PrescriptionService extends BaseService {
                boolean flag = false;
                for (int j = 0; j < des.size(); j++) {
                    PrescriptionDiagnosis ds = des.getObject(j, PrescriptionDiagnosis.class);
    
//                    String icdCode = ds.getHealthProblem();
//                    System.out.println(icdCode);
//                    Icd10Dict icd10Dict = icd10DictDao.findByCode(icdCode);
@ -729,13 +742,13 @@ public class PrescriptionService extends BaseService {
                }
            }
        }
        
        if(org.apache.commons.lang.StringUtils.isNotBlank(RECIPE_NO)){
            String response = jwPrescriptionService.getRecipe(RECIPE_NO,patient.getSsc());
            com.alibaba.fastjson.JSONObject jsonObject = presModeAdapter.modelToSinglePrescription(response);
            //药品
            com.alibaba.fastjson.JSONArray infos = jsonObject.getJSONArray("prescriptionInfo");
            
            for(int i=0;i<infos.size();i++){
                com.alibaba.fastjson.JSONObject info = infos.getJSONObject(i);
                String drugname =  info.getString("drugName");
@ -746,10 +759,10 @@ public class PrescriptionService extends BaseService {
                    }
                }
            }
            
        }
        
        
        return medicationRecords;
    }
}

+ 11 - 6
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/reservation/PatientReservationService.java

@ -230,16 +230,19 @@ public class PatientReservationService extends BaseService {
     */
    @Transactional
    public JSONArray getReservationByPatient(String patient, Long teamCode, int page, int pagesize) throws Exception {
        List<PatientReservation> list = new ArrayList<>();
//        List<PatientReservation> list = new ArrayList<>();
        JSONArray array = new JSONArray();
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(page - 1, pagesize, sort);
        Page<Object> result = null;
        if (teamCode != null && teamCode > 0) {//传入医生查询医生帮此患者的预约记录
            list = patientReservationDao.findByPatientAndAdminTeamCode(patient, teamCode, pageRequest);
//            list = patientReservationDao.findByPatientAndAdminTeamCode(patient, teamCode, pageRequest);
            result = patientReservationDao.findByPatientAndAdminTeamCode(patient, teamCode, pageRequest);
        } else {
            list = patientReservationDao.findByPatient(patient, pageRequest);
//            list = patientReservationDao.findByPatient(patient, pageRequest);
            result = patientReservationDao.findByPatient(patient, pageRequest);
        }
        //更新当前状态
@ -262,10 +265,12 @@ public class PatientReservationService extends BaseService {
            patientReservationDao.save(list);
        }*/
//        List<PatientReservation> a = new ArrayList<PatientReservation>(result.getContent());
        List<Object> list = result.getContent();
        if (list != null) {
            Map<String, Doctor> doctors = new HashMap<>();
            for (PatientReservation item : list) {
            for (Object one : list) {
                PatientReservation item = (PatientReservation)one;
                JSONObject obj = new JSONObject(item);
                if (!StringUtils.isEmpty(item.getDoctor())) {
                    if (doctors.get(item.getDoctor()) != null) {
@ -279,7 +284,7 @@ public class PatientReservationService extends BaseService {
                        }
                    }
                }
                obj.put("total",result.getTotalElements());
                array.put(obj);
            }
        }

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

@ -14,6 +14,7 @@ import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.message.MessageNoticeSetting;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
@ -23,6 +24,7 @@ import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.statistics.WlyySignFamilyCodeDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
@ -163,6 +165,8 @@ public class FamilyContractService extends BaseService {
    private HttpClientUtil httpClientUtil;
    @Autowired
    private TrackPatientDao trackPatientDao;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    public SignFamily findSignFamilyByCode(String code) {
@ -1254,17 +1258,24 @@ public class FamilyContractService extends BaseService {
            Doctor doc = doctorDao.findByCode(sf.getDoctor());
            Hospital hos = hospitalDao.findByCode(doc.getHospital());
            String content = sf.getName() + ",您好!祝贺您,成功签约" + sf.getDoctorName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success", "self");
            String first = templateConfig.getFirst();
            String keyword4 = templateConfig.getKeyword4();
            keyword4 = keyword4.replace("key1",sf.getName()==null?"":sf.getName()).replace("key2",sf.getDoctorName()==null?"":sf.getDoctorName())
                        .replace("key3",(hos != null ? hos.getName() : "") ).replace("key4",(hos != null ? hos.getAddress() : ""));
            /*String content = sf.getName() + ",您好!祝贺您,成功签约" + sf.getDoctorName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                    "为了给您提供更好的服务,请尽快完成缴费。您可点击此条消息,跳转缴费页面完成缴费,或进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + (hos != null ? hos.getName() : "") + "社区(地址:" +
                    (hos != null ? hos.getAddress() : "") + ")缴费。";
                    (hos != null ? hos.getAddress() : "") + ")缴费。";*/
            JSONObject json = new JSONObject();
            json.put("first", "签约成功通知");
            json.put("first", first);
            json.put("toUser", sf.getPatient());
            json.put("represented", sf.getPatient());//被代理人
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(sf.getBegin()));
            json.put("content", content);
            json.put("content", keyword4);
            json.put("remark", ""); //您好,您成功签约家庭医生
//            添加签约code by wjj  2017.7.18
            json.put("signCode", signCode);
@ -1272,21 +1283,9 @@ public class FamilyContractService extends BaseService {
            if (StringUtils.isNotBlank(sf.getOpenid())) {
                // 添加到发送队列
                pushMsgTask.putWxMsg(access_token, 1, sf.getOpenid(), sf.getName(), json);
            }
//            else {
//                JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
//                if (j != null) {
//                    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(patient, j.getInt("relation"), sf.getName()));
//                        pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), sf.getName(), json);
//                    }
//                }
//            }
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
            } else{
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
@ -1299,17 +1298,22 @@ public class FamilyContractService extends BaseService {
                    data.put("represented", member.getCode());
                    data.put("agent", "1");
                    String ms = sf.getName() + ",您好!祝贺您,成功签约" + sf.getDoctorName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                    templateConfig = templateConfigDao.findByScene("template_sign_success", "agent");
                    keyword4 = templateConfig.getKeyword4();
                    keyword4 = keyword4.replace("key1",sf.getName()==null?"":sf.getName()).replace("key2",sf.getDoctorName()==null?"":sf.getDoctorName())
                            .replace("key3",(hos != null ? hos.getName() : "") ).replace("key4",(hos != null ? hos.getAddress() : ""));
                    /*String ms = sf.getName() + ",您好!祝贺您,成功签约" + sf.getDoctorName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                            "为了给您提供更好的服务,请尽快完成缴费。您可登录签约居民的微信账号,进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + (hos != null ? hos.getName() : "") + "社区(地址:" +
                            (hos != null ? hos.getAddress() : "") + ")缴费。";
                            (hos != null ? hos.getAddress() : "") + ")缴费。";*/
                    data.put("content", ms);
                    data.put("content", keyword4);
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()));
                    pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                }
            }
        }
            new Thread(new SignUploadTask(sf.getCode(), httpUtil, jwUrl)).start();
            JSONObject participants = new JSONObject();
@ -1553,9 +1557,16 @@ public class FamilyContractService extends BaseService {
            if (StringUtils.isNotEmpty(refuseReason)){
                sf.setRefuseSpeak(refuseReason);
            }
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_failed","self");
            String first = templateConfig.getFirst();
            String keyword4 = templateConfig.getKeyword4();
            keyword4 = keyword4.replace("key1",(sf.getName()==null?"":sf.getName())).replace("key2",(StringUtils.isEmpty(sf.getDoctor()) ? sf.getDoctorHealthName() : sf.getDoctorName()));
            String remark = templateConfig.getRemark();
            // 拒绝签约
            JSONObject json = new JSONObject();
            json.put("first", "签约失败通知");
            json.put("first",first);
            json.put("toUser", sf.getPatient());
            json.put("represented", sf.getPatient());//被代理人
            json.put("doctor", StringUtils.isEmpty(sf.getDoctor()) ? sf.getDoctorHealth() : sf.getDoctor());
@ -1563,27 +1574,18 @@ public class FamilyContractService extends BaseService {
            json.put("signCode", sf.getCode());
            json.put("doctorName", StringUtils.isEmpty(sf.getDoctor()) ? sf.getDoctorHealthName() : sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(new Date()));
            json.put("content", sf.getName() + ",您好!您与 " + (StringUtils.isEmpty(sf.getDoctor()) ? sf.getDoctorHealthName() : sf.getDoctorName()) + " 医生建立家庭医生签约关系失败,请查看!");
//            json.put("content", sf.getName() + ",您好!您与 " + (StringUtils.isEmpty(sf.getDoctor()) ? sf.getDoctorHealthName() : sf.getDoctorName()) + " 医生建立家庭医生签约关系失败,请查看!");
            json.put("content", keyword4);
            if (StringUtils.isNotEmpty(refuseReason)){
                json.put("remark", refuseReason);
            }else {
                json.put("remark", "您好,签约家庭医生失败通知");
                json.put("remark", remark);
            }
            if (StringUtils.isNotBlank(sf.getOpenid())) {
                // 添加到发送队列
                pushMsgTask.putWxMsg(access_token, 2, sf.getOpenid(), sf.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"), p.getName()));
//                    pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), p.getName(), json);
//                }
//            }
            }else{
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
@ -1599,6 +1601,7 @@ public class FamilyContractService extends BaseService {
                    pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), p.getName(), data);
                }
            }
        }
            result.put("status", 2);
@ -1616,18 +1619,25 @@ public class FamilyContractService extends BaseService {
            Doctor doc = doctorDao.findByCode(StringUtils.isNotEmpty(doctor) ? sf.getDoctorHealth() : sf.getDoctor());
            Hospital hos = hospitalDao.findByCode(doc.getHospital());
            String content = sf.getName() + ",您好!祝贺您,成功签约" + doc.getName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success", "self");
            String first = templateConfig.getFirst();
            String keyword4 = templateConfig.getKeyword4();
            keyword4 = keyword4.replace("key1",sf.getName()==null?"":sf.getName()).replace("key2",sf.getDoctorName()==null?"":sf.getDoctorName())
                    .replace("key3",(hos != null ? hos.getName() : "") ).replace("key4",(hos != null ? hos.getAddress() : ""));
            /*String content = sf.getName() + ",您好!祝贺您,成功签约" + doc.getName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                    "为了给您提供更好的服务,请尽快完成缴费。您可点击此条消息,跳转缴费页面完成缴费,或进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + (hos != null ? hos.getName() : "") + "社区(地址:" +
                    (hos != null ? hos.getAddress() : "") + ")缴费。";
                    (hos != null ? hos.getAddress() : "") + ")缴费。";*/
            // 同意签约
            JSONObject json = new JSONObject();
            json.put("first", "签约成功通知");
            json.put("first", first);
            json.put("toUser", sf.getPatient());
            json.put("represented", sf.getPatient());//被代理人
            json.put("doctor", doc.getCode());
            json.put("doctorName", doc.getName());
            json.put("date", DateUtil.dateToStrShort(new Date()));
            json.put("content", content);
//            json.put("content", content);
            json.put("content", keyword4);
            json.put("remark", ""); //您好,您成功签约家庭医生
//            添加签约code by wjj 2017.7.18
            json.put("signCode", sf.getCode()); //签约code
@ -1635,38 +1645,34 @@ public class FamilyContractService extends BaseService {
            // 添加到发送队列
            if (StringUtils.isNotBlank(sf.getOpenid())) {
                pushMsgTask.putWxMsg(access_token, 1, sf.getOpenid(), sf.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"), p.getName()));
//                    pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), p.getName(), json);
//                }
//            }
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.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;
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.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.remove("agent");
                        data.remove("agent");
//                    data.put("toUser", member.getCode());
                    data.put("agent", "1");
                    data.remove("represented");
                    data.put("represented", member.getCode());
                    String ms = sf.getName() + ",您好!祝贺您,成功签约" + doc.getName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                            "为了给您提供更好的服务,请尽快完成缴费。您可登录签约居民的微信账号,进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + (hos != null ? hos.getName() : "") + "社区(地址:" +
                            (hos != null ? hos.getAddress() : "") + ")缴费。";
                    data.put("content", ms);
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                    pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), p.getName(), data);
                        data.put("agent", "1");
                        data.remove("represented");
                        data.put("represented", member.getCode());
                        /*String ms = sf.getName() + ",您好!祝贺您,成功签约" + doc.getName() + "医生团队,您已可以享受家庭医生所带来的无微不至的健康保健服务。" +
                                "为了给您提供更好的服务,请尽快完成缴费。您可登录签约居民的微信账号,进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + (hos != null ? hos.getName() : "") + "社区(地址:" +
                                (hos != null ? hos.getAddress() : "") + ")缴费。";*/
                        templateConfig = templateConfigDao.findByScene("template_sign_success", "agent");
                        keyword4 = templateConfig.getKeyword4();
                        keyword4 = keyword4.replace("key1",sf.getName()==null?"":sf.getName()).replace("key2",sf.getDoctorName()==null?"":sf.getDoctorName())
                                .replace("key3",(hos != null ? hos.getName() : "") ).replace("key4",(hos != null ? hos.getAddress() : ""));
                        data.put("content", keyword4);
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), p.getName(), data);
                    }
                }
            }
@ -1737,91 +1743,82 @@ public class FamilyContractService extends BaseService {
            //结束患者家庭签约咨询
            consultTeamDao.updateStatusByPatient(patient);
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_termination","jycg");
            String first = templateConfig.getFirst();
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(sf.getName()==null?"":sf.getName()));
            // 推送消息消息给微信端
            JSONObject json = new JSONObject();
            json.put("first", "解约申请通知");
            json.put("first", first);
            json.put("toUser", sf.getPatient());
            json.put("represented", sf.getPatient());//被代理人
            json.put("date", DateUtil.getStringDateShort());
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("orgName", sf.getHospitalName());
            json.put("remark", sf.getName() + ",您好!您的签约医生已同意您的解约申请,解约已生效。");
//            json.put("remark", sf.getName() + ",您好!您的签约医生已同意您的解约申请,解约已生效。");
            json.put("remark", remark);
            if (StringUtils.isNotBlank(sf.getOpenid())) {
                // 添加到发送队列
                pushMsgTask.putWxMsg(access_token, 5, sf.getOpenid(), sf.getName(), json);
            }
//            else {
//                JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient);
//                Patient member = (Patient) j.get("member");
//                if (StringUtils.isNotBlank(member.getOpenid())) {
//                    String first = (String) json.get("first");
//                    json.remove("first");
//                    Patient p = patientDao.findByCode(patient);
//                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
//                    pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), member.getName(), json);
//                }
//            }
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                Patient p = patientDao.findByCode(patient);
                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());
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                    pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), p.getName(), data);
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    Patient p = patientDao.findByCode(patient);
                    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());
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), p.getName(), data);
                    }
                }
            }
        } else {
            // 更新状态为正常
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_termination","jysb");
            String first = templateConfig.getFirst();
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(sf.getName()==null?"":sf.getName()));
            signFamilyDao.refuseSurrender(patient);
            // 拒绝解约,推送消息消息给微信端
            JSONObject json = new JSONObject();
            json.put("first", "解约申请通知");
            json.put("first", first);
            json.put("toUser", sf.getPatient());
            json.put("represented", sf.getPatient());//被代理人
            json.put("date", DateUtil.getStringDateShort());
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("orgName", sf.getHospitalName());
            json.put("remark", sf.getName() + ",您好!您的签约医生拒绝您的解约申请,解约失败。");
//            json.put("remark", sf.getName() + ",您好!您的签约医生拒绝您的解约申请,解约失败。");
            json.put("remark", remark);
            if (StringUtils.isNotBlank(sf.getOpenid())) {
                // 添加到发送队列
                pushMsgTask.putWxMsg(access_token, 5, sf.getOpenid(), sf.getName(), json);
            }
//            else {
//                JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient);
//                Patient member = (Patient) j.get("member");
//                if (StringUtils.isNotBlank(member.getOpenid())) {
//                    String first = (String) json.get("first");
//                    json.remove("first");
//                    Patient p = patientDao.findByCode(patient);
//                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()));
//                    pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), member.getName(), json);
//                }
//            }
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
            if (jsonArray != null && jsonArray.length() > 0) {
                Patient p = patientDao.findByCode(patient);
                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());
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                    pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), p.getName(), data);
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(sf.getPatient(), sf.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    Patient p = patientDao.findByCode(patient);
                    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());
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(access_token, 5, member.getOpenid(), p.getName(), data);
                    }
                }
            }
@ -2332,22 +2329,38 @@ public class FamilyContractService extends BaseService {
                    doctorTeamDoctor.save(teamMember);
                }
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsbg");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(p.getName()==null?"":p.getName()));
                String keyword3 = templateConfig.getKeyword3();
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(docHealth.getName()==null?"":docHealth.getName()));
                JSONObject data = new JSONObject();
                data.put("toUser", patient);
                data.put("represented", patient);//被代理人
                data.put("doctor", docHealth.getCode());
                data.put("doctorName", docHealth.getName());
                data.put("first", p.getName() + ",您好!您签约团队的健康管理师已变更,您的新健管师信息如下:");
                data.put("keyword3", "家庭医生-健康管理师");
//                data.put("first", p.getName() + ",您好!您签约团队的健康管理师已变更,您的新健管师信息如下:");
                data.put("first", first);
                data.put("keyword3", keyword3);
                data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
                data.put("keyword1", docHealth.getName());
                if (StringUtils.isEmpty(signFamily.getDoctor()) || docHealth.getCode().equals(signFamily.getDoctor())) {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
                data.put("remark", remark);
                /*if (StringUtils.isEmpty(signFamily.getDoctor()) || docHealth.getCode().equals(signFamily.getDoctor())) {
                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                } else {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
                }
                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                }*/
                wxMessages.add(data);
            } else {
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxz");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(p.getName()==null?"":p.getName()));
                String keyword3 = templateConfig.getKeyword3();
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(docHealth.getName()==null?"":docHealth.getName()));
                JSONObject data = new JSONObject();
                data.put("toUser", patient);
                data.put("represented", patient);//被代理人
@ -2358,9 +2371,14 @@ public class FamilyContractService extends BaseService {
                data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
                data.put("keyword1", docHealth.getName());
                if (StringUtils.isEmpty(signFamily.getDoctor()) || docHealth.getCode().equals(signFamily.getDoctor())) {
                    data.put("remark", docHealth.getName() + "医生将继续为您提供优质健康服务");
//                    data.put("remark", docHealth.getName() + "健管师将继续为您提供优质健康服务");
                    data.put("remark", remark);
                } else {
                    data.put("remark", docHealth.getName() + "医生与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                    templateConfig = templateConfigDao.findByScene("template_doctor_change","jgsxzqk");
                    remark = templateConfig.getRemark();
                    remark = remark.replace("key1",(docHealth.getName()==null?"":docHealth.getName())).replace("key2",(signFamily.getDoctorName()==null?"":signFamily.getDoctorName()));
                    data.put("remark", remark);
//                    data.put("remark", docHealth.getName() + "健管师与" + signFamily.getDoctorName() + "医生一道,为您提供优质健康服务");
                }
                wxMessages.add(data);
                try {
@ -2448,20 +2466,29 @@ public class FamilyContractService extends BaseService {
            signFamily.setDoctorName(docQk.getName());
            signFamily.setCzrq(new Date());
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(p.getName()==null?"":p.getName()));
            String keyword3 = templateConfig.getKeyword3();
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(docQk.getName()==null?"":docQk.getName()));
            JSONObject data = new JSONObject();
            data.put("toUser", patient);
            data.put("represented", patient);//被代理人
            data.put("doctor", docQk.getCode());
            data.put("doctorName", docQk.getName());
            data.put("first", p.getName() + ",您好!您签约团队的全科医生已变更,您的新全科医生信息如下:");
            data.put("keyword3", "家庭医生-全科医生");
//            data.put("first", p.getName() + ",您好!您签约团队的全科医生已变更,您的新全科医生信息如下:");
            data.put("first", first);
            data.put("keyword3", keyword3);
            data.put("keyword2", DateUtil.dateToStrNoSecond(new Date()));
            data.put("keyword1", docQk.getName());
            if (StringUtils.isEmpty(signFamily.getDoctorHealth()) || signFamily.getDoctor().equals(signFamily.getDoctorHealth())) {
            data.put("remark", remark);
            /*if (StringUtils.isEmpty(signFamily.getDoctorHealth()) || signFamily.getDoctor().equals(signFamily.getDoctorHealth())) {
                data.put("remark", docQk.getName() + "医生将专门为您提供优质健康服务");
            } else {
                data.put("remark", docQk.getName() + "医生将继续为您提供优质健康服务");
            }
            }*/
            wxMessages.add(data);
        }
@ -2482,36 +2509,21 @@ public class FamilyContractService extends BaseService {
            if (StringUtils.isNotBlank(p.getOpenid())) {
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, p.getOpenid(), p.getName(), msg);
            }
//            else {
//                //如果自己没有绑定,则发给家人
//                JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getCode());
//                Patient member = (Patient) j.get("member");
//                if (StringUtils.isNotBlank(member.getOpenid())) {
//                    String first = (String) msg.get("first");
//                    msg.remove("first");
//
//                    try {
//                        msg.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), member.getName(), msg);
//                }
//            }
            //发送代理人
            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 = msg;
                    data.remove("toUser");
                    data.put("toUser", member.getCode());
                    String first = (String) data.get("first");
                    data.remove("first");
                    data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), data);
            }else {
                //发送代理人
                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 = msg;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        String first = (String) data.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 10, member.getOpenid(), p.getName(), data);
                    }
                }
            }

+ 34 - 21
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/PatientRemindService.java

@ -4,10 +4,12 @@ import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.common.SMSService;
@ -62,6 +64,8 @@ public class PatientRemindService extends BaseService {
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
     * 缴费提醒
     *
@ -224,6 +228,12 @@ public class PatientRemindService extends BaseService {
                }
            }
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_expenses_remind","jftx");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(doc.getName()==null?"":doc.getName()));
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(p.getName()==null?"":p.getName())).replace("key2",(hos.getName()==null?"":hos.getName()))
                            .replace("key3",(hos.getAddress()==null?"":hos.getAddress()));
            // 微信提醒
            JSONObject json = new JSONObject();
            json.put("first", "缴费提醒");
@ -231,9 +241,11 @@ public class PatientRemindService extends BaseService {
            json.put("represented",p.getCode());//被代理人
            json.put("name", p.getName());
            json.put("doctor", doc.getCode());
            json.put("doctorName", "提醒医生:  "+doc.getName());
//            json.put("doctorName", "提醒医生:  "+doc.getName());
            json.put("doctorName", first);
            json.put("date", DateUtil.dateToStrShort(new Date()));
            json.put("content", p.getName() + ",您好!为完成家庭医生签约,尽早为您提供家庭医生服务,请尽快到" + hos.getName() + "(地址:" + hos.getAddress() + ")缴费");
//            json.put("content", p.getName() + ",您好!为完成家庭医生签约,尽早为您提供家庭医生服务,请尽快到" + hos.getName() + "(地址:" + hos.getAddress() + ")缴费");
            json.put("content", remark);
            json.put("remark", "");
            //判断是否判定openId,有没有发则查找家人发送
@ -242,29 +254,30 @@ public class PatientRemindService extends BaseService {
                // 添加到发送队列
                pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, p.getOpenid(), p.getName(), json);
                wFlag = true;
            }
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
            if(jsonArray!=null&&jsonArray.length()>0){
                String first = (String) json.get("doctorName");
                for (int i = 0;i<jsonArray.length();i++){
                    JSONObject j  = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    isOpenIdExist = true;
                    JSONObject data = json;
                    data.remove("toUser");
                    data.put("toUser",member.getCode());
                    data.remove("doctorName");
                    data.put("doctorName", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) +"\n"+first);
                    pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                    wFlag = true;
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    first = (String) json.get("doctorName");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        isOpenIdExist = true;
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        data.remove("doctorName");
                        data.put("doctorName", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + "\n" + first);
                        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                        wFlag = true;
                    }
                }
            }
            //发送IM
            consultService.sendMucMessageBySingnType(doc.getCode(), doc.getName(), p.getCode(), doc.getName() + "医生提醒您:为完成家庭医生签约," +
                    "尽早为您提供家庭医生服务,请尽快到" + hos.getName() + "(地址:" + hos.getAddress() + ")缴费", "1",p.getName());
          /*  consultService.sendMucMessageBySingnType(doc.getCode(), doc.getName(), p.getCode(), doc.getName() + "医生提醒您:为完成家庭医生签约," +
                    "尽早为您提供家庭医生服务,请尽快到" + hos.getName() + "(地址:" + hos.getAddress() + ")缴费", "1",p.getName());*/
            consultService.sendMucMessageBySingnType(doc.getCode(), doc.getName(), p.getCode(), doc.getName() + "医生提醒您:"+remark, "1",p.getName());
            if (wFlag || mFlag) {
                reObj.put("status", 200);

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

@ -12,6 +12,7 @@ import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.*;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.address.CountryDao;
import com.yihu.wlyy.repository.address.StreetDao;
import com.yihu.wlyy.repository.address.TownDao;
@ -24,6 +25,7 @@ import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
@ -126,6 +128,8 @@ public class SignWebService extends BaseService {
    private String esIndex;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
     * 厦门市
     */
@ -1424,35 +1428,47 @@ public class SignWebService extends BaseService {
                String openid = (String) signFamily.get("openid");
                String name = (String) signFamily.get("name");
                String doctorName = (String) signFamily.get("doctorName");
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xqtx");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(name==null?"":name)).replace("br","\n");
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(doctorName==null?"":doctorName)).replace("br","\n");
                String keyword1 = templateConfig.getKeyword1();
                JSONObject json = new JSONObject();
                String patient = (String) signFamily.get("code");
                json.put("toUser", patient);
                json.put("represented", patient);//被代理人
                json.put("keyword1", "续签家庭医生");
                json.put("keyword1", keyword1);
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark", "提醒医生 :" + doctorName + "\n"
                        + "我们将继续为您提供优质的健康服务。");
                json.put("remark", remark);
                json.put("first", first);
                if (StringUtils.isNotBlank(openid)) {
                    flag = false;
                    json.put("first", name + ",您好!\n" +
                            "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                    /*json.put("first", name + ",您好!\n" +
                            "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
                    pushMsgTask.putWxMsg(access_token, 16, openid, name, json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                if (jsonArray != null && jsonArray.length() > 0) {
                    Patient p = patientService.findByCode(patient);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        flag = false;
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                name + ",您好!\n" +
                                "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                        pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                    if (jsonArray != null && jsonArray.length() > 0) {
                        Patient p = patientService.findByCode(patient);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            flag = false;
                            JSONObject j = jsonArray.getJSONObject(i);
                            Patient member = (Patient) j.get("member");
                            JSONObject data = json;
                            data.remove("toUser");
                            data.put("toUser", member.getCode());
                            /*json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                    name + ",您好!\n" +
                                    "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +first);
                            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                        }
                    }
                }
@ -1528,40 +1544,53 @@ public class SignWebService extends BaseService {
        List<Map<String, Object>> signFamilies = jdbcTemplate.queryForList(sql);
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xqtx");
        if (signFamilies != null && signFamilies.size() > 0) {
            for (Map<String, Object> signFamily : signFamilies) {
                String openid = (String) signFamily.get("openid");
                String name = (String) signFamily.get("name");
                String doctorName = (String) signFamily.get("doctorName");
                String first = templateConfig.getFirst();
                first = first.replace("key1",(name==null?"":name)).replace("br","\n");
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(doctorName==null?"":doctorName)).replace("br","\n");
                String keyword1 = templateConfig.getKeyword1();
                JSONObject json = new JSONObject();
                Boolean flag = true;
                String patient = (String) signFamily.get("code");
                json.put("toUser", patient);
                json.put("represented", patient);//被代理人
                json.put("keyword1", "续签家庭医生");
                json.put("keyword1", keyword1);
                json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                json.put("remark", "提醒医生 :" + doctorName + "\n"
                        + "我们将继续为您提供优质的健康服务。");
                json.put("remark", remark);
                json.put("first", first);
                if (StringUtils.isNotBlank(openid)) {
                    json.put("first", name + ",您好!\n" +
                            "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                    /*json.put("first", name + ",您好!\n" +
                            "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
                    pushMsgTask.putWxMsg(access_token, 16, openid, name, json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                if (jsonArray != null && jsonArray.length() > 0) {
                    Patient p = patientService.findByCode(patient);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        flag = false;
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                name + ",您好!\n" +
                                "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                        pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                    if (jsonArray != null && jsonArray.length() > 0) {
                        Patient p = patientService.findByCode(patient);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            flag = false;
                            JSONObject j = jsonArray.getJSONObject(i);
                            Patient member = (Patient) j.get("member");
                            JSONObject data = json;
                            data.remove("toUser");
                            data.put("toUser", member.getCode());
                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +first);
                            /*json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                                    name + ",您好!\n" +
                                    "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
                            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
                        }
                    }
                }
                if (flag) {
@ -1667,7 +1696,7 @@ public class SignWebService extends BaseService {
                JSONObject data = new JSONObject();
                data.put("doctorName", renew.getDoctorName());
                data.put("date", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                data.put("content", "家庭医生续签");
//                data.put("content", "家庭医生续签");
                data.put("doctor", dotorCode);
                data.put("represented", patientCode);
                data.put("toUser", patientCode);
@ -1681,64 +1710,82 @@ public class SignWebService extends BaseService {
                if (patient != null && StringUtils.isNotBlank(patient.getOpenid())) {
                    if ("0".equals(state)) {
                        data.put("first", renew.getName() + ",您好!\n" +
                        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_failed","failed");
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(renew.getName()==null?"":renew.getName())).replace("br","\n");
                        String remark = templateConfig.getRemark();
                        String keyword4 = templateConfig.getKeyword4();
                        /*data.put("first", renew.getName() + ",您好!\n" +
                                "您的家庭医生续签申请已被拒绝");
                        data.put("remark", "您可选择其他医生进行签约。");
                        data.put("remark", "您可选择其他医生进行签约。");*/
                        data.put("first", first);
                        data.put("remark", remark);
                        data.put("content", keyword4);
                        pushMsgTask.putWxMsg(access_token, 2, patient.getOpenid(), patient.getName(), data);
                    } else if ("1".equals(state)) {
                        data.put("first", renew.getName() + ",您好!\n" +
                        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success","success");
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(renew.getName()==null?"":renew.getName())).replace("br","\n");
                        String remark = templateConfig.getRemark();
                        String keyword4 = templateConfig.getKeyword4();
                        data.put("first", first);
                        data.put("remark", remark);
                        data.put("content", keyword4);
                        /*data.put("first", renew.getName() + ",您好!\n" +
                                "您的家庭医生续签申请已通过");
                        data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
                        data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");*/
                        pushMsgTask.putWxMsg(access_token, 1, patient.getOpenid(), patient.getName(), data);
                    }
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        //String first = (String) json.get("first");
                        if ("0".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + ",您好!\n" +
                                    "您的家庭医生续签申请已被拒绝");
                            data.put("remark", "您可选择其他医生进行签约。");
                            pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                        } else if ("1".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + ",您好!\n" +
                                    "您的家庭医生续签申请已通过");
                            data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
                            pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                }else {
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
                    if (jsonArray != null && jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject j = jsonArray.getJSONObject(i);
                            Patient member = (Patient) j.get("member");
                            data.remove("toUser");
                            data.put("toUser", member.getCode());
                            //String first = (String) json.get("first");
                            if ("0".equals(state)) {
                                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_failed","failed");
                                String first = templateConfig.getFirst();
                                first = first.replace("key1",(patient.getName()==null?"":patient.getName())).replace("br","\n");
                                String remark = templateConfig.getRemark();
                                String keyword4 = templateConfig.getKeyword4();
                                data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" + first);
                                data.put("remark", remark);
                                data.put("content", keyword4);
                                /*data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                        patient.getName() + ",您好!\n" +
                                        "您的家庭医生续签申请已被拒绝");
                                data.put("remark", "您可选择其他医生进行签约。");*/
                                pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                            } else if ("1".equals(state)) {
                                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success","success");
                                String first = templateConfig.getFirst();
                                first = first.replace("key1",(patient.getName()==null?"":patient.getName())).replace("br","\n");
                                String remark = templateConfig.getRemark();
                                String keyword4 = templateConfig.getKeyword4();
                                data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" + first);
                                data.put("remark", remark);
                                data.put("content", keyword4);
                                /*data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                        patient.getName() + ",您好!\n" +
                                        "您的家庭医生续签申请已通过");
                                data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");*/
                                pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                            }
                        }
                    }
                }
//                else {
//                    //如果自己没有绑定,则发给家人
//                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
//                    Patient member = (Patient) j.get("member");
//                    if (StringUtils.isNotBlank(member.getOpenid())) {
//
//                        if ("0".equals(state)) {
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
//                                    patient.getName() + ",您好!\n" +
//                                    "您的家庭医生续签申请已被拒绝");
//                            data.put("remark", "您可选择其他医生进行签约。");
//                            pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
//                        } else if ("1".equals(state)) {
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
//                                    patient.getName() + ",您好!\n" +
//                                    "您的家庭医生续签申请已通过");
//                            data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
//                            pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
//                        }
//                    }
//                }
                //-1患者已取消,-2已拒绝,-3已解约,-4已到期,0待签约,1已签约,2患者申请取消签约,3医生申请取消签约
            } else if (status == 1) {
                //已经同意
@ -1851,64 +1898,76 @@ public class SignWebService extends BaseService {
                        }else {
                            data.put("content", "家庭医生续签");
                        }
                        data.put("first", renew.getName() + ",您好!\n" +
                        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_failed","failed");
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(renew.getName()==null?"":renew.getName())).replace("br","\n");
                        String remark = templateConfig.getRemark();
                        data.put("first", first);
                        data.put("remark", remark);
                        /*data.put("first", renew.getName() + ",您好!\n" +
                                "您的家庭医生续签申请已被拒绝");
                        data.put("remark", "您可在到期后选择其他医生进行签约。");
                        data.put("remark", "您可在到期后选择其他医生进行签约。");*/
                        pushMsgTask.putWxMsg(access_token, 2, patient.getOpenid(), patient.getName(), data);
                    } else if ("1".equals(state)) {
                        data.put("content", "家庭医生续签");
                        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success","success");
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(renew.getName()==null?"":renew.getName())).replace("br","\n");
                        String remark = templateConfig.getRemark();
                        String keyword4 = templateConfig.getKeyword4();
                        data.put("first", first);
                        data.put("remark", remark);
                        data.put("content", keyword4);
                        /*data.put("content", "家庭医生续签");
                        data.put("first", renew.getName() + ",您好!\n" +
                                "您的家庭医生续签申请已通过");
                        data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
                        data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");*/
                        pushMsgTask.putWxMsg(access_token, 1, patient.getOpenid(), patient.getName(), data);
                    }
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        //String first = (String) json.get("first");
                        if ("0".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + ",您好!\n" +
                                    "您的家庭医生续签申请已被拒绝");
                            data.put("remark", "您可在到期后选择其他医生进行签约。");
                            pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                        } else if ("1".equals(state)) {
                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                    patient.getName() + ",您好!\n" +
                                    "您的家庭医生续签申请已通过");
                            data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
                            pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                }else {
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
                    if (jsonArray != null && jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject j = jsonArray.getJSONObject(i);
                            Patient member = (Patient) j.get("member");
                            data.remove("toUser");
                            data.put("toUser", member.getCode());
                            //String first = (String) json.get("first");
                            if ("0".equals(state)) {
                                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_failed","failed");
                                String first = templateConfig.getFirst();
                                first = first.replace("key1",(patient.getName()==null?"":patient.getName())).replace("br","\n");
                                String remark = templateConfig.getRemark();
                                data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" + first);
                                data.put("remark", remark);
                                /*data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                        patient.getName() + ",您好!\n" +
                                        "您的家庭医生续签申请已被拒绝");
                                data.put("remark", "您可在到期后选择其他医生进行签约。");*/
                                pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
                            } else if ("1".equals(state)) {
                                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_sign_success","success");
                                String first = templateConfig.getFirst();
                                first = first.replace("key1",(patient.getName()==null?"":patient.getName())).replace("br","\n");
                                String remark = templateConfig.getRemark();
                                data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" + first);
                                data.put("remark", remark);
                                /*data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
                                        patient.getName() + ",您好!\n" +
                                        "您的家庭医生续签申请已通过");
                                data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");*/
                                pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
                            }
                        }
                    }
                }
//                else {
//                    //如果自己没有绑定,则发给家人
//                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
//                    Patient member = (Patient) j.get("member");
//                    if (StringUtils.isNotBlank(member.getOpenid())) {
//
//                        if ("0".equals(state)) {
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
//                                    patient.getName() + ",您好!\n" +
//                                    "您的家庭医生续签申请已被拒绝");
//                            data.put("remark", "您可在到期后选择其他医生进行签约。");
//                            pushMsgTask.putWxMsg(access_token, 2, member.getOpenid(), patient.getName(), data);
//                        } else if ("1".equals(state)) {
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(patient, (int) j.get("relation"), patient.getName()) + "\n" +
//                                    patient.getName() + ",您好!\n" +
//                                    "您的家庭医生续签申请已通过");
//                            data.put("remark", "待自动扣费成功后,家庭医生将续签成功。");
//                            pushMsgTask.putWxMsg(access_token, 1, member.getOpenid(), patient.getName(), data);
//                        }
//                    }
//                }
            } else if (status == 1) {
                //已经同意
                return 2;
@ -2101,39 +2160,52 @@ public class SignWebService extends BaseService {
        }
        //发送微信模板消息
        Patient p = patientService.findByCode(patientCode);
        String openid = p.getOpenid();
        String name = p.getName();
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","xqtx");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(name==null?"":name)).replace("br","\n");
        String remark = templateConfig.getRemark();
        remark = remark.replace("key1",(d.getName()==null?"":d.getName())).replace("br","\n");
        String keyword1 = templateConfig.getKeyword1();
        JSONObject json = new JSONObject();
        json.put("toUser", patientCode);
        json.put("represented", patientCode);//被代理人
        json.put("keyword1", "续签家庭医生");
        json.put("keyword1", keyword1);
        json.put("keyword2", DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
        json.put("remark", "提醒医生 :" + d.getName() + "\n"
                + "我们将继续为您提供优质的健康服务。");
        String openid = p.getOpenid();
        String name = p.getName();
        /*json.put("remark", "提醒医生 :" + d.getName() + "\n"
                + "我们将继续为您提供优质的健康服务。");*/
        json.put("remark", remark);
        boolean flag = true;
        if (StringUtils.isNotBlank(openid)) {
            json.put("first", name + ",您好!\n" +
                    "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
            /*json.put("first", name + ",您好!\n" +
                    "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
            json.put("first", first);
            pushMsgTask.putWxMsg(access_token, 16, openid, name, json);
            patientSetReminFlag(patientCode);
            return 1;
        }
        //发送代理人
        boolean flag = true;
        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patientCode, openid);
        if (jsonArray != null && jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                flag = false;
                JSONObject j = jsonArray.getJSONObject(i);
                Patient member = (Patient) j.get("member");
                JSONObject data = json;
                data.remove("toUser");
                data.put("toUser", member.getCode());
                json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                        name + ",您好!\n" +
                        "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
                pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
        }else {
            //发送代理人
            JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patientCode, openid);
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    flag = false;
                    JSONObject j = jsonArray.getJSONObject(i);
                    Patient member = (Patient) j.get("member");
                    JSONObject data = json;
                    data.remove("toUser");
                    data.put("toUser", member.getCode());
                    /*json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +
                            name + ",您好!\n" +
                            "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");*/
                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()) + "\n" +first);
                    pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 16, member.getOpenid(), p.getName(), data);
                    flag = false;
                }
            }
        }
        if (flag) {
@ -2147,28 +2219,6 @@ public class SignWebService extends BaseService {
        } else {
            return 1;
        }
//        else {
//            //如果自己没有绑定,则发给家人
//            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patientCode);
//            Patient member = (Patient) j.get("member");
//            if (StringUtils.isNotBlank(member.getOpenid())) {
//                json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), name) + "\n" +
//                        name + ",您好!\n" +
//                        "您的家庭医生签约将于6月30日到期,为了能继续给您提供健康服务,诚邀您续签家庭医生。");
//                pushMsgTask.putWxMsg(access_token, 16, member.getOpenid(), name, json);
//                patientSetReminFlag(patientCode);
//                return 1;
//            } else {
//                //发送短信
//                String mobile = p.getMobile();
//                if (StringUtils.isNotBlank(mobile)) {
//                    SMSService.sendMsg(mobile, name + "您好!您的家庭医生将于6月30日到期,为了继续给您提供健康服务,请关注“厦门i健康”公众号,回复“续签”,进行家庭医生线上续签。");
//                    patientSetReminFlag(patientCode);
//                    return 2;
//                }
//            }
//        }
        return -1;
    }

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java

@ -4013,7 +4013,7 @@ public class StatisticsESService {
        Date startDate = DateUtil.getNextMonthReturnDate(endDate, -6);
        startDate = DateUtil.getDateShort(startDate);
        if (interval == 1) {
            rs = DateUtil.findDates(startDate, endDate);
            rs = DateUtil.findDates(startDate, DateUtil.getDateShort(endDate));
            //加入当天数据
            Map<String, Object> dateMap = new HashedMap();
            dateMap.put("date", dateFormat.format(endDate));

+ 9 - 41
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/jimeiJkEdu/JMJkEduArticleService.java

@ -1251,44 +1251,6 @@ public class JMJkEduArticleService extends BaseService {
        }
    }
    /**
     * 查询给患者发送的健康教育文章
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pageSize
     * @return
     */
//    public List<Map<String, Object>> findByPatientAndTeam(String patient, long teamCode, int page, int pageSize) {
//        List<Object> params = new ArrayList<Object>();
//        String sql = "select " +
//                "    a.article" +
//                "    ,b.title" +
//                "    ,b.url" +
//                "    ,a.czrq" +
//                "    ,b.summary content" +
//                "    ,d.code" +
//                "    ,d.name" +
//                "    ,d.photo" +
//                "    ,a.admin_team_code" +
//                "    ,a.is_read" +
//                "    ,a.attached_content" +
//                "  from" +
//                "    wlyy_health_edu_article_patient a" +
//                "    ,wlyy_health_edu_article b" +
//                "    ,wlyy_doctor d" +
//                "  where" +
//                "    a.article = b.code " +
//                "    and a.doctor = d.code " +
//                "   and ( a.send_type =1 or a.send_type is null or a.send_type = '') "+  //添加类型判断是集美的推送还是三师原来的推送
//                "    and a.patient = ?" +
//                "    and a.admin_team_code = ?" +
//                "  order by a.czrq desc limit " + page*pageSize + "," + pageSize;
//
//        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql,new Object[]{patient,teamCode});
//        return result;
//    }
    public List<HealthEduArticleES> findByPatientAndTeam(String patient, long teamCode, int page, int pageSize) {
@ -1313,17 +1275,22 @@ public class JMJkEduArticleService extends BaseService {
    
    
        page = (page - 1) * pagesize;
    
        //查询记录sql
        String sql = "SELECT * FROM " + esType + "  where patientCode= '" + patientCode + "' and adminTeamCode = '"+teamCode+"' and doctorCode='" + uid + "' and userType = 1";
    
        //查询总数sql
        String countSql = "SELECT COUNT(*) AS count FROM " + esType + "  where patientCode= '" + patientCode + "' and adminTeamCode = '"+teamCode+"' and doctorCode='" + uid + "' and userType = 1";
        if(!StringUtils.isEmpty(level1Type)){
            sql= sql + " and firstLevelCategoryId = '"+level1Type+"' ";
            countSql= countSql + " and firstLevelCategoryId = '"+level1Type+"' ";
        }
        sql += " order by createTime desc ";
        if(pagesize !=0){
            sql= sql+  " limit " + page + "," + pagesize;
        }
    
        Long total = elasticsearchUtil.excuteForLong(countSql,esIndex, esType);
        List<HealthEduArticleES> esList = elasticsearchUtil.excute(sql, HealthEduArticleES.class, esIndex, esType);
        HealthEduArticlePatientModel heapm = null;
        JSONObject article = null;
@ -1356,6 +1323,7 @@ public class JMJkEduArticleService extends BaseService {
            heapm.setLeaveWords(one.getLeaveWords());//医生留言
            doctor = doctorDao.findByCode(one.getDoctorCode());
            heapm.setPhoto(doctor.getPhoto());
            heapm.setTotalData(total);
            result.add(heapm);
            // heapm.setTime();//时间  xx小时前  2017-10-11
        }

+ 33 - 35
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/survey/ManagerQuestionnaireService.java

@ -4,9 +4,11 @@ import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.survey.*;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
@ -81,6 +83,8 @@ public class ManagerQuestionnaireService extends BaseService {
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
@ -242,8 +246,9 @@ public class ManagerQuestionnaireService extends BaseService {
        //            发送居民模板 send=1发送
        if ("1".equals(send)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String str = "{\"remark\":\"我们将按调查最终结果,优化健康服务。\",\"keyword1\":\"调查问卷\"}";
            JSONObject json = new JSONObject(str);
//            String str = "{\"remark\":\"我们将按调查最终结果,优化健康服务。\",\"keyword1\":\"调查问卷\"}";
//            JSONObject json = new JSONObject(str);
            JSONObject json = new JSONObject();
 /*           for (String code : codes) {
//            codes.stream().forEach(c -> {
//                Patient p = patientDao.findByCode(c);
@ -281,6 +286,10 @@ public class ManagerQuestionnaireService extends BaseService {
                }
//            });
            }*/
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
            String remark = templateConfig.getRemark();
            String keyword1 = templateConfig.getKeyword1();
            new Thread() {
                public void run() {
                    for (String c : codes) {
@ -291,47 +300,36 @@ public class ManagerQuestionnaireService extends BaseService {
                        json.put("toUser", c);
                        json.put("represented", c);
                        json.put("survey_id", surveyCode);
                        String first = name + ",您好!为了给您提供更好的家庭医生健康服务,现有一份问卷需要您填写。";
//                        String first = name + ",您好!为了给您提供更好的家庭医生健康服务,现有一份问卷需要您填写。";
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(name==null?"":name));
                        json.put("first", first);
                        json.put("remark", remark);
                        json.put("keyword1", keyword1);
                        //判断是否判定openId,有没有发则查找家人发送
                        if (StringUtils.isNotBlank(p.getOpenid())) {
                            // 添加到发送队列
                            logger.error("json =======>" + json);
//                            PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                            pushMsgTask.sendWeixinMessage(accessToken, 11, openId, name, json);
                        }
//                        else {
//                            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
//                            Patient member = (Patient) j.get("member");
//                            if (StringUtils.isNotBlank(member.getOpenid())) {
//                                String first = (String) json.get("first");
//                                json.remove("first");
//                                try {
//                                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                logger.error("没有opIn  json =======>" + json);
////                                PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
//                                PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, 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");
                                if (StringUtils.isNotBlank(member.getOpenid())) {
                                    json.remove("toUser");
                                    json.put("toUser", member.getCode());
                                    json.remove("first");
                                    try {
                                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                        }else {
                            //发送代理人
                            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");
                                    if (StringUtils.isNotBlank(member.getOpenid())) {
                                        json.remove("toUser");
                                        json.put("toUser", member.getCode());
                                        json.remove("first");
                                        try {
                                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        pushMsgTask.sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                    }
                                    pushMsgTask.sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                }
                            }
                        }

+ 13 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java

@ -45,6 +45,8 @@ public class DoctorFeldsherTemplateService extends BaseService {
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private ImUtill imUtill;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    private static final Logger logger = LoggerFactory.getLogger(DoctorFeldsherTemplateService.class);
@ -63,12 +65,20 @@ public class DoctorFeldsherTemplateService extends BaseService {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray jsonArray = null;
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","jcfa");
        String first = templateConfig.getFirst();
        first = first.replace("key1",(name==null?"":name));
        String remark = templateConfig.getRemark();
        String keyword3 = templateConfig.getKeyword3();
        JSONObject sendJson = new JSONObject();
        String first = name + "您好,您的家庭医生已为您设置了血糖(血压)监测方案,请按照方案及时测量及上传您的体征数据。";
        String remark = "您可使用详情查看方案内容";
        /*String first = name + "您好,您的家庭医生已为您设置了血糖(血压)监测方案,请按照方案及时测量及上传您的体征数据。";
        String remark = "您可使用详情查看方案内容";*/
        sendJson.put("keyword1", name);
        sendJson.put("keyword2", dateFormat.format(new Date()));
        sendJson.put("keyword3", "血糖(血压)监测方案");
//        sendJson.put("keyword3", "血糖(血压)监测方案");
        sendJson.put("keyword3", keyword3);
        sendJson.put("first", first);
        sendJson.put("remark", remark);
        sendJson.put("url", url);//带参数的模板跳转链接

+ 56 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/iot/IotDeviceService.java

@ -274,17 +274,70 @@ public class IotDeviceService {
     * @param type
     * @return
     */
    public List<DevicePatientHealthIndex> findByPatientAndType(String patient,Integer type){
    public List<DevicePatientHealthIndex> findByPatientAndType(String patient,Integer type,Integer size){
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",patient,jsonArray);
        field("and","del","=","1",jsonArray);
        field("and","type","=",String.valueOf(type),jsonArray);
        if(type!=null){
            field("and","type","=",String.valueOf(type),jsonArray);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        jsonObject.put("page","1");
        jsonObject.put("size","5");
        jsonObject.put("size",size);
        JSONArray sort = new JSONArray();
        sort(sort,"measure_time","desc");
        jsonObject.put("sort",sort);
        String url = baseUrl+"/dataSearch/getById";
        String response = httpClientUtil.iotPostBody(url, jsonObject.toString());
        try {
            JSONObject json = JSONObject.parseObject(response);
            JSONArray obj = json.getJSONArray("obj");
            if(obj!=null&&obj.size()>0){
                for (int i=0;i<obj.size();i++){
                    DevicePatientHealthIndex index = transforHealthIndex(obj.getJSONObject(i),null);
                    list.add(index);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    /**
     * 按时间段查找
     * @param patient 居民code
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
    public List<DevicePatientHealthIndex> findByPatientAndTime(String patient,Integer type,Integer page,Integer size,Integer gi_type, String begin, String end){
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",patient,jsonArray);
        field("and","del","=","1",jsonArray);
        if(type!=null){
            field("and","type","=",String.valueOf(type),jsonArray);
        }
        if(gi_type!=null){
            field("and","blood_sugar_result","=",String.valueOf(gi_type),jsonArray);
        }
        field("and","measure_time",">=",begin,jsonArray);
        field("and","measure_time","<=",end,jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        jsonObject.put("page",page);
        jsonObject.put("size",size);
        JSONArray sort = new JSONArray();
        sort(sort,"measure_time","desc");

+ 36 - 19
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/task/RemindExpensesTask.java

@ -3,6 +3,8 @@ package com.yihu.wlyy.task;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.DateUtil;
@ -38,6 +40,8 @@ public class RemindExpensesTask implements Runnable {
    private PushMsgTask pushMsgTask;
    private SMSService smsService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    public RemindExpensesTask(List<Patient> patients, Doctor doctor, Hospital hospital,SMSService smsService) {
@ -52,6 +56,10 @@ public class RemindExpensesTask implements Runnable {
    public void run() {
        StringBuffer sb = new StringBuffer();
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_expenses_remind","jftx");
        String first = templateConfig.getFirst();
        String remark = templateConfig.getRemark();
        for (Patient p : patients) {
            try {
                if (StringUtils.isNotEmpty(p.getMobile())) {
@ -60,6 +68,11 @@ public class RemindExpensesTask implements Runnable {
                    }
                    sb.append(p.getMobile());
                }
                first = first.replace("key1",( doctor.getName()==null?"": doctor.getName()));
                remark = remark.replace("key1",(p.getName()==null?"":p.getName())).replace("key2",(hospital.getName()==null?"":hospital.getName()))
                        .replace("key3",(hospital.getAddress()==null?"":hospital.getAddress()));
                // 微信提醒
                JSONObject json = new JSONObject();
                json.put("first", "缴费提醒");
@ -67,39 +80,43 @@ public class RemindExpensesTask implements Runnable {
                json.put("represented",p.getCode());//被代理人
                json.put("name", p.getName());
                json.put("doctor", doctor.getCode());
                json.put("doctorName", doctor.getName());
//                json.put("doctorName", doctor.getName());
                json.put("doctorName", first);
                json.put("date", DateUtil.dateToStrShort(new Date()));
                json.put("content", p.getName() + ",您好!为完成家庭医生签约,尽早为您提供家庭医生服务,请尽快到" + hospital.getName() + "(地址:" + hospital.getAddress() + ")缴费");
//                json.put("content", p.getName() + ",您好!为完成家庭医生签约,尽早为您提供家庭医生服务,请尽快到" + hospital.getName() + "(地址:" + hospital.getAddress() + ")缴费");
                json.put("content", remark);
                json.put("remark", "");
                if (StringUtils.isNotEmpty(p.getOpenid())) {
                    // 添加到发送队列
                    pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, p.getOpenid(), p.getName(), json);
                }
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                if(jsonArray!=null&&jsonArray.length()>0){
                    String first = (String) json.get("doctorName");
                    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("doctorName");
                        data.put("doctorName", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) +"\n"+first);
                        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
                    if (jsonArray != null && jsonArray.length() > 0) {
                        first = (String) json.get("doctorName");
                        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("doctorName");
                            data.put("doctorName", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + "\n" + first);
                            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 8, member.getOpenid(), p.getName(), data);
                        }
                    }
                }
                //发送IM
                consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p.getCode(), doctor.getName() + "医生提醒您:为完成家庭医生签约," +
                        "尽早为您提供家庭医生服务,请尽快到" + doctor.getName() + "(地址:" + hospital.getAddress() + ")缴费", "1", p.getName());
                /*consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p.getCode(), doctor.getName() + "医生提醒您:为完成家庭医生签约," +
                        "尽早为您提供家庭医生服务,请尽快到" + doctor.getName() + "(地址:" + hospital.getAddress() + ")缴费", "1", p.getName());*/
                consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p.getCode(), doctor.getName() + "医生提醒您:" +remark, "1", p.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject result = smsService.sendMsg(sb.toString(), doctor.getName() + "医生提醒您:为完成家庭医生签约," +
                "尽早为您提供家庭医生服务,请尽快到" + hospital.getName() + "(地址:" + hospital.getAddress() + ")缴费");
                "尽早为您提供家庭医生服务,您可登录微信账号,进入签约管理,选择待缴费的签约记录进行缴费操作,如需线下缴费,请尽快到" + hospital.getName() + "(地址:" + hospital.getAddress() + ")缴费");
    }
}

+ 14 - 24
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/consult/DoctorConsultPublicController.java

@ -262,33 +262,23 @@ public class DoctorConsultPublicController extends BaseController {
				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);
				}else {
					//发送代理人
					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("回复成功!");

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

@ -466,27 +466,27 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
                                map.get("openid") == null ? "" : map.get("openid").toString(),
                                map.get("name") == null ? "" : map.get("name").toString(),
                                (JSONObject) map.get("json"));
                    }
                    //发送代理人
                    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);
                    }else {
                        //发送代理人
                        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId((String) map.get("code"), openid);
                        if (jsonArray != null && jsonArray.length() > 0) {
                            Patient p = patientService.findByCode((String) map.get("code"));
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject j = jsonArray.getJSONObject(i);
                                Patient member = (Patient) j.get("member");
                                JSONObject data = (JSONObject) map.get("json");
                                data.remove("toUser");
                                data.put("toUser", member.getCode());
                                String first = (String) data.get("first");
                                data.remove("first");
                                data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.isNull("relation") ? 1 : j.getInt("relation"), p.getName()));
                                if (StringUtils.isNotBlank(member.getOpenid())) {
                                    pushMsgTask.putWxMsg(getAccessToken(), 9, member.getOpenid(), p.getName(), data);
                                }
                            }
                        }
                    }
                }
                for (HealthEduArticlePatient heap : list) {
                    BusinessLogs.info(BusinessLogs.BusinessType.article, getUID(), heap.getPatient(), new JSONObject(heap));

+ 5 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/prescription/PrescriptionInfoController.java

@ -113,6 +113,8 @@ public class PrescriptionInfoController extends BaseController {
        }
    }
    @RequestMapping(value = "/getDoctorPrescription", method = RequestMethod.GET)
    @ApiOperation(value = "获取全科医生/建管师续方列表/搜索")
    public String getDoctorPrescription(@RequestParam(required = false) @ApiParam(value = "团队code", name = "teamCode") Integer teamCode,
@ -123,9 +125,10 @@ public class PrescriptionInfoController extends BaseController {
                                        @RequestParam(required = false) @ApiParam(name = "nameKeyword", value = "患者姓名模糊匹配") String nameKeyword,
                                        @RequestParam(required = false) @ApiParam(name = "patient", value = "患者Code") String patient,
                                        @RequestParam(required = false) @ApiParam(name = "page", value = "起始页") Integer page,
                                        @RequestParam(required = false) @ApiParam(name = "size", value = "每页条数") Integer size) {
                                        @RequestParam(required = false) @ApiParam(name = "size", value = "每页条数") Integer size,
                                        @RequestParam(required = false , defaultValue = "0") @ApiParam(name = "isPcim",value = "是否在pcim上使用,0否1是")String isPcim) {
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getDoctorPrescription(teamCode, state, diseases, startDate, endDate, nameKeyword, patient, page, size));
            return write(200, "查询成功!", "data", prescriptionInfoService.getDoctorPrescription(teamCode, state, diseases, startDate, endDate, nameKeyword, patient, page, size,isPcim));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");

+ 32 - 36
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/survey/ManagerQuestionnaireController.java

@ -2,8 +2,10 @@ package com.yihu.wlyy.web.doctor.survey;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.doctor.SurveyUserDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.survey.ManagerQuestionnaireService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.web.WeixinBaseController;
@ -53,6 +55,8 @@ public class ManagerQuestionnaireController extends WeixinBaseController {
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
     * 获取问卷列表
     *
@ -429,8 +433,9 @@ public class ManagerQuestionnaireController extends WeixinBaseController {
            String accessToken = getAccessToken();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String str = "{\"remark\":\"我们将按调查最终结果,优化健康服务。\",\"keyword1\":\"调查问卷\"}";
            JSONObject json = new JSONObject(str);
//            String str = "{\"remark\":\"我们将按调查最终结果,优化健康服务。\",\"keyword1\":\"调查问卷\"}";
//            JSONObject json = new JSONObject(str);
            JSONObject json = new JSONObject();
           /* codes.stream().forEach(c -> {
                Patient p = patientDao.findByCode(c);
                String name = p.getName();
@ -464,7 +469,9 @@ public class ManagerQuestionnaireController extends WeixinBaseController {
                    }
                }
            });*/
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_change","qkxz");
            String remark = templateConfig.getRemark();
            String keyword1 = templateConfig.getKeyword1();
            new Thread() {
                public void run() {
                    for (String c : codes) {
@ -475,47 +482,36 @@ public class ManagerQuestionnaireController extends WeixinBaseController {
                        json.put("toUser", c);
                        json.put("represented", c);
                        json.put("survey_id", code);
                        String first = name + ",您好!为了给您提供更好的家庭医生健康服务,现有一份问卷需要您填写。";
//                        String first = name + ",您好!为了给您提供更好的家庭医生健康服务,现有一份问卷需要您填写。";
                        String first = templateConfig.getFirst();
                        first = first.replace("key1",(name==null?"":name));
                        json.put("first", first);
                        json.put("remark", remark);
                        json.put("keyword1", keyword1);
                        //判断是否判定openId,有没有发则查找家人发送
                        if (StringUtils.isNotBlank(p.getOpenid())) {
                            // 添加到发送队列
                            logger.error("json =======>" + json);
//                            PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                            pushMsgTask.sendWeixinMessage(accessToken, 11, openId, name, json);
                        }
//                        else {
//                            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
//                            Patient member = (Patient) j.get("member");
//                            if (StringUtils.isNotBlank(member.getOpenid())) {
//                                String first = (String) json.get("first");
//                                json.remove("first");
//                                try {
//                                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                logger.error("没有opIn  json =======>" + json);
////                                PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
//                                PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, 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");
                                if(StringUtils.isNotBlank(member.getOpenid())){
                                    json.remove("toUser");
                                    json.put("toUser",member.getCode());
                                    json.remove("first");
                                    try {
                                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                        }else {
                            //发送代理人
                            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");
                                    if (StringUtils.isNotBlank(member.getOpenid())) {
                                        json.remove("toUser");
                                        json.put("toUser", member.getCode());
                                        json.remove("first");
                                        try {
                                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        pushMsgTask.sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                    }
                                    pushMsgTask.sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                }
                            }
                        }

+ 82 - 65
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/booking/PatientBookingController.java

@ -7,11 +7,13 @@ import com.yihu.wlyy.entity.message.SMS;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientReservation;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.imm.ChildImmuneRegisterRecordDao;
import com.yihu.wlyy.repository.message.SMSDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.organization.HospitalMappingDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.reservation.PatientReservationService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.imm.ChildInfoService;
@ -84,6 +86,8 @@ public class PatientBookingController extends WeixinBaseController{
    private SMSDao smsDao;
    @Autowired
    private ChildImmuneRegisterRecordDao childImmuneRegisterRecordDao;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @RequestMapping(value = "CancelOrder", method = RequestMethod.POST)
@ -118,6 +122,11 @@ public class PatientBookingController extends WeixinBaseController{
//                patientReservationService.patientCancelOrder(orderId,getUID());//"9aa5c557e06a4324911487a035195545"
                //微信消息
                Patient p = patientService.findByCode(obj.getPatient());
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_failed","qxgh");
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(obj.getName()==null?"":obj.getName())).replace("key2",(obj.getStartTime()==null?"":obj.getStartTime()+""))
                             .replace("br","\n");
                if (StringUtils.isNotEmpty(p.getOpenid())) {
                    JSONObject json = new JSONObject();
                    json.put("first", "");
@ -127,36 +136,28 @@ public class PatientBookingController extends WeixinBaseController{
                    json.put("date", obj.getStartTime());
                    json.put("doctorName", obj.getDoctorName());
                    json.put("orgName", obj.getOrgName());
                    json.put("remark", obj.getName() + ",您好!\n您已取消了" + obj.getStartTime() + "的挂号!");
//                    json.put("remark", obj.getName() + ",您好!\n您已取消了" + obj.getStartTime() + "的挂号!");
                    json.put("remark", remark);
                    //判断是否判定openId,有没有发则查找家人发送
                    if(StringUtils.isNotBlank(p.getOpenid())){
                        // 添加到发送队列
                        pushMsgTask.putWxMsg(getAccessToken(), 7, p.getOpenid(), obj.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.getInstance().putWxMsg(getAccessToken(), 7, member.getOpenid(), member.getName(), json);
//                        }
//                    }
                    //发送代理人
                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                    if(jsonArray!=null&&jsonArray.length()>0){
                        String first = (String) json.get("first");
                        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(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
                    }else {
                        //发送代理人
                        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
                        if (jsonArray != null && jsonArray.length() > 0) {
                            String first = (String) json.get("first");
                            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(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
                            }
                        }
                    }
                }
@ -288,8 +289,15 @@ public class PatientBookingController extends WeixinBaseController{
//            Patient p = patientService.findByCode("e5a46f0264d9492897b1d3789c5b164a");
            String hospitalcode = hospitalMappingDao.getCodeByMapping(OrgCode, "1");
            Hospital hospital = hospitalDao.findByCode(hospitalcode);
    
            String msg = "您成功为"+PatientName+"预约了" + hospital.getName() + "的计划免疫 "+date+" 的号源!";
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_success","yymycg");
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(p.getName()==null?"":p.getName()))
                        .replace("key2",(PatientName==null?"":PatientName))
                        .replace("key3",(hospital.getName()==null?"":hospital.getName()))
                        .replace("key4",(date==null?"":date));
//            String msg = "您成功为"+PatientName+"预约了" + hospital.getName() + "的计划免疫 "+date+" 的号源!";
            // 推送消息给微信端
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", "");
@ -301,8 +309,9 @@ public class PatientBookingController extends WeixinBaseController{
            json.put("orgName", "-");
            json.put("doctorName", "-");
            json.put("deptName", "-");
            json.put("remark", p.getName() + ",您好!" + msg);
    
//            json.put("remark", p.getName() + ",您好!" + msg);
            json.put("remark", remark);
            //本地保存计划免疫预约记录
            ChildImmuneRegisterRecord childImmuneRegisterRecord = new ChildImmuneRegisterRecord();
            childImmuneRegisterRecord.setCode(UUID.randomUUID().toString());
@ -328,30 +337,30 @@ public class PatientBookingController extends WeixinBaseController{
            if(org.apache.commons.lang3.StringUtils.isNotBlank(p.getOpenid())){
                // 添加到发送队列
                pushMsgTask.putWxMsg(getAccessToken(), 6, p.getOpenid(), p.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());
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName()));
                    pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
            }else {
                //发送代理人
                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());
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
                    }
                }
            }
    
            //发送短信消息
            //调用总部发送信息的接口
            String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(msg, p.getMobile()), "GBK");
            String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(remark, p.getMobile()), "GBK");
            JSONObject r = toJson(result);
            SMS sms = new SMS();
            sms.setContent(msg);
            sms.setContent(remark);
            sms.setCaptcha(null);
            Date dateMsg = new Date();
            sms.setDeadline(dateMsg);
@ -414,8 +423,15 @@ public class PatientBookingController extends WeixinBaseController{
            Patient p = patientService.findByCode(getRepUID());
            String hospitalcode = hospitalMappingDao.getCodeByMapping(OrgCode, "1");
            Hospital hospital = hospitalDao.findByCode(hospitalcode);
    
            String msg = "您已取消了为"+PatientName+"预约的" + hospital.getName() + "的计划免疫 "+date+" 的挂号!";
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_success","qxmyyy");
            String remark = templateConfig.getRemark();
            remark = remark.replace("key1",(p.getName()==null?"":p.getName()))
                    .replace("key2",(PatientName==null?"":PatientName))
                    .replace("key3",(hospital.getName()==null?"":hospital.getName()))
                    .replace("key4",(date==null?"":date));
//            String msg = "您已取消了为"+PatientName+"预约的" + hospital.getName() + "的计划免疫 "+date+" 的挂号!";
            // 推送消息给微信端
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", "");
@ -425,8 +441,9 @@ public class PatientBookingController extends WeixinBaseController{
            json.put("date", date);
            json.put("doctorName", "-");
            json.put("orgName", hospital.getName());
            json.put("remark", p.getName() + ",您好!" + msg);
    
//            json.put("remark", p.getName() + ",您好!" + msg);
            json.put("remark", remark);
            //本地保存计划免疫预约记录
            ChildImmuneRegisterRecord childImmuneRegisterRecord = new ChildImmuneRegisterRecord();
            childImmuneRegisterRecord.setCode(UUID.randomUUID().toString());
@ -452,21 +469,21 @@ public class PatientBookingController extends WeixinBaseController{
            if(org.apache.commons.lang3.StringUtils.isNotBlank(p.getOpenid())){
                // 添加到发送队列
                pushMsgTask.putWxMsg(getAccessToken(), 7, p.getOpenid(), p.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());
                    //String first = (String) json.get("first");
                    data.remove("first");
                    data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName()));
                    pushMsgTask.putWxMsg(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
            }else {
                //发送代理人
                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());
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                        pushMsgTask.putWxMsg(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
                    }
                }
            }
    

+ 54 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java

@ -39,6 +39,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@ -49,6 +50,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 患者端:三师咨询控制类
@ -102,6 +104,8 @@ public class ConsultController extends WeixinBaseController {
    private HttpClientUtil httpClientUtil;
    @Autowired
    private MessageService messageService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 患者咨询记录查询
@ -854,7 +858,7 @@ public class ConsultController extends WeixinBaseController {
                    }
                    failed.add(String.valueOf(resObj.get("data")));
                    try {
                        if(messageService.getMessageNoticeSettingByMessageType(consultModel.getDoctor(),"1",MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue())){
                         /*if(messageService.getMessageNoticeSettingByMessageType(consultModel.getDoctor(),"1",MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue())){
                            //            新增发送医生助手模板消息 v1.4.0 by wujunjie
                            Doctor doctor = doctorDao.findByCode(consultModel.getDoctor());
                            String doctorOpenID = doctor.getOpenid();
@ -883,6 +887,55 @@ public class ConsultController extends WeixinBaseController {
                                    httpClientUtil.post(url, params, "UTF-8");
                                }
                            }
                        }*/
                        String sql = "SELECT t.participant_id FROM im_new.participants t where t.session_id = '" +
                                patient.getCode() + "_" + consultModel.getTeam() + "_" + consultModel.getType() +
                                "' and t.participant_role = 0";
                        List<Map<String, Object>> participants = jdbcTemplate.queryForList(sql);
                        for (Map<String, Object> participant : participants) {
//                          //有居民、健管、全科
                            String doctorCode = participant.get("participant_id").toString();
                            if (doctorCode.equals(patient.getCode())) {
                                continue;
                            }
                            //健管
                            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
                            //全科
//                            Boolean flag2 = !messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue());
                            if (flag) {
                                //            新增发送医生助手模板消息 v1.4.0 by wujunjie
                                Doctor doctor = doctorDao.findByCode(doctorCode);
                                String doctorOpenID = doctor.getOpenid();
                                if (StringUtils.isNotEmpty(doctorOpenID)) {
                                    String title = "";
                                    Consult consultSingle = consultDao.findByCode(log.getConsult());
                                    if (consultSingle != null) {
                                        Integer singleType = consultSingle.getType();
                                        if (singleType != null && singleType == 8) {
                                            title = consultSingle.getTitle();
                                        } else if (singleType != null && singleType != 8) {
                                            title = consultSingle.getSymptoms();
                                        }
                                        String repContent = parseContentType(type + "", content);
                                        String first = "居民" + patient.getName() + "的健康咨询有新的回复。";
                                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                                        List<NameValuePair> params = new ArrayList<>();
                                        params.add(new BasicNameValuePair("type", "8"));
                                        params.add(new BasicNameValuePair("openId", doctorOpenID));
                                        params.add(new BasicNameValuePair("url", targetUrl));
                                        params.add(new BasicNameValuePair("first", first));
                                        params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
                                        String keywords = title + "," + repContent + "," + doctor.getName();
                                        params.add(new BasicNameValuePair("keywords", keywords));
                                        httpClientUtil.post(url, params, "UTF-8");
                                        System.out.println("发送对象:"+doctorCode);
                                        System.out.println("发送对象名字:"+doctor.getName());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();

+ 8 - 4
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java

@ -265,19 +265,23 @@ public class PatientHealthController extends BaseController {
            Map<String, Object> map = new HashMap<>();
            String patient = getRepUID();
//            String patient = getUID();
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient, 1);
//            DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient, 1);
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
            if (xt != null) {
                map.put("xt", xt);
            }
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient, 2);
//            DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient, 2);
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
            if (xy != null) {
                map.put("xy", xy);
            }
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient, 3);
//            DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient, 3);
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
            if (tz != null) {
                map.put("tz", tz);
            }
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient, 4);
//            DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient, 4);
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
            if (sg != null) {
                map.put("sg", sg);
            }

+ 3 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/iot/IotMonitoringHealthController.java

@ -86,6 +86,8 @@ public class IotMonitoringHealthController extends BaseController {
    public String searchPatient(
            @ApiParam(name="name",value="居民姓名")
            @RequestParam(value="name",required = false) String name,
            @ApiParam(name="idcards",value="身份证(多个用逗号间隔)")
            @RequestParam(value="idcards",required = false) String idcards,
            @ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
            @RequestParam(value="page",required = false) Integer page,
            @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
@ -97,7 +99,7 @@ public class IotMonitoringHealthController extends BaseController {
            if(pageSize==null){
                pageSize = 10;
            }
            return write(200,"查询成功","data",patientDeviceService.searchPatient(name,page,pageSize));
            return write(200,"查询成功","data",patientDeviceService.searchPatient(name,page,pageSize,idcards));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");

+ 9 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/vo/HealthEduArticlePatientModel.java

@ -62,6 +62,7 @@ public class HealthEduArticlePatientModel {
    private String photo;//医生头像
    private String operatorName;//文章作者
    private String czrq;//阅读时间
    private Long totalData;//查询数据总数
    public String getSendCode() {
        return sendCode;
@ -286,4 +287,12 @@ public class HealthEduArticlePatientModel {
    public void setCzrq(String czrq) {
        this.czrq = czrq;
    }
    public Long getTotalData() {
        return totalData;
    }
    public void setTotalData(Long totalData) {
        this.totalData = totalData;
    }
}

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/iot/IotDeviceController.java

@ -251,7 +251,7 @@ public class IotDeviceController extends BaseController{
                                                    @ApiParam(name="type",value = "类型")
                                                    @RequestParam(name="type",required = true)Integer type){
        try {
            return write(200,"查询成功","data",iotDeviceService.findByPatientAndType(patientCode,type));
            return write(200,"查询成功","data",iotDeviceService.findByPatientAndType(patientCode,type,5));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());

+ 81 - 85
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/zysoft/BookingController.java

@ -3,8 +3,10 @@ package com.yihu.wlyy.web.third.zysoft;
import com.yihu.wlyy.entity.message.SMS;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientReservation;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.message.SMSDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.reservation.PatientReservationService;
import com.yihu.wlyy.service.common.SMSService;
@ -75,6 +77,8 @@ public class BookingController extends WeixinBaseController {
    private HttpClientUtil HttpClientUtil;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    /**
@ -330,7 +334,12 @@ public class BookingController extends WeixinBaseController {
                    consultService.sendMucMessageBySingnType(obj.getDoctor(),obj.getDoctorName(),patient,"我已成功为您预约:" + DateUtil.dateToStrLong(obj.getStartTime()) + "," + hospitalName + hosDeptName + doctorName + "医生的号源。您可直接前往医院就诊</br><a name='guahao' href='javascript:void(0)' data-id='" + obj.getId() + "'>点击查看详情</a>","1",p.getName());
                }
                String msg = "您成功预约了 " + obj.getOrgName() + " " + obj.getDoctorName() + " " + obj.getStartTime() + " 的号源!";
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_success","yyghcg");
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(p.getName()==null?"":p.getName()))
                        .replace("key2",(obj.getOrgName() + " " + obj.getDoctorName() + " " + obj.getStartTime()));
//                String msg = "您成功预约了 " + obj.getOrgName() + " " + obj.getDoctorName() + " " + obj.getStartTime() + " 的号源!";
                // 推送消息给微信端
                JSONObject json = new JSONObject();
                json.put("first", "");
@ -342,46 +351,35 @@ public class BookingController extends WeixinBaseController {
                json.put("orgName", obj.getOrgName());
                json.put("doctorName", obj.getDoctorName());
                json.put("deptName", obj.getDeptName());
                json.put("remark", p.getName() + ",您好!" + msg);
                json.put("remark",  remark);
                //判断是否判定openId,有没有发则查找家人发送
                if(StringUtils.isNotBlank(p.getOpenid())){
                        // 添加到发送队列
                        pushMsgTask.putWxMsg(getAccessToken(), 6, 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(getAccessToken(), 6, 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());
                        //String first = (String) json.get("first");
                        data.remove("first");
                        data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName()));
                        pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
                }else {
                    //发送代理人
                    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());
                            //String first = (String) json.get("first");
                            data.remove("first");
                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                            pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
                        }
                    }
                }
                //发送短信消息
                 //调用总部发送信息的接口
                String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(msg, p.getMobile()), "GBK");
                String result = HttpClientUtil.post(SystemConf.getInstance().getSmsUrl(), buildSmsParams(remark, p.getMobile()), "GBK");
                JSONObject r = toJson(result);
                SMS sms = new SMS();
                sms.setContent(msg);
                sms.setContent(remark);
                sms.setCaptcha(null);
                Date date = new Date();
                sms.setDeadline(date);
@ -441,6 +439,13 @@ public class BookingController extends WeixinBaseController {
                patientReservationService.updateStatus(orderId, 0);
                //微信消息
                Patient p = patientService.findByCode(obj.getPatient());
                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_failed","qxgh");
                String remark = templateConfig.getRemark();
                remark = remark.replace("key1",(obj.getName()==null?"":obj.getName()))
                            .replace("key2",(obj.getStartTime()==null?"":obj.getStartTime()+""))
                            .replace("br","\n");
                if (StringUtils.isNotEmpty(p.getOpenid())) {
                    JSONObject json = new JSONObject();
                    json.put("first", "");
@ -450,36 +455,28 @@ public class BookingController extends WeixinBaseController {
                    json.put("date", obj.getStartTime());
                    json.put("doctorName", obj.getDoctorName());
                    json.put("orgName", obj.getOrgName());
                    json.put("remark", obj.getName() + ",您好!\n您已取消了" + obj.getStartTime() + "的挂号!");
//                    json.put("remark", obj.getName() + ",您好!\n您已取消了" + obj.getStartTime() + "的挂号!");
                    json.put("remark", remark);
                    //判断是否判定openId,有没有发则查找家人发送
                    if(StringUtils.isNotBlank(p.getOpenid())){
                        // 添加到发送队列
                        pushMsgTask.putWxMsg(getAccessToken(), 7, p.getOpenid(), obj.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(getAccessToken(), 7, 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());
                            //String first = (String) json.get("first");
                            data.remove("first");
                            data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName()));
                            pushMsgTask.putWxMsg(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
                    }else {
                        //发送代理人
                        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());
                                //String first = (String) json.get("first");
                                data.remove("first");
                                data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                                pushMsgTask.putWxMsg(getAccessToken(), 7, member.getOpenid(), p.getName(), data);
                            }
                        }
                    }
                }
@ -583,17 +580,25 @@ public class BookingController extends WeixinBaseController {
            if (obj != null) {
                String des = "";
                try {
                    String msg = obj.getDname() + "医生已成功为您预约:" + DateUtil.dateToChinese(obj.getStartTime()) + "," + obj.getOrgName() +
                            obj.getDeptName() + obj.getDoctorName() + "医生的号源。您可直接前往医院就诊。";
                   /* String msg = obj.getDname() + "医生已成功为您预约:" + DateUtil.dateToChinese(obj.getStartTime()) + "," + obj.getOrgName() +
                            obj.getDeptName() + obj.getDoctorName() + "医生的号源。您可直接前往医院就诊。";*/
                    WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_appoint_success","ysyycg");
                    String remark = templateConfig.getRemark();
                    remark = remark.replace("key1",(patientName==null?"":patientName))
                            .replace("key2",(obj.getDname()==null?"":obj.getDname()))
                            .replace("key3",(DateUtil.dateToChinese(obj.getStartTime()) + "," + obj.getOrgName() +
                                    obj.getDeptName() + obj.getDoctorName()))
                            .replace("br","\n");
                    //发送短信消息,调用总部发送信息的接口
                    JSONObject resultJson = smsService.sendMsg(patientPhone,msg);
                    JSONObject resultJson = smsService.sendMsg(patientPhone,remark);
                    if (resultJson != null && resultJson.getInt("result") != 0) {
                        des = "短信提醒失败!(原因:"+resultJson.getString("description")+")";
                    }
                    //保存短信记录
                    SMS sms = new SMS();
                    sms.setContent(msg+des);
                    sms.setContent(remark+des);
                    sms.setCaptcha(null);
                    Date date = new Date();
                    sms.setDeadline(date);
@ -618,40 +623,31 @@ public class BookingController extends WeixinBaseController {
                        json.put("orgCode", obj.getOrgCode());
                        json.put("doctorName", obj.getDeptName());
                        json.put("deptName", obj.getDeptName());
                        json.put("remark", patientName + ",您好!\n" + msg);
//                        json.put("remark", patientName + ",您好!\n" + msg);
                        json.put("remark", remark);
                        //判断是否判定openId,有没有发则查找家人发送
                        if(StringUtils.isNotBlank(p.getOpenid())){
                            // 添加到发送队列
                            pushMsgTask.putWxMsg(getAccessToken(), 6, p.getOpenid(), patientName, 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(getAccessToken(), 6, 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());
                                //String first = (String) json.get("first");
                                data.remove("first");
                                data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName()));
                                pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
                        }else {
                            //发送代理人
                            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());
                                    //String first = (String) json.get("first");
                                    data.remove("first");
                                    data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()));
                                    pushMsgTask.putWxMsg(getAccessToken(), 6, member.getOpenid(), p.getName(), data);
                                }
                            }
                        }
                    }
                    else{
                        des +=" 微信提醒失败,患者无绑定微信!";

+ 1 - 1
patient-co/patient-co-wlyy/src/main/resources/application-test.yml

@ -30,7 +30,7 @@ im:
#物联网配置
iot:
  url: http://172.19.103.88:8088/svr-iot/
  url: http://172.19.103.33:8088/svr-iot/
wechat:
  appId: wx1f129f7b51701428