瀏覽代碼

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

huangwenjie 7 年之前
父節點
當前提交
b0fcaae1b3
共有 36 個文件被更改,包括 3141 次插入803 次删除
  1. 162 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/call/CallRecord.java
  2. 250 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/call/CallService.java
  3. 10 0
      patient-co-manage/wlyy-manage/pom.xml
  4. 125 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/common/account/CustomerController.java
  5. 4 2
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Message.java
  6. 162 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/call/CallRecord.java
  7. 250 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/call/CallService.java
  8. 13 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/call/CallRecordDao.java
  9. 18 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/call/CallServiceDao.java
  10. 283 8
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java
  11. 9 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/util/DateUtil.java
  12. 65 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/prescription/Prescription.java
  13. 1 1
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java
  14. 0 156
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java
  15. 8 8
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/AgeConvert.java
  16. 64 0
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/PrescriptionAgeConvert.java
  17. 101 101
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/FollowupPlanJob.java
  18. 150 150
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/HealthMessageJob.java
  19. 220 220
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/NoticeJob.java
  20. 1 0
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/DoctorWorkTimeService.java
  21. 0 125
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java
  22. 16 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/event/ApplicationEvent.java
  23. 150 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/HealthMessageJob.java
  24. 221 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/NoticeJob.java
  25. 4 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/message/MessageDao.java
  26. 112 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java
  27. 2 2
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  28. 139 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/task/NoticeJobPushMsgTask.java
  29. 65 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/DBExtract.java
  30. 156 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/DBPageExtract.java
  31. 128 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/NoticeHttpClientUtil.java
  32. 221 0
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/NoticeImUtill.java
  33. 2 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/FamilyContractService.java
  34. 27 26
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java
  35. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java
  36. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/StatisticsController.java

+ 162 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/call/CallRecord.java

@ -14,6 +14,7 @@ import java.util.Date;
public class CallRecord extends IdEntity {
    private String  code; //业务关联标识
    private Integer type; //1.呼入,2.呼出
    private String  callerNumber; //主叫号码
    private String  recipientNumber;//被叫号码
    private Integer  answerStatus;//接听状态: 1.接通,2. 队列中放弃,3.接通
@ -32,6 +33,7 @@ public class CallRecord extends IdEntity {
    private String  ssc; //社保卡号
    private String  doctor; //签约医生code
    private String  doctorName; //签约医生姓名
    private String  adminTeamCode;
    public String getCode() {
        return code;
@ -40,4 +42,164 @@ public class CallRecord extends IdEntity {
    public void setCode(String code) {
        this.code = code;
    }
    public String getCallerNumber() {
        return callerNumber;
    }
    public void setCallerNumber(String callerNumber) {
        this.callerNumber = callerNumber;
    }
    public String getRecipientNumber() {
        return recipientNumber;
    }
    public void setRecipientNumber(String recipientNumber) {
        this.recipientNumber = recipientNumber;
    }
    public Integer getAnswerStatus() {
        return answerStatus;
    }
    public void setAnswerStatus(Integer answerStatus) {
        this.answerStatus = answerStatus;
    }
    public Integer getServiceType() {
        return serviceType;
    }
    public void setServiceType(Integer serviceType) {
        this.serviceType = serviceType;
    }
    public String getServiceContent() {
        return serviceContent;
    }
    public void setServiceContent(String serviceContent) {
        this.serviceContent = serviceContent;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getEndTime() {
        return endTime;
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public Date getCallTime() {
        return callTime;
    }
    public void setCallTime(Date callTime) {
        this.callTime = callTime;
    }
    public String getTalkTime() {
        return talkTime;
    }
    public void setTalkTime(String talkTime) {
        this.talkTime = talkTime;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(String adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
}

+ 250 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/call/CallService.java

@ -34,6 +34,16 @@ public class CallService extends IdEntity {
    private Integer dealState; // 处理结果:1.完成,2.无法联系居民
    private String dealContent; // 处理内容
    private Integer dealReason; // 处理取消原因:0.没有号源、1.病人取消
    private String orderHospital; //预约医院code
    private String orderHospitalName; //预约医院
    private String orderDept; //预约科室code
    private String orderDeptName; //预约科室名称
    private String orderDoctor; //预约医生code
    private String orderDoctorName; //预约医生名称
    private String orderTime; //预约时间段
    private String user; //创建人
    private String userName; //创建人
    private String adminTeamCode; //团队id
    public String getCode() {
        return code;
@ -42,4 +52,244 @@ public class CallService extends IdEntity {
    public void setCode(String code) {
        this.code = code;
    }
    public String getCallCode() {
        return callCode;
    }
    public void setCallCode(String callCode) {
        this.callCode = callCode;
    }
    public Integer getServerType() {
        return serverType;
    }
    public void setServerType(Integer serverType) {
        this.serverType = serverType;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getIdcard() {
        return Idcard;
    }
    public void setIdcard(String idcard) {
        Idcard = idcard;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getServerContent() {
        return serverContent;
    }
    public void setServerContent(String serverContent) {
        this.serverContent = serverContent;
    }
    public Integer getState() {
        return state;
    }
    public void setState(Integer state) {
        this.state = state;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Integer getDealType() {
        return dealType;
    }
    public void setDealType(Integer dealType) {
        this.dealType = dealType;
    }
    public Date getDealTime() {
        return dealTime;
    }
    public void setDealTime(Date dealTime) {
        this.dealTime = dealTime;
    }
    public Integer getDealState() {
        return dealState;
    }
    public void setDealState(Integer dealState) {
        this.dealState = dealState;
    }
    public String getDealContent() {
        return dealContent;
    }
    public void setDealContent(String dealContent) {
        this.dealContent = dealContent;
    }
    public Integer getDealReason() {
        return dealReason;
    }
    public void setDealReason(Integer dealReason) {
        this.dealReason = dealReason;
    }
    public String getOrderHospital() {
        return orderHospital;
    }
    public void setOrderHospital(String orderHospital) {
        this.orderHospital = orderHospital;
    }
    public String getOrderHospitalName() {
        return orderHospitalName;
    }
    public void setOrderHospitalName(String orderHospitalName) {
        this.orderHospitalName = orderHospitalName;
    }
    public String getOrderDept() {
        return orderDept;
    }
    public void setOrderDept(String orderDept) {
        this.orderDept = orderDept;
    }
    public String getOrderDeptName() {
        return orderDeptName;
    }
    public void setOrderDeptName(String orderDeptName) {
        this.orderDeptName = orderDeptName;
    }
    public String getOrderDoctor() {
        return orderDoctor;
    }
    public void setOrderDoctor(String orderDoctor) {
        this.orderDoctor = orderDoctor;
    }
    public String getOrderDoctorName() {
        return orderDoctorName;
    }
    public void setOrderDoctorName(String orderDoctorName) {
        this.orderDoctorName = orderDoctorName;
    }
    public String getOrderTime() {
        return orderTime;
    }
    public void setOrderTime(String orderTime) {
        this.orderTime = orderTime;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(String adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
}

+ 10 - 0
patient-co-manage/wlyy-manage/pom.xml

@ -102,6 +102,16 @@
            <artifactId>jackson-module-jaxb-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>

+ 125 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/common/account/CustomerController.java

@ -5,12 +5,15 @@ import com.yihu.wlyy.entity.Doctor;
import com.yihu.wlyy.entity.Patient;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.entity.WlyyCustomerLog;
import com.yihu.wlyy.entity.call.CallRecord;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.service.manager.account.CustomerService;
import com.yihu.wlyy.service.manager.hos.HosDoctorService;
import com.yihu.wlyy.service.manager.patient.AdminPatientService;
import com.yihu.wlyy.service.manager.user.UserService;
import com.yihu.wlyy.service.manager.user.WlyyCustomerLogService;
import com.yihu.wlyy.util.DateUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -195,4 +198,126 @@ public class CustomerController extends BaseController {
        return write(-1,"发送失败","data",resp);
    }
    @RequestMapping(value = "/addCallRecord", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "新增电话记录")
    public String addCallRecord(@ApiParam(name="type",value="1.呼入,2.呼出")@RequestParam(required = true)Integer type,
                                 @ApiParam(name="callerNumber",value="呼入号码")@RequestParam(required = true)String callerNumber,
                                 @ApiParam(name="recipientNumber",value="接收号码")@RequestParam(required = true)String recipientNumber,
                                 @ApiParam(name="status",value="接听状态: 1.接通,2. 队列中放弃,3.接通")@RequestParam(required = true)Integer status,
                                 @ApiParam(name="serviceType",value="服务类型")@RequestParam(required = true)Integer serviceType,
                                 @ApiParam(name="serviceContent",value="服务内容")@RequestParam(required = false)String serviceContent){
        try {
            return write(200,"保存成功","data",customerService.addCallRecord( getUID(), type, callerNumber, recipientNumber, status, serviceType, serviceContent));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/updateCallRecord", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "更新电话记录")
    public String  updateCallRecord(@ApiParam(name="jsonString",value="保存实体json串")@RequestParam(required = true)String jsonString){
        try {
            return write(200,"保存成功","data",customerService.updateCallRecord(jsonString));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/updateCallRecordEndTime", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "更新电话记录(更新结束时间)")
    public String  updateCallRecordEndTime(@ApiParam(name="jsonString",value="保存实体json串")@RequestParam(required = true)String jsonString){
        try {
            return write(200,"保存成功","data",customerService.updateCallRecordEndTime(jsonString));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/getCallRecords", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取通讯记录列表")
    public String getCallRecords(@ApiParam(name="callerNumber",value="呼叫人电话")@RequestParam(required = true)String callerNumber,
                                 @ApiParam(name="answerStatus",value="接听状态: 1.接通,2. 队列中放弃,3.接通")@RequestParam(required = true)Integer answerStatus,
                                 @ApiParam(name="serviceType",value="服务类型:0.医生咨询,1.预约挂号")@RequestParam(required = true)Integer serviceType ,
                                 @ApiParam(name="startDate",value="开始时间")@RequestParam(required = true)String startDate,
                                 @ApiParam(name="endDate",value="结束时间")@RequestParam(required = true)String endDate,
                                 @ApiParam(name="page",value="第几页,从1开始")@RequestParam(required = true)Integer page,
                                 @ApiParam(name="size",value="页码大小")@RequestParam(required = true)Integer size){
        try {
            return write(200,"保存成功","data",customerService.getCallRecords(callerNumber,answerStatus,serviceType,startDate,endDate,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/getCallRecordInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取通讯记录详情")
    public String getCallRecordInfo(@ApiParam(name="code",value="通话记录code")@RequestParam(required = true)String code){
        try {
            return write(200,"保存成功","data",customerService.getCallRecordInfo(code));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/getCallServiceCode", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取协同服务编号")
    public String getCallServiceCode(@ApiParam(name="type",value="协同服务类型编号,1为咨询 2为待预约")@RequestParam(required = true)String type){
        try {
            return write(200,"保存成功","data",customerService.getCallServiceCode(type));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/saveCallService", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "保存协同服务")
    public String saveCallService(@ApiParam(name="type",value="协同服务json串")@RequestParam(required = true)String callServiceJson){
        try {
            return write(200,"保存成功","data",customerService.saveCallService( callServiceJson,getUID()));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/getCallServices", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "协同服务查询")
    public String getCallServices(@ApiParam(name="keyword",value="姓名或身份证或医保卡号")@RequestParam(required = true)String keyword,
                                  @ApiParam(name="serverType",value="服务类型:0.医生咨询,1.预约挂号")@RequestParam(required = true)Integer serverType,
                                  @ApiParam(name="state",value="订单状态:0.草稿,1.待处理,2.完成")@RequestParam(required = true)Integer state,
                                  @ApiParam(name="patientName",value="患者姓名")@RequestParam(required = true)String patientName,
                                  @ApiParam(name="ssc",value="医保卡号")@RequestParam(required = true)String ssc,
                                  @ApiParam(name="idCard",value="身份证号")@RequestParam(required = true)String idCard,
                                  @ApiParam(name="doctorName",value="医生姓名")@RequestParam(required = true)String doctorName,
                                  @ApiParam(name="code",value="服务编号")@RequestParam(required = true)String code,
                                  @ApiParam(name="startDate",value="开始时间")@RequestParam(required = true)String startDate,
                                  @ApiParam(name="endDate",value="结束时间")@RequestParam(required = true)String endDate,
                                  @ApiParam(name="page",value="第几页,从1开始")@RequestParam(required = true)Integer page,
                                  @ApiParam(name="size",value="每页大小")@RequestParam(required = true)Integer size){
        try {
            return write(200,"保存成功","data",customerService.getCallServices(keyword, serverType,state,patientName,ssc,idCard,doctorName, code, startDate, endDate, page, size));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
    @RequestMapping(value = "/getCallServiceInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "协同服务详情")
    public String getCallServiceInfo(@ApiParam(name="code",value="协同服务编号")@RequestParam(required = true)String code){
        try {
            return write(200,"保存成功","data",customerService.getCallServiceInfo(code));
        }catch (Exception e){
            error(e);
            return error(-1,"保存失败");
        }
    }
}

File diff suppressed because it is too large
+ 4 - 2
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Message.java


+ 162 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/call/CallRecord.java

@ -14,6 +14,7 @@ import java.util.Date;
public class CallRecord extends IdEntity {
    private String  code; //业务关联标识
    private Integer type; //1.呼入,2.呼出
    private String  callerNumber; //主叫号码
    private String  recipientNumber;//被叫号码
    private Integer  answerStatus;//接听状态: 1.接通,2. 队列中放弃,3.接通
@ -32,6 +33,7 @@ public class CallRecord extends IdEntity {
    private String  ssc; //社保卡号
    private String  doctor; //签约医生code
    private String  doctorName; //签约医生姓名
    private String  adminTeamCode;
    public String getCode() {
        return code;
@ -40,4 +42,164 @@ public class CallRecord extends IdEntity {
    public void setCode(String code) {
        this.code = code;
    }
    public String getCallerNumber() {
        return callerNumber;
    }
    public void setCallerNumber(String callerNumber) {
        this.callerNumber = callerNumber;
    }
    public String getRecipientNumber() {
        return recipientNumber;
    }
    public void setRecipientNumber(String recipientNumber) {
        this.recipientNumber = recipientNumber;
    }
    public Integer getAnswerStatus() {
        return answerStatus;
    }
    public void setAnswerStatus(Integer answerStatus) {
        this.answerStatus = answerStatus;
    }
    public Integer getServiceType() {
        return serviceType;
    }
    public void setServiceType(Integer serviceType) {
        this.serviceType = serviceType;
    }
    public String getServiceContent() {
        return serviceContent;
    }
    public void setServiceContent(String serviceContent) {
        this.serviceContent = serviceContent;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getEndTime() {
        return endTime;
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public Date getCallTime() {
        return callTime;
    }
    public void setCallTime(Date callTime) {
        this.callTime = callTime;
    }
    public String getTalkTime() {
        return talkTime;
    }
    public void setTalkTime(String talkTime) {
        this.talkTime = talkTime;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(String adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
}

+ 250 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/call/CallService.java

@ -34,6 +34,16 @@ public class CallService extends IdEntity {
    private Integer dealState; // 处理结果:1.完成,2.无法联系居民
    private String dealContent; // 处理内容
    private Integer dealReason; // 处理取消原因:0.没有号源、1.病人取消
    private String orderHospital; //预约医院code
    private String orderHospitalName; //预约医院
    private String orderDept; //预约科室code
    private String orderDeptName; //预约科室名称
    private String orderDoctor; //预约医生code
    private String orderDoctorName; //预约医生名称
    private String orderTime; //预约时间段
    private String user; //创建人
    private String userName; //创建人
    private String adminTeamCode; //团队id
    public String getCode() {
        return code;
@ -42,4 +52,244 @@ public class CallService extends IdEntity {
    public void setCode(String code) {
        this.code = code;
    }
    public String getCallCode() {
        return callCode;
    }
    public void setCallCode(String callCode) {
        this.callCode = callCode;
    }
    public Integer getServerType() {
        return serverType;
    }
    public void setServerType(Integer serverType) {
        this.serverType = serverType;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getIdcard() {
        return Idcard;
    }
    public void setIdcard(String idcard) {
        Idcard = idcard;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getServerContent() {
        return serverContent;
    }
    public void setServerContent(String serverContent) {
        this.serverContent = serverContent;
    }
    public Integer getState() {
        return state;
    }
    public void setState(Integer state) {
        this.state = state;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public Integer getDealType() {
        return dealType;
    }
    public void setDealType(Integer dealType) {
        this.dealType = dealType;
    }
    public Date getDealTime() {
        return dealTime;
    }
    public void setDealTime(Date dealTime) {
        this.dealTime = dealTime;
    }
    public Integer getDealState() {
        return dealState;
    }
    public void setDealState(Integer dealState) {
        this.dealState = dealState;
    }
    public String getDealContent() {
        return dealContent;
    }
    public void setDealContent(String dealContent) {
        this.dealContent = dealContent;
    }
    public Integer getDealReason() {
        return dealReason;
    }
    public void setDealReason(Integer dealReason) {
        this.dealReason = dealReason;
    }
    public String getOrderHospital() {
        return orderHospital;
    }
    public void setOrderHospital(String orderHospital) {
        this.orderHospital = orderHospital;
    }
    public String getOrderHospitalName() {
        return orderHospitalName;
    }
    public void setOrderHospitalName(String orderHospitalName) {
        this.orderHospitalName = orderHospitalName;
    }
    public String getOrderDept() {
        return orderDept;
    }
    public void setOrderDept(String orderDept) {
        this.orderDept = orderDept;
    }
    public String getOrderDeptName() {
        return orderDeptName;
    }
    public void setOrderDeptName(String orderDeptName) {
        this.orderDeptName = orderDeptName;
    }
    public String getOrderDoctor() {
        return orderDoctor;
    }
    public void setOrderDoctor(String orderDoctor) {
        this.orderDoctor = orderDoctor;
    }
    public String getOrderDoctorName() {
        return orderDoctorName;
    }
    public void setOrderDoctorName(String orderDoctorName) {
        this.orderDoctorName = orderDoctorName;
    }
    public String getOrderTime() {
        return orderTime;
    }
    public void setOrderTime(String orderTime) {
        this.orderTime = orderTime;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getAdminTeamCode() {
        return adminTeamCode;
    }
    public void setAdminTeamCode(String adminTeamCode) {
        this.adminTeamCode = adminTeamCode;
    }
}

+ 13 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/call/CallRecordDao.java

@ -0,0 +1,13 @@
package com.yihu.wlyy.repository.call;
import com.yihu.wlyy.entity.call.CallRecord;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2017/11/9.
 */
public interface CallRecordDao extends PagingAndSortingRepository<CallRecord, Long>, JpaSpecificationExecutor<CallRecord> {
    CallRecord findByCode(String code);
}

+ 18 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/call/CallServiceDao.java

@ -0,0 +1,18 @@
package com.yihu.wlyy.repository.call;
import com.yihu.wlyy.entity.call.CallRecord;
import com.yihu.wlyy.entity.call.CallService;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2017/11/9.
 */
public interface CallServiceDao extends PagingAndSortingRepository<CallService, Long>, JpaSpecificationExecutor<CallRecord> {
    List<CallService> findByCallCodeAndType(String callCode,Integer type);
    CallService findByCode(String code);
}

+ 283 - 8
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java

@ -1,12 +1,22 @@
package com.yihu.wlyy.service.manager.account;
import com.yihu.wlyy.entity.Doctor;
import com.yihu.wlyy.entity.Patient;
import com.yihu.wlyy.entity.SignFamily;
import com.yihu.wlyy.entity.*;
import com.yihu.wlyy.entity.call.CallRecord;
import com.yihu.wlyy.entity.call.CallService;
import com.yihu.wlyy.repository.MessageDao;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.repository.UserDao;
import com.yihu.wlyy.repository.call.CallRecordDao;
import com.yihu.wlyy.repository.call.CallServiceDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.manager.family.FamilyMemberService;
import com.yihu.wlyy.service.manager.hos.HosDoctorService;
import com.yihu.wlyy.service.manager.sign.FamilyContractService;
import com.yihu.wlyy.service.manager.sign.SignFamilyService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import io.swagger.models.auth.In;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
@ -15,15 +25,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
public class CustomerService{
public class CustomerService extends BaseService{
	@Autowired
	private FamilyMemberService familyMemberService;
@ -31,6 +39,20 @@ public class CustomerService{
	private FamilyContractService contractService;
	@Autowired
	private HosDoctorService hosDoctorService;
	@Autowired
	private CallRecordDao callRecordDao;
	@Autowired
	private CallServiceDao callServiceDao;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private SignFamilyService familyService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private MessageDao messageDao;
	@Value(("${doctorAssistant.api}")+"/wlyygc/doctor/message")
	private String messageApi;
@ -160,4 +182,257 @@ public class CustomerService{
		}
		return resp;
	}
	public Map<String,Object> addCallRecord(String user,Integer type,String callerNumber,String recipientNumber,Integer status,Integer serviceType,String serviceContent){
		List<Patient> list =  patientDao.findByMobile(callerNumber);
		Map<String,Object> rs = new HashedMap();
		Patient p ;
		if(list!=null||list.size()==0){
			rs.put("state",-1);
			rs.put("mes","未找到患者信息");
			rs.put("callRecord",null);
			return rs;
		}else{
			p = list.get(0);
		}
		SignFamily sf = familyService.findByPatientCode(p.getCode());
		User u = userDao.findByCode(user);
		CallRecord callRecord = new CallRecord();
		callRecord.setType(type);
		callRecord.setCode(getCode());
		callRecord.setCallerNumber(callerNumber);
		callRecord.setRecipientNumber(recipientNumber);
		callRecord.setAnswerStatus(status);
		callRecord.setServiceType(serviceType);
		callRecord.setServiceContent(serviceContent);
		callRecord.setCreateTime(new Date());
		callRecord.setCallTime(new Date());
		callRecord.setUserCode(user);
		callRecord.setUserName(u.getName());
		callRecord.setPatient(p.getCode());
		callRecord.setPatientName(p.getName());
		callRecord.setIdcard(p.getIdcard());
		callRecord.setSsc(p.getSsc());
		callRecord.setDoctor(sf.getDoctor());
		callRecord.setDoctorName(sf.getDoctorName());
		CallRecord temp = callRecordDao.save(callRecord);
		rs.put("state",1);
		rs.put("mes","保存成功");
		rs.put("callRecord",temp);
		return rs;
	}
	public String  updateCallRecord(String jsonString){
		net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(jsonString);
		CallRecord callRecord =(CallRecord)net.sf.json.JSONObject.toBean(json,CallRecord.class);
		callRecordDao.save(callRecord);
		return "1";
	}
	public String  updateCallRecordEndTime(String jsonString){
		net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(jsonString);
		CallRecord callRecord =(CallRecord)net.sf.json.JSONObject.toBean(json,CallRecord.class);
		callRecord.setEndTime(new Date());
		callRecord.setTalkTime(DateUtil.getTimeDifference(callRecord.getCreateTime(),callRecord.getEndTime()));
		callRecordDao.save(callRecord);
		return "1";
	}
	public List<Map<String,Object>> getCallRecords(String callerNumber,Integer answerStatus,Integer serviceType ,String startDate,String endDate,Integer page,Integer size){
		String sql = "SELECT " +
				" r.type, " +
				" r.caller_number AS callerNumber, " +
				" r.recipient_number AS recipientNumber, " +
				" r.call_time AS callTime, " +
				" r.talk_time AS talkTime, " +
				" r.answer_status AS answerStatus, " +
				" r.service_type AS serviceType, " +
				" r.user_name AS userName, " +
				" r.user_code AS userCode " +
				" FROM " +
				" manage_call_record r " +
				" WHERE " +
				" 1 = 1 ";
		if(StringUtils.isNotBlank(callerNumber)){
			sql +=" AND r.caller_number = '"+callerNumber+"'";
		}
		if(answerStatus!=null){
			sql += " AND r.answer_status = "+answerStatus ;
		}
		if(serviceType!=null){
			sql += " AND r.service_type = " +serviceType;
		}
		if(StringUtils.isNotBlank(startDate)){
			sql +=" AND r.call_time >='"+startDate+" 00:00:00'";
		}
		if(StringUtils.isNotBlank(endDate)){
			sql +=" AND r.call_time <='"+endDate+" 23:59:59'";
		}
		sql += " LIMIT "+(page-1)*size+","+size +" ORDER BY r.call_time DESC";
		List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
		return rs;
	}
	public Map<String,Object> getCallRecordInfo(String code){
		CallRecord callRecord = callRecordDao.findByCode(code);
		List<CallService> consultService = callServiceDao.findByCallCodeAndType(code,0);
		List<CallService> orderService = callServiceDao.findByCallCodeAndType(code,1);
		Map<String,Object> rs = new HashedMap();
		rs.put("callRecord",callRecord);
		rs.put("consultService",consultService);
		rs.put("orderService",orderService);
		return rs;
	}
	public String getCallServiceCode(String type){
		/**
		 * 服务编号规则:协同服务类型编号+YYMMddhhmmss+编号
		 * 协同服务类型编号:01预约挂号,02咨询医生
		 * YYMMDDHHMMSS:创建时间,例子20170901010101
		 * 编号:4位,当天累计协同服务数,按顺序+1
		 */
		String head ;
		if("1".equals(type)){
			head = "01";
		}else{
			head = "02";
		}
		String time = DateUtil.getStringDate("YYYYMMDDHHmmss");
		String sql = "SElECT count(1) AS total FROM manage_call_service s WHERE s.create_time >='"+DateUtil.getStringDate("yyyy-MM-ss")+" 00:00:00'";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
		String count ;
		if(list!=null&&list.size()>0){
			Map<String,Object> map = list.get(0);
			Long c = (Long) map.get("total");
			count =c.toString();
		}else{
			count = "0000";
		}
		if(count.length()==1){
			count = "000"+count;
		}else if(count.length()==2){
			count = "00"+count;
		}else if(count.length()==3){
			count = "0"+count;
		}else if(count.length()==4){
			count = count;
		}else{
			count = count.substring(0,3);
		}
		return head+time+count;
	}
	public String saveCallService(String callServiceJson,String user){
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(callServiceJson);
		CallService callService =  (CallService)net.sf.json.JSONObject.toBean(jsonObject);
		callService.setUser(user);
		User u = userDao.findByCode(user);
		callService.setUserName(u.getName());
		callServiceDao.save(callService);
		//待处理发送消息给医生
		if(callService.getState()==1){
			Patient p = patientDao.findByCode(callService.getPatient());
			// 添加签约消息
			Message message = new Message();
			message.setCzrq(new Date());
			message.setCreateTime(new Date());
			message.setContent("您有一条新的协同服务消息!");
			message.setRead(1);//设置未读
			message.setReceiver(callService.getDoctor());//设置接受医生的code
			message.setSender(callService.getPatient());//设置发送的用户
			message.setSenderName(callService.getPatientName());
			message.setCode(getCode());
			message.setSenderPhoto(p.getPhoto());
			message.setTitle("协同服务消息");
			message.setType(11);//协同服务消息
			message.setReadonly(1);//是否只读消息
			message.setSex(p.getSex());
			message.setOver("1");//未处理
			messageDao.save(message);
		}
		return "1";
	}
	public List<Map<String,Object>> getCallServices(String keyword, Integer serverType,Integer state,String patientName,String ssc,String idCard,String doctorName,String code,String startDate,String endDate,Integer page,Integer size){
		String sql = "SELECT " +
				" s.`code`, " +
				" s.patient, " +
				" s.patient_name AS patientName, " +
				" s.doctor, " +
				" s.doctor_name AS doctorName, " +
				" s.server_type As serverType, " +
				" s.state, " +
				" s.server_content AS serverContent, " +
				" s.create_time AS createTime, " +
				" s.user, " +
				" s.user_name AS userName " +
				" FROM " +
				" manage_call_service s " +
				" WHERE " +
				" 1 = 1";
		if(StringUtils.isNotBlank(keyword)){
			sql +=" AND (s.patient_name = '"+keyword+"' OR s.ssc ='"+keyword+"' OR s.Idcard ='"+keyword+"')";
		}
		if(serverType!=null){
			sql += " AND s.server_type ='"+serverType+"' " ;
		}
		if(state != null){
			sql +=" AND s.state ='"+state+"'";
		}
		if(StringUtils.isNotBlank(patientName)){
			sql +=" AND s.patient_name ='"+patientName+"'" ;
		}
		if(StringUtils.isNotBlank(ssc)){
			sql +=" AND s.ssc ='"+ssc+"'" ;
		}
		if(StringUtils.isNotBlank(idCard)){
			sql +=" AND s.IdCard ='"+idCard+"'" ;
		}
		if(StringUtils.isNotBlank(doctorName)){
			sql +=" AND s.doctor_name ='"+doctorName+"'" ;
		}
		if(StringUtils.isNotBlank(code)){
			sql +=" AND s.code ='"+code+"'" ;
		}
		if(StringUtils.isNotBlank(startDate)){
			sql +=" AND s.create_time >='"+startDate+" 00:00:00'" ;
		}
		if(StringUtils.isNotBlank(endDate)){
			sql +=" AND s.create_time <='"+endDate+" 23:59:59'" ;
		}
		sql += " LIMIT "+(page-1)*size+","+size +" ORDER BY r.create_time DESC";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}
	public Map<String,Object> getCallServiceInfo(String code){
		CallService callService = callServiceDao.findByCode(code);
		CallRecord callRecord = callRecordDao.findByCode(callService.getCallCode());
		Map<String,Object> rs = new HashedMap();
		rs.put("callService",callService);
		rs.put("callRecord",callRecord);
		return rs;
	}
}

+ 9 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/util/DateUtil.java

@ -680,6 +680,15 @@ public class DateUtil {
		return localDate.getYear()+"年"+localDate.getMonth().getValue()+"月"+localDate.getDayOfMonth()+"日";
	}
	public static String  getTimeDifference(Date date1,Date date2){
		long l = date2.getTime() - date1.getTime();
		long day = l / (24 * 60 * 60 * 1000);
		long hour = (l / (60 * 60 * 1000) - day * 24);
		long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		return hour + ":" + min +":" + s;
	}
//	public static void main(String[] args) {
//		String hour = "12:22:12";
//		System.out.println(Time.valueOf(hour));

+ 65 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/prescription/Prescription.java

@ -89,6 +89,15 @@ public class Prescription extends IdEntity {
    private Integer jwPayStatus;//处方结算状态,0为未结算,1为结算成功,默认为0
    //1.4.0新增字段
    private Integer drugDeliveryFlag;   //是否异常出药0为正常 1为异常
    private String drugDeliveryReasonCode; //原因字典对应Code
    private String drugDeliveryReasonValue; //原因字典对应Name
    private String drugDeliveryReason; //详细原因
    private String drugDeliveryOperator; //操作人员code
    private String drugDeliveryOperatorName; //操作人员名字
    private Date drugDeliveryTime; //出药时间
    @Column(name = "code", unique = true, nullable = false)
    public String getCode() {
        return code;
@ -651,4 +660,60 @@ public class Prescription extends IdEntity {
    public void setJwPayStatus(Integer jwPayStatus) {
        this.jwPayStatus = jwPayStatus;
    }
    public Integer getDrugDeliveryFlag() {
        return drugDeliveryFlag;
    }
    public void setDrugDeliveryFlag(Integer drugDeliveryFlag) {
        this.drugDeliveryFlag = drugDeliveryFlag;
    }
    public String getDrugDeliveryReasonCode() {
        return drugDeliveryReasonCode;
    }
    public void setDrugDeliveryReasonCode(String drugDeliveryReasonCode) {
        this.drugDeliveryReasonCode = drugDeliveryReasonCode;
    }
    public String getDrugDeliveryReasonValue() {
        return drugDeliveryReasonValue;
    }
    public void setDrugDeliveryReasonValue(String drugDeliveryReasonValue) {
        this.drugDeliveryReasonValue = drugDeliveryReasonValue;
    }
    public String getDrugDeliveryReason() {
        return drugDeliveryReason;
    }
    public void setDrugDeliveryReason(String drugDeliveryReason) {
        this.drugDeliveryReason = drugDeliveryReason;
    }
    public String getDrugDeliveryOperator() {
        return drugDeliveryOperator;
    }
    public void setDrugDeliveryOperator(String drugDeliveryOperator) {
        this.drugDeliveryOperator = drugDeliveryOperator;
    }
    public String getDrugDeliveryOperatorName() {
        return drugDeliveryOperatorName;
    }
    public void setDrugDeliveryOperatorName(String drugDeliveryOperatorName) {
        this.drugDeliveryOperatorName = drugDeliveryOperatorName;
    }
    public Date getDrugDeliveryTime() {
        return drugDeliveryTime;
    }
    public void setDrugDeliveryTime(Date drugDeliveryTime) {
        this.drugDeliveryTime = drugDeliveryTime;
    }
}

+ 1 - 1
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/prescription/PrescriptionService.java

@ -340,7 +340,7 @@ public class PrescriptionService extends ZysoftBaseService{
                Prescription prescription = prescriptionDao.findByVisitNoAndRecipeNo(orderNo,recipeNo);
                if(prescription.getStatus().equals(PrescriptionLog.PrescriptionLogStatus.pay_success.getValue())){
                    prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.wait_expressage.getValue());
                    prescription.setDrugDeliveryTime(new Date());
                    prescriptionDao.save(prescription);
                    //新增log表

+ 0 - 156
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java

@ -271,161 +271,5 @@ public class JobController extends BaseController {
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动健康信息生成的任务
     *
     * @return
     */
    @ApiOperation(value = "启动健康信息生成的任务")
    @RequestMapping(value = "startHealthMessageJob", method = RequestMethod.GET)
    public String startHealthMessageJob() {
        try {
            jobService.startHealthMessageJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "立即启动健康信息生成的任务")
    @RequestMapping(value = "startHealthMessageJobNow", method = RequestMethod.GET)
    public String startHealthMessageJobNow() {
        try {
            jobService.startHealthMessageJobNow();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止判断的任务
     *
     * @return
     */
    @ApiOperation(value = "停止健康信息生成的任务")
    @RequestMapping(value = "stopHealthMessageJob", method = RequestMethod.GET)
    public String stopHealthMessageJob() {
        try {
            jobService.stopHealthMessageJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的健康消息
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "生成过去某一天的健康消息")
    @RequestMapping(value = "productHealthDataByOneDay", method = RequestMethod.GET)
    public String productHealthDataByOneDay( @ApiParam(name = "day", value = "yyyy-MM-dd")
                                           @RequestParam(value = "day", required = true)String day) {
        try {
            jobService.productHealthDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天到某一天的某个指标的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的健康消息(包含头尾)")
    @RequestMapping(value = "productHealthDataByDayToDay", method = RequestMethod.GET)
    public String productHealthDataByDayToDay( @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
                                             ) {
        try {
            jobService.productHealthDataByDayToDay(start,end);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "启动通知任务")
    @RequestMapping(value = "startNoticeJob", method = RequestMethod.GET)
    public String startNoticeJob() {
        try {
            jobService.startNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "立即启动通知任务")
    @RequestMapping(value = "startNoticeJobNow", method = RequestMethod.GET)
    public String startNoticeJobNow() {
        try {
            jobService.startNoticeJobNow();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动通知任务
     *
     * @return
     */
    @ApiOperation(value = "停止通知任务")
    @RequestMapping(value = "stopNoticeJob", method = RequestMethod.GET)
    public String stopNoticeJob() {
        try {
            jobService.stopNoticeJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /******************************** 随访计划消息 ****************************************************/
    @ApiOperation(value = "启动随访计划消息任务")
    @RequestMapping(value = "startFollowupPlantJob", method = RequestMethod.GET)
    public String startFollowupPlantJob() {
        try {
            jobService.startFollowupPlantJob();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    @ApiOperation(value = "停止随访计划消息任务")
    @RequestMapping(value = "stopFollowupPlantJob", method = RequestMethod.GET)
    public String stopFollowupPlantJob() {
        try {
            jobService.stopFollowupPlantJob();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 8 - 8
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/AgeConvert.java

@ -31,20 +31,20 @@ public class AgeConvert implements Convert {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                Integer age= IdCardUtil.getAgeForIdcard(String.valueOf(value));
                String key = getAgeCode(age);
                if("63".equals(temp.getQuotaCode())){
                    if(tempMap.containsKey(String.valueOf(value))){
                        continue;
                    }
                }
//                if("63".equals(temp.getQuotaCode())){
//
//                    if(tempMap.containsKey(String.valueOf(value))){
//                        continue;
//                    }
//                }
                tempMap.put(String.valueOf(value),one);
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, key);
                result.add(one);
//                result.add(one);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        return result;
        return oneList;
    }
    public String getAgeCode(Integer age) {

+ 64 - 0
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/convert/wlyy/PrescriptionAgeConvert.java

@ -0,0 +1,64 @@
package com.yihu.wlyy.statistics.etl.convert.wlyy;
import com.yihu.wlyy.entity.dimension.WlyyDimensionQuota;
import com.yihu.wlyy.statistics.etl.convert.Convert;
import com.yihu.wlyy.statistics.util.Contant;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.vo.DataModel;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/5.
 */
public class PrescriptionAgeConvert implements Convert {
    /**
     * @param oneList    数据
     * @param slaveLevel 从1开始
     * @return
     */
    public List<DataModel> convert(JdbcTemplate jdbcTemplate, List<DataModel> oneList, String slaveLevel, WlyyDimensionQuota temp ) {
        Map<String,Object> tempMap = new HashMap<>();
        List<DataModel> result = new ArrayList<>();
        for(DataModel one:oneList) {
            try {
                Object value = DataModel.class.getMethod("get" + temp.getKey()).invoke(one);
                Integer age= IdCardUtil.getAgeForIdcard(String.valueOf(value));
                String key = getAgeCode(age);
                if("63".equals(temp.getQuotaCode())){
                    if(tempMap.containsKey(String.valueOf(value))){
                        continue;
                    }
                }
                tempMap.put(String.valueOf(value),one);
                DataModel.class.getMethod("setSlaveKey" + slaveLevel, String.class).invoke(one, key);
//                result.add(one);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        return oneList;
    }
    public String getAgeCode(Integer age) {
        if (age >= 0 && age <= 6) {
            return Contant.convert.level_age_1;
        } else if (age >= 7 && age <= 18) {
            return Contant.convert.level_age_2;
        } else if (age >= 19 && age <= 30) {
            return Contant.convert.level_age_3;
        } else if (age >= 31 && age <= 50) {
            return Contant.convert.level_age_4;
        } else if (age >= 51 && age <= 64) {
            return Contant.convert.level_age_5;
        } else {
            return Contant.convert.level_age_6;
        }
    }
}

+ 101 - 101
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/message/FollowupPlanJob.java

@ -1,101 +1,101 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import javax.transaction.Transactional;
import java.util.*;
/**
 * Created by hzp on 2017.1.4.
 */
@Component
@Scope("prototype")
public class FollowupPlanJob implements Job {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private MessageDao messageDao;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        System.out.print("follow plan message sending...");
        String date = DateUtil.dateToStrShort(new Date());
        //发送随访计划消息
        sendMessage(date);
        System.out.print("follow plan message send over.");
    }
    /**
     * 每日发送随访计划提醒消息
     */
    @Transactional
    public void sendMessage(String date)
    {
        try{
            String start = date +" 00:00:00";
            String end = date +" 23:59:59";
            String sql = "select doctor_code,count(1) count from wlyy_followup where status not in ('0','1') and followup_plan_date>='"+start+"' and followup_plan_date<='"+end+"' group by doctor_code";
            //获取所有未执行随访计划
            List<Map<String,Object>> followupToday = jdbcTemplate.queryForList(sql);
            if(followupToday!=null)
            {
                List<Message> list = new ArrayList<>();
                for(Map<String,Object> map:followupToday)
                {
                    String doctor = String.valueOf(map.get("doctor_code"));
                    String count = String.valueOf(map.get("count"));
                    // 添加签约消息
                    String title = "随访计划提醒";
                    String content = "您今日有" +count+"个随访计划待处理";
                    Message message = new Message();
                    message.setCode(UUID.randomUUID().toString());
                    message.setCzrq(new Date());
                    message.setCreateTime(new Date());
                    message.setContent(content);
                    message.setRead(1);//设置未读
                    message.setReceiver(doctor);//设置接受医生的code
                    message.setSender("system");//设置发送的用户
                    message.setTitle(title);
                    message.setType(4);//随访计划提醒
                    message.setReadonly(1);//是否只读消息
                    list.add(message);
                    // 推送消息给医生
                    PushMsgTask.url= url;
                    // 推送消息给医生
                    PushMsgTask.getInstance().put(doctor,"4",title,content,"");
                }
                messageDao.save(list);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
//package com.yihu.wlyy.statistics.job.message;
//
//import com.yihu.wlyy.entity.message.Message;
//import com.yihu.wlyy.statistics.dao.MessageDao;
//import com.yihu.wlyy.statistics.task.PushMsgTask;
//import com.yihu.wlyy.statistics.util.DateUtil;
//import org.quartz.Job;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Scope;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.support.SpringBeanAutowiringSupport;
//
//import javax.transaction.Transactional;
//import java.util.*;
//
//
///**
// * Created by hzp on 2017.1.4.
// */
//@Component
//@Scope("prototype")
//public class FollowupPlanJob implements Job {
//    @Autowired
//    JdbcTemplate jdbcTemplate;
//
//    @Value("${systemConfig.msg_push_server}")
//    private String url;
//
//    @Autowired
//    private MessageDao messageDao;
//
//    @Override
//    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
//        System.out.print("follow plan message sending...");
//
//        String date = DateUtil.dateToStrShort(new Date());
//        //发送随访计划消息
//        sendMessage(date);
//
//        System.out.print("follow plan message send over.");
//    }
//
//    /**
//     * 每日发送随访计划提醒消息
//     */
//    @Transactional
//    public void sendMessage(String date)
//    {
//        try{
//            String start = date +" 00:00:00";
//            String end = date +" 23:59:59";
//
//            String sql = "select doctor_code,count(1) count from wlyy_followup where status not in ('0','1') and followup_plan_date>='"+start+"' and followup_plan_date<='"+end+"' group by doctor_code";
//            //获取所有未执行随访计划
//            List<Map<String,Object>> followupToday = jdbcTemplate.queryForList(sql);
//
//            if(followupToday!=null)
//            {
//                List<Message> list = new ArrayList<>();
//                for(Map<String,Object> map:followupToday)
//                {
//                    String doctor = String.valueOf(map.get("doctor_code"));
//                    String count = String.valueOf(map.get("count"));
//
//                    // 添加签约消息
//                    String title = "随访计划提醒";
//                    String content = "您今日有" +count+"个随访计划待处理";
//                    Message message = new Message();
//                    message.setCode(UUID.randomUUID().toString());
//                    message.setCzrq(new Date());
//                    message.setCreateTime(new Date());
//                    message.setContent(content);
//                    message.setRead(1);//设置未读
//                    message.setReceiver(doctor);//设置接受医生的code
//                    message.setSender("system");//设置发送的用户
//                    message.setTitle(title);
//                    message.setType(4);//随访计划提醒
//                    message.setReadonly(1);//是否只读消息
//                    list.add(message);
//                    // 推送消息给医生
//                    PushMsgTask.url= url;
//                    // 推送消息给医生
//                    PushMsgTask.getInstance().put(doctor,"4",title,content,"");
//                }
//
//                messageDao.save(list);
//            }
//
//
//        }
//        catch (Exception e)
//        {
//            e.printStackTrace();
//        }
//    }
//}

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

@ -1,150 +1,150 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.etl.extract.db.DBExtract;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Administrator on 2016.10.25.
 */
@Component
@Scope("prototype")
public class HealthMessageJob implements Job {
    public static String jobKey = "Health_Message_JOB";
    public static String cron = "0 0 8 * * ?";
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(jobKey);
            quartzJobLog.setJobName(jobKey);
            String yesterday = jobExecutionContext.getMergedJobDataMap().getString("yesterday");
            String now = jobExecutionContext.getMergedJobDataMap().getString("now");
            if (StringUtils.isEmpty(yesterday)) {
                yesterday = getYesterday(-1, new Date());
            }
            if (StringUtils.isEmpty(now)) {
                now = getYesterday(0, new Date());
            }
            //删除原来的数据
            String deleteSql = "delete from wlyy_message where type=3 and czrq >= '" + yesterday + " 00:00:00'and czrq <= '" + now + " 00:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql = "select admin_team_code  from wlyy_sign_family " +
                    " where  status >0 and type='2' " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            String countSql = "select count(id) from wlyy_sign_family " +
                    " where  status >0 and type='2'  " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            List<SignFamily> signFamilyList = dbExtract.extractByPage(SignFamily.class, sql, countSql, true, jdbcTemplate);
            Map<Long, List<SignFamily>> signFamilyMap = new HashMap<Long, List<SignFamily>>();
            for (int i = 0; i < signFamilyList.size(); i++) {
                SignFamily signFamilyTemp = signFamilyList.get(i);
                if (signFamilyMap.containsKey(signFamilyTemp.getAdminTeamId())) {
                    signFamilyMap.get(signFamilyTemp.getAdminTeamId()).add(signFamilyTemp);
                } else {
                    List<SignFamily> signFamilies = new ArrayList<>();
                    signFamilies.add(signFamilyTemp);
                    signFamilyMap.put(signFamilyTemp.getAdminTeamId(), signFamilies);
                }
            }
            JSONArray jsonArray = new JSONArray();
            for (Map.Entry<Long, List<SignFamily>> entry : signFamilyMap.entrySet()) {
                //得到未分配的所有数目
                countSql = "select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2'  " +
                        "  and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '') and admin_team_code=" + entry.getKey() + "";
                Integer allCount = jdbcTemplate.queryForObject(countSql, Integer.class);
                //得到团队的leader
                sql = "select leader_code from wlyy_admin_team m where m.id= ?";
                String teamLeader = jdbcTemplate.queryForObject(sql, String.class, entry.getKey());
                Message message = new Message();
                message.setType(3);
                message.setRead(0);
                message.setOver("0");
                message.setDel("1");
                message.setSender("system");
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setState(1);
                String title = "新增系统消息";
                message.setTitle(title);
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
                String content = dateFormat2.format(dateFormat1.parse(yesterday)) + "新增" + entry.getValue().size() + "个签约居民待分配健管师,目前共" + allCount + "人待处理";
                message.setContent(content);
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(teamLeader);
                messageDao.save(message);
                quartzJobLogDao.save(quartzJobLog);
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", teamLeader);
                json.put("type", "D_NH_01");
                json.put("title", title);
                json.put("msg", content);
                json.put("data", "");
                jsonArray.add(json);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成" + yesterday + "的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            // 推送消息给医生
            PushMsgTask.url = url;
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    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 void main(String[] args) {
    }
}
//package com.yihu.wlyy.statistics.job.message;
//
//import com.yihu.wlyy.entity.job.QuartzJobLog;
//import com.yihu.wlyy.entity.message.Message;
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.statistics.dao.MessageDao;
//import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
//import com.yihu.wlyy.statistics.etl.extract.db.DBExtract;
//import com.yihu.wlyy.statistics.task.PushMsgTask;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//import org.quartz.Job;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Scope;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//import org.springframework.web.context.support.SpringBeanAutowiringSupport;
//
//import java.text.SimpleDateFormat;
//import java.util.*;
//
///**
// * Created by Administrator on 2016.10.25.
// */
//@Component
//@Scope("prototype")
//public class HealthMessageJob implements Job {
//    public static String jobKey = "Health_Message_JOB";
//    public static String cron = "0 0 8 * * ?";
//
//    @Value("${systemConfig.msg_push_server}")
//    private String url;
//    @Autowired
//    private DBExtract dbExtract;
//    @Autowired
//    private MessageDao messageDao;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    private QuartzJobLogDao quartzJobLogDao;
//
//    @Transactional
//    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        try {
//
//            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
//            QuartzJobLog quartzJobLog = new QuartzJobLog();
//            quartzJobLog.setJobStartTime(new Date());
//            quartzJobLog.setJobId(jobKey);
//            quartzJobLog.setJobName(jobKey);
//            String yesterday = jobExecutionContext.getMergedJobDataMap().getString("yesterday");
//            String now = jobExecutionContext.getMergedJobDataMap().getString("now");
//            if (StringUtils.isEmpty(yesterday)) {
//                yesterday = getYesterday(-1, new Date());
//            }
//            if (StringUtils.isEmpty(now)) {
//                now = getYesterday(0, new Date());
//            }
//            //删除原来的数据
//            String deleteSql = "delete from wlyy_message where type=3 and czrq >= '" + yesterday + " 00:00:00'and czrq <= '" + now + " 00:00:00'";
//            jdbcTemplate.execute(deleteSql);
//            //生成新的数据
//            String sql = "select admin_team_code  from wlyy_sign_family " +
//                    " where  status >0 and type='2' " +
//                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
//            String countSql = "select count(id) from wlyy_sign_family " +
//                    " where  status >0 and type='2'  " +
//                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
//            List<SignFamily> signFamilyList = dbExtract.extractByPage(SignFamily.class, sql, countSql, true, jdbcTemplate);
//            Map<Long, List<SignFamily>> signFamilyMap = new HashMap<Long, List<SignFamily>>();
//            for (int i = 0; i < signFamilyList.size(); i++) {
//                SignFamily signFamilyTemp = signFamilyList.get(i);
//                if (signFamilyMap.containsKey(signFamilyTemp.getAdminTeamId())) {
//                    signFamilyMap.get(signFamilyTemp.getAdminTeamId()).add(signFamilyTemp);
//                } else {
//                    List<SignFamily> signFamilies = new ArrayList<>();
//                    signFamilies.add(signFamilyTemp);
//                    signFamilyMap.put(signFamilyTemp.getAdminTeamId(), signFamilies);
//                }
//            }
//            JSONArray jsonArray = new JSONArray();
//            for (Map.Entry<Long, List<SignFamily>> entry : signFamilyMap.entrySet()) {
//                //得到未分配的所有数目
//                countSql = "select count(id) from wlyy_sign_family " +
//                        " where  status >0 and type='2'  " +
//                        "  and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '') and admin_team_code=" + entry.getKey() + "";
//                Integer allCount = jdbcTemplate.queryForObject(countSql, Integer.class);
//                //得到团队的leader
//                sql = "select leader_code from wlyy_admin_team m where m.id= ?";
//                String teamLeader = jdbcTemplate.queryForObject(sql, String.class, entry.getKey());
//                Message message = new Message();
//                message.setType(3);
//                message.setRead(0);
//                message.setOver("0");
//                message.setDel("1");
//                message.setSender("system");
//                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
//                message.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
//                message.setState(1);
//                String title = "新增系统消息";
//                message.setTitle(title);
//                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
//                SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
//                String content = dateFormat2.format(dateFormat1.parse(yesterday)) + "新增" + entry.getValue().size() + "个签约居民待分配健管师,目前共" + allCount + "人待处理";
//                message.setContent(content);
//                message.setCode(UUID.randomUUID().toString());
//                message.setReceiver(teamLeader);
//                messageDao.save(message);
//                quartzJobLogDao.save(quartzJobLog);
//
//                // 异常通知
//                JSONObject json = new JSONObject();
//                json.put("receiver", teamLeader);
//                json.put("type", "D_NH_01");
//                json.put("title", title);
//                json.put("msg", content);
//                json.put("data", "");
//                jsonArray.add(json);
//            }
//            quartzJobLog.setJobEndTime(new Date());
//            quartzJobLog.setJobContent("生成" + yesterday + "的健康管理师消息成功");
//            quartzJobLog.setJobType("1");
//
//
//            // 推送消息给医生
//            PushMsgTask.url = url;
//            // 推送消息给医生
//            PushMsgTask.getInstance().put(jsonArray);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    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 void main(String[] args) {
//
//    }
//}

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

@ -1,220 +1,220 @@
package com.yihu.wlyy.statistics.job.message;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.statistics.dao.DoctorDao;
import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
import com.yihu.wlyy.statistics.service.DoctorWorkTimeService;
import com.yihu.wlyy.statistics.task.PushMsgTask;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/11/7.
 */
@Component
@Scope("prototype")
public class NoticeJob implements Job {
    public static String jobKey = "Notice_JOB";
    public static String jobCron = "0 0 8,14 * * ?"; //每天8点,14点,20 点执行一次
    private static String noticeKey1 = "D_ST_01";//专科
    private static String noticeKey2 = "D_ST_02";//全科
    private static String noticeKey3 = "D_ST_03";//健康管理师
    private static String noticeTitle = "系统消息";
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private QuartzJobLogDao dbStorage;
    @Autowired
    private DoctorDao doctorDao;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MessageDao messageDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(jobKey);
        quartzJobLog.setJobName(jobKey);
        try {
            List<Doctor> doctors = doctorDao.findAllDoctors();
            //得到所有未发送的医生的通知
            Map<String, JSONObject> maps = new HashMap<>();
            //发送通知
            for (Doctor doctor : doctors) {
                //判断医生是不是在工作时间内
                String noticeContent1 = " 您当前有[zxsize]条未处理消息,其中[qysize]条为签约消息。请尽快处理~";
                String noticeContent2 = " 您当前有[zxsize]条未处理消息,请尽快处理~";
                String noticeContent3 = " 您当前有[qysize]条签约消息待处理,请尽快处理~";
                String workTime = "";
                try {
                    workTime = doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).getString("status");
                } catch (Exception e) {
                }
                if ("1".equals(workTime)) {
                    //得到医生多少条咨询消息
                    Integer zxsize = getDoctorMesssageCount(doctor.getCode(), 1);
                    //得到医生多少条签约消息
                    Integer qysize = getDoctorMesssageCount(doctor.getCode(), 2);
                    //如果既有签约又有咨询
                    if (zxsize > 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent1 = noticeContent1.replace("[zxsize]", zxsize + "");
                        noticeContent1 = noticeContent1.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent1);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize > 0 && qysize == 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent2 = noticeContent2.replace("[zxsize]", zxsize + "");
                        jo.put("content", noticeContent2);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize == 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent3 = noticeContent3.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent3);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            //发送通知
            for (Map.Entry<String, JSONObject> entry : maps.entrySet()) {
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", entry.getKey());
                json.put("type", getType(entry.getValue().getInt("level")));
                json.put("title", noticeTitle);
                json.put("msg", entry.getValue().getString("content"));
                json.put("data", "");
                jsonArray.add(json);
            }
            // 推送消息给医生
            PushMsgTask.url = url;
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知成功");
            quartzJobLog.setJobType("1");
            dbStorage.save(quartzJobLog);
        } catch (Exception e) {
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知失败");
            quartzJobLog.setJobType("0");
            dbStorage.save(quartzJobLog);
            e.printStackTrace();
        }
    }
    private String getType(Integer level) {
        switch (level) {
            case 1: {
                //专科
                return noticeKey1;
            }
            case 2: {
                //全科
                return noticeKey2;
            }
            case 3: {
                //健康管理师
                return noticeKey3;
            }
        }
        return "";
    }
    /**
     * 得到医生的未读数目
     *
     * @param doctorCode 医生code
     * @param type       1是咨询 2个签约 3是体征
     * @return
     */
    private Integer getDoctorMesssageCount(String doctorCode, int type) throws Exception {
        switch (type) {
            case 1: {
                return getImMsgAmount(doctorCode);
            }
            case 2: {
                String sql = "select count(a.id) from wlyy_message a where a.type =1 and a.has_read=1 and a.receiver=?";
                return jdbcTemplate.queryForObject(sql, Integer.class, doctorCode);
            }
        }
        return 0;
    }
    private int findDoctorAllMessage(String doctor) {
        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        // 体征指标未读消息总数
        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        //系统消息
        int systemMessage = messageDao.amountUnreadSystemByReceiver(doctor);
        Integer doctorCount = 0;
        Integer patientCount = 0;
        JSONObject json = new JSONObject();
        getImMsgAmount(json, doctor);
        if (json.containsKey("imMsgCount")) {
            JSONObject jsonC = json.getJSONObject("imMsgCount");
            if (jsonC.containsKey("doctor")) {
                doctorCount = jsonC.getInt("doctor");
            }
            if (jsonC.containsKey("patient")) {
                patientCount = jsonC.getInt("patient");
            }
        }
        return sign + healthIndex + systemMessage + doctorCount + patientCount;
    }
    private void getImMsgAmount(JSONObject obj, String doctor) {
        String urlall = url + "/api/v1/chats/msg/amount?user_id=" + doctor;
        String response = HttpClientUtil.get(urlall, "UTF-8");
        obj.put("imMsgCount", response);
    }
    private Integer getImMsgAmount(String doctor) throws Exception {
        /**
         * {"msg":"获取消息总数成功!","data":{"imMsgCount":"{\"doctor\":0,\"patient\":0}","healthIndex":{"amount":0},"sign":{"amount":0}},"status":200}
         */
        return findDoctorAllMessage(doctor);
    }
}
//package com.yihu.wlyy.statistics.job.message;
//
//import com.yihu.wlyy.entity.doctor.profile.Doctor;
//import com.yihu.wlyy.entity.job.QuartzJobLog;
//import com.yihu.wlyy.statistics.dao.DoctorDao;
//import com.yihu.wlyy.statistics.dao.MessageDao;
//import com.yihu.wlyy.statistics.dao.QuartzJobLogDao;
//import com.yihu.wlyy.statistics.service.DoctorWorkTimeService;
//import com.yihu.wlyy.statistics.task.PushMsgTask;
//import com.yihu.wlyy.statistics.util.DateUtil;
//import com.yihu.wlyy.statistics.util.HttpClientUtil;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//import org.quartz.Job;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Scope;
//import org.springframework.data.domain.Page;
//import org.springframework.data.domain.PageRequest;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by Administrator on 2016/11/7.
// */
//
//@Component
//@Scope("prototype")
//public class NoticeJob implements Job {
//    public static String jobKey = "Notice_JOB";
//    public static String jobCron = "0 0 8,14 * * ?"; //每天8点,14点,20 点执行一次
//    private static String noticeKey1 = "D_ST_01";//专科
//    private static String noticeKey2 = "D_ST_02";//全科
//    private static String noticeKey3 = "D_ST_03";//健康管理师
//    private static String noticeTitle = "系统消息";
//
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private QuartzJobLogDao dbStorage;
//    @Autowired
//    private DoctorDao doctorDao;
//    @Value("${systemConfig.msg_push_server}")
//    private String url;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    private MessageDao messageDao;
//
//    @Transactional
//    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        //新建任务日志对象
//        QuartzJobLog quartzJobLog = new QuartzJobLog();
//        quartzJobLog.setJobStartTime(new Date());
//        quartzJobLog.setJobId(jobKey);
//        quartzJobLog.setJobName(jobKey);
//        try {
//            List<Doctor> doctors = doctorDao.findAllDoctors();
//            //得到所有未发送的医生的通知
//            Map<String, JSONObject> maps = new HashMap<>();
//            //发送通知
//            for (Doctor doctor : doctors) {
//                //判断医生是不是在工作时间内
//                String noticeContent1 = " 您当前有[zxsize]条未处理消息,其中[qysize]条为签约消息。请尽快处理~";
//                String noticeContent2 = " 您当前有[zxsize]条未处理消息,请尽快处理~";
//                String noticeContent3 = " 您当前有[qysize]条签约消息待处理,请尽快处理~";
//                String workTime = "";
//                try {
//                    workTime = doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).getString("status");
//                } catch (Exception e) {
//
//                }
//                if ("1".equals(workTime)) {
//                    //得到医生多少条咨询消息
//                    Integer zxsize = getDoctorMesssageCount(doctor.getCode(), 1);
//                    //得到医生多少条签约消息
//                    Integer qysize = getDoctorMesssageCount(doctor.getCode(), 2);
//                    //如果既有签约又有咨询
//                    if (zxsize > 0 && qysize > 0) {
//                        JSONObject jo = new JSONObject();
//                        noticeContent1 = noticeContent1.replace("[zxsize]", zxsize + "");
//                        noticeContent1 = noticeContent1.replace("[qysize]", qysize + "");
//                        jo.put("content", noticeContent1);
//                        jo.put("level", doctor.getLevel());
//                        maps.put(doctor.getCode(), jo);
//                    }
//                    //只有咨询
//                    if (zxsize > 0 && qysize == 0) {
//                        JSONObject jo = new JSONObject();
//                        noticeContent2 = noticeContent2.replace("[zxsize]", zxsize + "");
//                        jo.put("content", noticeContent2);
//                        jo.put("level", doctor.getLevel());
//                        maps.put(doctor.getCode(), jo);
//                    }
//                    //只有咨询
//                    if (zxsize == 0 && qysize > 0) {
//                        JSONObject jo = new JSONObject();
//                        noticeContent3 = noticeContent3.replace("[qysize]", qysize + "");
//                        jo.put("content", noticeContent3);
//                        jo.put("level", doctor.getLevel());
//                        maps.put(doctor.getCode(), jo);
//                    }
//                }
//            }
//            JSONArray jsonArray = new JSONArray();
//            //发送通知
//            for (Map.Entry<String, JSONObject> entry : maps.entrySet()) {
//                // 异常通知
//                JSONObject json = new JSONObject();
//                json.put("receiver", entry.getKey());
//                json.put("type", getType(entry.getValue().getInt("level")));
//                json.put("title", noticeTitle);
//                json.put("msg", entry.getValue().getString("content"));
//                json.put("data", "");
//                jsonArray.add(json);
//            }
//            // 推送消息给医生
//            PushMsgTask.url = url;
//            // 推送消息给医生
//            PushMsgTask.getInstance().put(jsonArray);
//            //保存日志
//            quartzJobLog.setJobEndTime(new Date());
//            quartzJobLog.setJobContent("通知成功");
//            quartzJobLog.setJobType("1");
//            dbStorage.save(quartzJobLog);
//        } catch (Exception e) {
//            //保存日志
//            quartzJobLog.setJobEndTime(new Date());
//            quartzJobLog.setJobContent("通知失败");
//            quartzJobLog.setJobType("0");
//            dbStorage.save(quartzJobLog);
//            e.printStackTrace();
//        }
//
//    }
//
//    private String getType(Integer level) {
//        switch (level) {
//            case 1: {
//                //专科
//                return noticeKey1;
//            }
//            case 2: {
//                //全科
//                return noticeKey2;
//            }
//            case 3: {
//                //健康管理师
//                return noticeKey3;
//            }
//        }
//        return "";
//    }
//
//
//    /**
//     * 得到医生的未读数目
//     *
//     * @param doctorCode 医生code
//     * @param type       1是咨询 2个签约 3是体征
//     * @return
//     */
//    private Integer getDoctorMesssageCount(String doctorCode, int type) throws Exception {
//        switch (type) {
//            case 1: {
//                return getImMsgAmount(doctorCode);
//            }
//            case 2: {
//                String sql = "select count(a.id) from wlyy_message a where a.type =1 and a.has_read=1 and a.receiver=?";
//                return jdbcTemplate.queryForObject(sql, Integer.class, doctorCode);
//            }
//        }
//        return 0;
//    }
//
//    private int findDoctorAllMessage(String doctor) {
//        // 签约未读消息总数
//        int sign = messageDao.amountUnreadByReceiver(doctor);
//        // 体征指标未读消息总数
//        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
//        //系统消息
//        int systemMessage = messageDao.amountUnreadSystemByReceiver(doctor);
//        Integer doctorCount = 0;
//        Integer patientCount = 0;
//        JSONObject json = new JSONObject();
//        getImMsgAmount(json, doctor);
//        if (json.containsKey("imMsgCount")) {
//            JSONObject jsonC = json.getJSONObject("imMsgCount");
//            if (jsonC.containsKey("doctor")) {
//                doctorCount = jsonC.getInt("doctor");
//            }
//            if (jsonC.containsKey("patient")) {
//                patientCount = jsonC.getInt("patient");
//            }
//        }
//
//        return sign + healthIndex + systemMessage + doctorCount + patientCount;
//    }
//
//    private void getImMsgAmount(JSONObject obj, String doctor) {
//        String urlall = url + "/api/v1/chats/msg/amount?user_id=" + doctor;
//        String response = HttpClientUtil.get(urlall, "UTF-8");
//        obj.put("imMsgCount", response);
//    }
//
//    private Integer getImMsgAmount(String doctor) throws Exception {
//        /**
//         * {"msg":"获取消息总数成功!","data":{"imMsgCount":"{\"doctor\":0,\"patient\":0}","healthIndex":{"amount":0},"sign":{"amount":0}},"status":200}
//         */
//        return findDoctorAllMessage(doctor);
//    }
//}

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

@ -186,6 +186,7 @@ public class DoctorWorkTimeService {
        return json;
    }
    public Date getDoctorWeek(String doctor, Integer week) throws Exception {
        Date json = new Date();
        Calendar calendar = Calendar.getInstance();

+ 0 - 125
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java

@ -6,9 +6,6 @@ import com.yihu.wlyy.statistics.dao.QuartzJobConfigDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.etl.cache.Cache;
import com.yihu.wlyy.statistics.job.check.CheckSignJob;
import com.yihu.wlyy.statistics.job.message.FollowupPlanJob;
import com.yihu.wlyy.statistics.job.message.HealthMessageJob;
import com.yihu.wlyy.statistics.job.message.NoticeJob;
import com.yihu.wlyy.statistics.util.QuartzHelper;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import org.springframework.beans.BeanUtils;
@ -39,11 +36,6 @@ public class JobService {
    @Autowired
    private QuartzJobConfigDao wlyyJobConfigDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
@ -254,12 +246,6 @@ public class JobService {
        }
    }
    @Transactional
    @Async("dbExtractExecutor")
    public void startaaaa() throws Exception {
        quartzHelper.startNow(HealthMessageJob.class, UUID.randomUUID().toString().replace("-", ""), new HashMap<>());
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
@ -348,115 +334,4 @@ public class JobService {
        }
    }
    public void startHealthMessageJob() throws Exception {
        if (!quartzHelper.isExistJob(HealthMessageJob.jobKey)) {
            quartzHelper.addJob(HealthMessageJob.class, HealthMessageJob.cron, HealthMessageJob.jobKey, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopHealthMessageJob() throws Exception {
        if (quartzHelper.isExistJob(HealthMessageJob.jobKey)) {
            quartzHelper.removeJob(HealthMessageJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }
    public void productHealthDataByOneDay(String day) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(day);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        Map<String, String> params = new HashMap<String, String>();
        //往quartz框架添加任务
        params.put("now", yesterday);
        params.put("yesterday", day);
        quartzHelper.startNow(HealthMessageJob.class, HealthMessageJob.jobKey + UUID.randomUUID().toString().replace("-", ""), params);
        //Thread.sleep(40000L);
    }
    public void productHealthDataByDayToDay(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++) {
            productHealthDataByOneDay(getYesterday(i, startDate));
        }
    }
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse("2016-10-20");
        Date endDate = sdf.parse("2016-10-28");
        System.out.println(daysBetween(startDate, endDate));
        System.out.println(getYesterday(0, startDate));
    }
    public void startNoticeJob() throws Exception {
        if (!quartzHelper.isExistJob(NoticeJob.jobKey)) {
            quartzHelper.addJob(NoticeJob.class, NoticeJob.jobCron, NoticeJob.jobKey, new HashMap<>());
            // quartzHelper.startNow(NoticeJob.class, UUID.randomUUID().toString().replace("-", ""), new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopNoticeJob() throws Exception {
        if (quartzHelper.isExistJob(NoticeJob.jobKey)) {
            quartzHelper.removeJob(NoticeJob.jobKey);
        } else {
            throw new Exception("已经停止");
        }
    }
    /*******************************
     * 随访计划任务
     *******************************************************/
    @Value("${spring.followupMessage.jobId}")
    private String followupJob;
    @Value("${spring.followupMessage.cron}")
    private String followupJobCron;
    public void startFollowupPlantJob() throws Exception {
        if (!quartzHelper.isExistJob(followupJob)) {
            quartzHelper.addJob(FollowupPlanJob.class, followupJobCron, followupJob, new HashMap<>());
        } else {
            throw new Exception("已经启动");
        }
    }
    public void stopFollowupPlantJob() throws Exception {
        if (quartzHelper.isExistJob(followupJob)) {
            quartzHelper.removeJob(followupJob);
        } else {
            throw new Exception("已经停止");
        }
    }
    public void startNoticeJobNow() throws Exception {
        quartzHelper.startNow(NoticeJob.class, UUID.randomUUID().toString(), new HashMap<>());
    }
    public void startHealthMessageJobNow() throws Exception {
        quartzHelper.startNow(HealthMessageJob.class, UUID.randomUUID().toString(), new HashMap<>());
    }
}

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

@ -206,6 +206,22 @@ public class ApplicationEvent implements ApplicationListener<ContextRefreshedEve
                logger.info("sicard_query_job  job exist");
            }
            //待分配健管师消息提醒 从统计工程中转到到job工程
            if (!quartzHelper.isExistJob(HealthMessageJob.jobKey)) {
                quartzHelper.addJob(HealthMessageJob.class, HealthMessageJob.cron, HealthMessageJob.jobKey, new HashMap<String, Object>());
                logger.info("HealthMessageJob  job success");
            } else {
                logger.info("HealthMessageJob  job exist");
            }
            //签约消息提醒 从统计工程中转到到job工程
            if (!quartzHelper.isExistJob(NoticeJob.jobKey)) {
                quartzHelper.addJob(NoticeJob.class, NoticeJob.jobCron, NoticeJob.jobKey, new HashMap<String, Object>());
                logger.info("NoticeJob  job success");
            } else {
                logger.info("NoticeJob  job exist");
            }
            // 启动redis 消息队列线程
            logger.info("redis message start");
            new Thread(redisThread).start();

+ 150 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/HealthMessageJob.java

@ -0,0 +1,150 @@
package com.yihu.wlyy.job;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.job.QuartzJobLogDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.task.NoticeJobPushMsgTask;
import com.yihu.wlyy.util.DBExtract;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Administrator on 2016.10.25.
 */
@Component
@Scope("prototype")
public class HealthMessageJob implements Job {
    public static String jobKey = "Health_Message_JOB";
    public static String cron = "0 0 8 * * ?";
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(jobKey);
            quartzJobLog.setJobName(jobKey);
            String yesterday = jobExecutionContext.getMergedJobDataMap().getString("yesterday");
            String now = jobExecutionContext.getMergedJobDataMap().getString("now");
            if (StringUtils.isEmpty(yesterday)) {
                yesterday = getYesterday(-1, new Date());
            }
            if (StringUtils.isEmpty(now)) {
                now = getYesterday(0, new Date());
            }
            //删除原来的数据
            String deleteSql = "delete from wlyy_message where type=3 and czrq >= '" + yesterday + " 00:00:00'and czrq <= '" + now + " 00:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql = "select admin_team_code  from wlyy_sign_family " +
                    " where  status >0 and type='2' " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            String countSql = "select count(id) from wlyy_sign_family " +
                    " where  status >0 and type='2'  " +
                    " and apply_date >='" + yesterday + " 00:00:00' and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '')";
            List<SignFamily> signFamilyList = dbExtract.extractByPage(SignFamily.class, sql, countSql, true, jdbcTemplate);
            Map<Long, List<SignFamily>> signFamilyMap = new HashMap<Long, List<SignFamily>>();
            for (int i = 0; i < signFamilyList.size(); i++) {
                SignFamily signFamilyTemp = signFamilyList.get(i);
                if (signFamilyMap.containsKey(signFamilyTemp.getAdminTeamId())) {
                    signFamilyMap.get(signFamilyTemp.getAdminTeamId()).add(signFamilyTemp);
                } else {
                    List<SignFamily> signFamilies = new ArrayList<>();
                    signFamilies.add(signFamilyTemp);
                    signFamilyMap.put(signFamilyTemp.getAdminTeamId(), signFamilies);
                }
            }
            JSONArray jsonArray = new JSONArray();
            for (Map.Entry<Long, List<SignFamily>> entry : signFamilyMap.entrySet()) {
                //得到未分配的所有数目
                countSql = "select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2'  " +
                        "  and apply_date<'" + now + " 00:00:00' and  (doctor_health is null or doctor_health = '') and admin_team_code=" + entry.getKey() + "";
                Integer allCount = jdbcTemplate.queryForObject(countSql, Integer.class);
                //得到团队的leader
                sql = "select leader_code from wlyy_admin_team m where m.id= ?";
                String teamLeader = jdbcTemplate.queryForObject(sql, String.class, entry.getKey());
                Message message = new Message();
                message.setType(3);
                message.setRead(0);
                message.setOver("0");
                message.setDel("1");
                message.setSender("system");
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(yesterday + " 23:59:00"));
                message.setState(1);
                String title = "新增系统消息";
                message.setTitle(title);
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
                String content = dateFormat2.format(dateFormat1.parse(yesterday)) + "新增" + entry.getValue().size() + "个签约居民待分配健管师,目前共" + allCount + "人待处理";
                message.setContent(content);
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(teamLeader);
                messageDao.save(message);
                quartzJobLogDao.save(quartzJobLog);
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", teamLeader);
                json.put("type", "D_NH_01");
                json.put("title", title);
                json.put("msg", content);
                json.put("data", "");
                jsonArray.add(json);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成" + yesterday + "的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            // 推送消息给医生
            NoticeJobPushMsgTask.url = url;
            // 推送消息给医生
            NoticeJobPushMsgTask.getInstance().put(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    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 void main(String[] args) {
    }
}

+ 221 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/job/NoticeJob.java

@ -0,0 +1,221 @@
package com.yihu.wlyy.job;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.job.QuartzJobLogDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.task.NoticeJobPushMsgTask;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/11/7.
 */
@Component
@Scope("prototype")
public class NoticeJob implements Job {
    public static String jobKey = "Notice_JOB";
    public static String jobCron = "0 0 8,14 * * ?"; //每天8点,14点,20 点执行一次
    private static String noticeKey1 = "D_ST_01";//专科
    private static String noticeKey2 = "D_ST_02";//全科
    private static String noticeKey3 = "D_ST_03";//健康管理师
    private static String noticeTitle = "系统消息";
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private QuartzJobLogDao dbStorage;
    @Autowired
    private DoctorDao doctorDao;
    @Value("${systemConfig.msg_push_server}")
    private String url;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(jobKey);
        quartzJobLog.setJobName(jobKey);
        try {
            List<Doctor> doctors = doctorDao.findAllDoctors();
            //得到所有未发送的医生的通知
            Map<String, JSONObject> maps = new HashMap<>();
            //发送通知
            for (Doctor doctor : doctors) {
                //判断医生是不是在工作时间内
                String noticeContent1 = " 您当前有[zxsize]条未处理消息,其中[qysize]条为签约消息。请尽快处理~";
                String noticeContent2 = " 您当前有[zxsize]条未处理消息,请尽快处理~";
                String noticeContent3 = " 您当前有[qysize]条签约消息待处理,请尽快处理~";
                String workTime = "";
                try {
                    workTime = doctorWorkTimeService.isDoctorWorking(doctor.getCode(), -1).getString("status");
                } catch (Exception e) {
                }
                if ("1".equals(workTime)) {
                    //得到医生多少条咨询消息
                    Integer zxsize = getDoctorMesssageCount(doctor.getCode(), 1);
                    //得到医生多少条签约消息
                    Integer qysize = getDoctorMesssageCount(doctor.getCode(), 2);
                    //如果既有签约又有咨询
                    if (zxsize > 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent1 = noticeContent1.replace("[zxsize]", zxsize + "");
                        noticeContent1 = noticeContent1.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent1);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize > 0 && qysize == 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent2 = noticeContent2.replace("[zxsize]", zxsize + "");
                        jo.put("content", noticeContent2);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                    //只有咨询
                    if (zxsize == 0 && qysize > 0) {
                        JSONObject jo = new JSONObject();
                        noticeContent3 = noticeContent3.replace("[qysize]", qysize + "");
                        jo.put("content", noticeContent3);
                        jo.put("level", doctor.getLevel());
                        maps.put(doctor.getCode(), jo);
                    }
                }
            }
            JSONArray jsonArray = new JSONArray();
            //发送通知
            for (Map.Entry<String, JSONObject> entry : maps.entrySet()) {
                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", entry.getKey());
                json.put("type", getType(entry.getValue().getInt("level")));
                json.put("title", noticeTitle);
                json.put("msg", entry.getValue().getString("content"));
                json.put("data", "");
                jsonArray.add(json);
            }
            // 推送消息给医生
            NoticeJobPushMsgTask.url = url;
            // 推送消息给医生
            NoticeJobPushMsgTask.getInstance().put(jsonArray);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知成功");
            quartzJobLog.setJobType("1");
            dbStorage.save(quartzJobLog);
        } catch (Exception e) {
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("通知失败");
            quartzJobLog.setJobType("0");
            dbStorage.save(quartzJobLog);
            e.printStackTrace();
        }
    }
    private String getType(Integer level) {
        switch (level) {
            case 1: {
                //专科
                return noticeKey1;
            }
            case 2: {
                //全科
                return noticeKey2;
            }
            case 3: {
                //健康管理师
                return noticeKey3;
            }
        }
        return "";
    }
    /**
     * 得到医生的未读数目
     *
     * @param doctorCode 医生code
     * @param type       1是咨询 2个签约 3是体征
     * @return
     */
    private Integer getDoctorMesssageCount(String doctorCode, int type) throws Exception {
        switch (type) {
            case 1: {
                return getImMsgAmount(doctorCode);
            }
            case 2: {
                String sql = "select count(a.id) from wlyy_message a where a.type =1 and a.has_read=1 and a.receiver=?";
                return jdbcTemplate.queryForObject(sql, Integer.class, doctorCode);
            }
        }
        return 0;
    }
    private int findDoctorAllMessage(String doctor) {
        // 签约未读消息总数
        int sign = messageDao.amountUnreadByReceiver(doctor);
        // 体征指标未读消息总数
        int healthIndex = messageDao.amountUnreadHealthByReceiver(doctor);
        //系统消息
        int systemMessage = messageDao.amountUnreadSystemByReceiver(doctor);
        Integer doctorCount = 0;
        Integer patientCount = 0;
        JSONObject json = new JSONObject();
        getImMsgAmount(json, doctor);
        if (json.containsKey("imMsgCount")) {
            JSONObject jsonC = json.getJSONObject("imMsgCount");
            if (jsonC.containsKey("doctor")) {
                doctorCount = jsonC.getInt("doctor");
            }
            if (jsonC.containsKey("patient")) {
                patientCount = jsonC.getInt("patient");
            }
        }
        return sign + healthIndex + systemMessage + doctorCount + patientCount;
    }
    private void getImMsgAmount(JSONObject obj, String doctor) {
        String urlall = url + "/api/v1/chats/msg/amount?user_id=" + doctor;
        String response = httpClientUtil.get(urlall, "UTF-8");
        obj.put("imMsgCount", response);
    }
    private Integer getImMsgAmount(String doctor) throws Exception {
        /**
         * {"msg":"获取消息总数成功!","data":{"imMsgCount":"{\"doctor\":0,\"patient\":0}","healthIndex":{"amount":0},"sign":{"amount":0}},"status":200}
         */
        return findDoctorAllMessage(doctor);
    }
}

+ 4 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/repository/message/MessageDao.java

@ -89,4 +89,8 @@ public interface MessageDao extends PagingAndSortingRepository<Message, Long>, J
    //根据续方关联code查询团队长分配健管师消息
    @Query("from Message a where a.type = 8 and a.state=0 and a.del='1' and a.over='0' and relationCode = ?1  ")
    Message findByRelationCode(String relationCode);
    @Query("select count(a) from Message a where a.read = 1  and a.receiver=?1 and a.type=3 ")
    int amountUnreadSystemByReceiver(String doctor);
}

+ 112 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/app/scheduling/DoctorWorkTimeService.java

@ -266,6 +266,118 @@ public class DoctorWorkTimeService extends BaseService {
        }
    }
    /**
     * 医生是否在工作
     *
     * @param doctor 医生
     * @return
     */
    public JSONObject isDoctorWorking(String doctor, Integer week) throws Exception {
        JSONObject json = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        if (week < 0) {
            week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 0) {
                week = 7;
            }
        }
        // 医生工作时间设置
        Map<String, Object> result = findDoctorWeekWork(doctor, String.valueOf(week));
        if (result.get("workTime") == null) {
            // 医生未设置时,默认7*24小时工作
            json.put("status", "1");
            json.put("msg", "医生当前接受咨询");
        } else {
            WlyyDoctorWorkTime doctorWorkTime = (WlyyDoctorWorkTime) result.get("workTime");
            if (doctorWorkTime.getReceiveConsult().equals("0")) {
                // 医生设置不接受咨询
                json.put("status", "0");
                json.put("msg", "医生不接受咨询");
            } else {
                if (StringUtils.isEmpty(doctorWorkTime.getMorningBegin()) && StringUtils.isEmpty(doctorWorkTime.getMorningEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getAfternoonBegin()) && StringUtils.isEmpty(doctorWorkTime.getAfternoonEnd())
                        && StringUtils.isEmpty(doctorWorkTime.getNightBegin()) && StringUtils.isEmpty(doctorWorkTime.getNightEnd())) {
                    // 医生未设置工作时间,默认7*24小时工作
                    json.put("status", "1");
                    json.put("msg", "医生当前接受咨询");
                } else {
                    if (result.get("workWeek") != null) {
                        // 当前工作日已设置工作时间
                        int flag = 0;
                        WlyyDoctorWorkTime workTime = (WlyyDoctorWorkTime) result.get("workTime");
                        WlyyDoctorWorkWeek workWeek = (WlyyDoctorWorkWeek) result.get("workWeek");
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        String current = (hour < 10 ? ("0" + hour) : hour) + ":" + (hour < 10 ? ("0" + minute) : minute);
                        // 早上
                        if (workWeek.getMorning().equals("1")) {
                            String currentStart = workTime.getMorningBegin();
                            String currentEnd = workTime.getMorningEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 下午
                        if (workWeek.getAfternoon().equals("1")) {
                            String currentStart = workTime.getAfternoonBegin();
                            String currentEnd = workTime.getAfternoonEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        // 晚上
                        if (workWeek.getNight().equals("1")) {
                            String currentStart = workTime.getNightBegin();
                            String currentEnd = workTime.getNightEnd();
                            if (currentStart.length() == 4) {
                                currentStart = "0" + currentStart;
                            }
                            if (currentEnd.length() == 4) {
                                currentEnd = "0" + currentEnd;
                            }
                            if (current.compareTo(currentStart) >= 0 &&
                                    current.compareTo(currentEnd) < 0) {
                                flag = 1;
                            }
                        }
                        if (flag == 1) {
                            json.put("status", "1");
                            json.put("msg", "医生当前接受咨询");
                        } else {
                            json.put("status", "2");
                            json.put("msg", "医生当前不在工作时间");
                        }
                    } else {
                        json.put("status", "2");
                        json.put("msg", "医生当前不在工作时间");
                    }
                }
            }
        }
        return json;
    }
    /**
     * 医生是否在工作
     *

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

@ -1302,8 +1302,8 @@ public class FamilyContractService extends BaseService {
            }
            // 更新签约日期
            sf.setBegin(DateUtil.stringToDate(DateUtil.getSignYear() + "-07-01 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
            sf.setEnd(DateUtil.stringToDate(DateUtil.getSignYear() + 1 + "-07-01 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
            sf.setBegin(new Date());
            sf.setEnd(DateUtil.stringToDate(DateUtil.getSignYear() + 1 + "-06-30 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
            // 改为签约生效

+ 139 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/task/NoticeJobPushMsgTask.java

@ -0,0 +1,139 @@
package com.yihu.wlyy.task;
import com.yihu.wlyy.util.NoticeImUtill;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.LinkedBlockingQueue;
public class NoticeJobPushMsgTask {
	public static String url="";
	private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
	private static NoticeJobPushMsgTask instance;
	private static Object lock = new Object();
	public static NoticeJobPushMsgTask getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new NoticeJobPushMsgTask();
				instance.run();
			}
		}
		return instance;
	}
	/**
	 * 添加一条推送消息
	 * @param receiver 接收人
	 * @param type 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public void put(String receiver, String type, String title, String msg, String data) {
		try {
			JSONObject json = new JSONObject();
			json.put("receiver", receiver);
			json.put("type", type);
			json.put("title", title);
			json.put("msg", msg);
			json.put("data", data);
			queue.put(json);
		} catch (Exception e) {
			logger.error("添加到消息队列失败!", e);
			e.printStackTrace();
		}
	}
	public void put(JSONArray array) {
		if (array == null || array.size() == 0) {
			return;
		}
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			if (json == null) {
				continue;
			}
			try {
				queue.put(json);
			} catch (Exception e) {
				logger.error("批量添加到消息队列失败!", e);
			}
		}
	}
	private void run() {
		new Thread(new ConsumerTask()).start();
	}
	// 消费者
	class ConsumerTask implements Runnable {
		@Override
		public void run() {
			try {
				while (true) {
					// 如果queue为空,则当前线程会堵塞,直到有新数据加入
					JSONObject json = queue.take();
					logger.info("发送前:"+json);
					// 推送平台消息
					String receiver = json.containsKey("receiver") ? json.getString("receiver") : "";
					String type = json.containsKey("type") ? json.getString("type") : "";
					String title = json.containsKey("title") ? json.getString("title") : "";
					String msg = json.containsKey("msg") ? json.getString("msg") : "";
					String data = json.containsKey("data") ? json.getString("data") : "";
					boolean res = pushMessage(receiver, type, title, msg, data);
					if (res) {
						logger.info("消息推送成功!");
					} else {
						logger.error("消息推送失败!");
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	/**
	 * 消息推送
	 *
	 * @param receiver 消息接收人
	 * @param msgType 消息类型
	 * @param title 消息标题
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public static boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
		try {
			//List<NameValuePair> params = new ArrayList<NameValuePair>();
			//params.add(new BasicNameValuePair("to", receiver));
			//params.add(new BasicNameValuePair("content", msg));
			//params.add(new BasicNameValuePair("contentType", msgType));
			//params.add(new BasicNameValuePair("title", title));
			//params.add(new BasicNameValuePair("summary", data));
			//String response = HttpClientUtil.post(url, params, "UTF-8");
			org.json.JSONObject participants = new org.json.JSONObject();
			participants.put("system",0);
			participants.put(receiver,0);
			org.json.JSONObject sessionObj  = NoticeImUtill.createSession(url,participants,"0","系统消息","");
			if(sessionObj.getInt("status")==-1){
				throw  new RuntimeException(sessionObj.getString("message"));
			}
			org.json.JSONObject session = sessionObj.getJSONObject("data");
			NoticeImUtill.sendImMsg(url,"system","系统",session.getString("id"),"1", msg,msgType);
			return true;
		} catch (Exception e) {
			logger.error("push message error:", e);
		}
		return false;
	}
}

+ 65 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/DBExtract.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.util;
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.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 数据库抽取
 */
@Component
@Scope("prototype")
public class DBExtract<T> {
    Integer pageSize=100000;
    /**
     * 不分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<T> extract(Class<T> clazz,String sql,JdbcTemplate jdbcTemplate){
        List<T> returnList= jdbcTemplate.query(sql,new BeanPropertyRowMapper(clazz));
        return returnList;
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @param pageSize 每页显示多少 默认10000
     * @param isMultithreading 是否多线程抽取 默认否
     * @return
     */
    public List<T> extractByPage(Class<T> clazz,String sql,String countSql,int pageSize,Boolean isMultithreading,JdbcTemplate jdbcTemplate)throws  Exception{
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @param isMultithreading 是否多线程抽取 默认否
     * @return
     */
    public List<T> extractByPage(Class<T> clazz,String sql,String countSql,Boolean isMultithreading,JdbcTemplate jdbcTemplate)throws  Exception{
        if(StringUtils.isEmpty(countSql)){
            return extract(clazz,sql,jdbcTemplate);
        }
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
    /**
     * 分页抽取
     * @param clazz
     * @param sql
     * @return
     */
    public List<Object> extractByPage(Class<T> clazz,String sql,JdbcTemplate jdbcTemplate)throws  Exception{
        Boolean isMultithreading=false;
        String countSql="";
        return SpringUtil.getBean(DBPageExtract.class).extractByPage(clazz,sql,countSql,pageSize,isMultithreading,jdbcTemplate);
    }
}

+ 156 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/DBPageExtract.java

@ -0,0 +1,156 @@
package com.yihu.wlyy.util;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by Administrator on 2016.10.16.
 * 分页抽取器
 */
@Component
@Scope("prototype")
public class DBPageExtract<T> {
    private  List<T> returnList=new ArrayList<T>();
    public synchronized void addData( List<T> dataList) {
         returnList.addAll(dataList);
    }
    public List<T> extractByPage(Class<T> clazz, String sql, String countSql, int pageSize, Boolean isMultithreading,JdbcTemplate jdbcTemplate) throws Exception{
        if(!StringUtils.isEmpty(countSql)){
            isMultithreading=true;
        }
        if(isMultithreading){
            if(StringUtils.isEmpty(countSql)){
                throw new Exception("countSql is null");
            }
            return MultiThreadExtract(clazz, sql,countSql, pageSize,jdbcTemplate);
        }else{
            return noMultiThreadExtract(clazz, sql, pageSize,jdbcTemplate);
        }
    }
    /**
     * 不用多线程抽取
     * @param clazz
     * @param sql
     * @param pageSize
     * @return
     */
    private List<T> noMultiThreadExtract(Class<T> clazz, String sql, int pageSize,JdbcTemplate jdbcTemplate) {
        List<T> returnList=new ArrayList<T>();
        int start=0;
        int page=1;
        while (true){
            String finalSql=sql+" limit "+start+","+pageSize; //拼凑分页的语句
            List<T> listTemp= jdbcTemplate.query(finalSql,new BeanPropertyRowMapper(clazz));
            returnList.addAll(listTemp);//添加到list里面
            //判断是都是最后页面
            if(listTemp.size()!=pageSize){
                listTemp.clear();
                break;
            }else{
                start =page*pageSize;
                page++;
                listTemp.clear();
            }
        }
        return returnList;
    }
    /**
     * 多线程抽取数据
     * @param clazz
     * @param sql
     * @param pageSize
     * @return
     */
    private   List<T> MultiThreadExtract(Class<T> clazz, String sql,String countSql, int pageSize,JdbcTemplate jdbcTemplate)  {
        try{
            //得到数据的总数
            Integer dataCount=getCount(countSql,jdbcTemplate);
            //根据count 计算出 总共要执行几次
            Integer forCount=getForCount(dataCount,pageSize);
            forCount++;
            //綫程返回值的值
            List<AsyncResult<Boolean>> asyncResultPool=new ArrayList<AsyncResult<Boolean>>();
            for(int page=0;page<forCount;page++){
                //启动多线程采集数据
                AsyncResult<Boolean> future= multiExtractData(sql,page*pageSize,pageSize,clazz,jdbcTemplate);
                asyncResultPool.add(future);
            }
            ///循环判断,等待获取结果信息
            while (true){
                //得到迭代器
                Iterator<AsyncResult<Boolean>> asyncResultIterator=asyncResultPool.iterator();
                //判断有没有下一个
                while (asyncResultIterator.hasNext()){
                    AsyncResult<Boolean> asyncResult= asyncResultIterator.next();
                    if(asyncResult.isDone()){
                        //如果做完了就移除迭代器
                        asyncResultIterator.remove();
                    }else{
                        Thread.sleep(500L);
                    }
                }
                //如果一直移除到没有下一个就跳出循环 说明数据已经采集完成
                if(!asyncResultIterator.hasNext()){
                    break;
                }
            }
            return returnList;
        }catch (Exception e){
            e.printStackTrace();
            //如果多线程错误 就改用单线程
            return noMultiThreadExtract(clazz,sql,pageSize,jdbcTemplate);
        }
    }
    private Integer getForCount(Integer dataCount, int pageSize) {
        //根据所有的数据取余数
        int yushu=dataCount%pageSize;
        int page=dataCount/pageSize;
        if(yushu==0){
            //如果没有余数 返回总的页数
            return page;
        }else{
            //如果有余数 页数多加1
            page++;
            return page;
        }
    }
    private Integer getCount(String countSql,JdbcTemplate jdbcTemplate) {
        Integer countMap= jdbcTemplate.queryForObject(countSql,Integer.class);
        return countMap;
    }
    /**
     * 多线程采集数据
     * @param sql
     * @param start
     * @param pageSize
     * @param clazz
     * @return
     */
    @Async("dbExtractExecutor")
    private AsyncResult<Boolean> multiExtractData(String sql, int start, int pageSize, Class<T> clazz, JdbcTemplate jdbcTemplate) {
        String finalSql=sql+" limit "+start+","+pageSize; //拼凑分页的语句
        List<T> listTemp= jdbcTemplate.query(finalSql,new BeanPropertyRowMapper(clazz));
        addData(listTemp);
        return new AsyncResult<>(true);
    }
}

+ 128 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/NoticeHttpClientUtil.java

@ -0,0 +1,128 @@
package com.yihu.wlyy.util;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class NoticeHttpClientUtil {
	/**
	 * 发送post请求
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String post(String url, List<NameValuePair> params, String chatSet) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 发送get请求
	 * @param url 请求地址
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String get(String url, String chatSet) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public static String postBody(String url,JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	public static void putBody(String url,JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		restTemplate.put(url, formEntity, String.class);
	}
}

+ 221 - 0
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/util/NoticeImUtill.java

@ -0,0 +1,221 @@
package com.yihu.wlyy.util;
import org.json.JSONObject;
/**
 * Created by 卓 on 2017/1/13.
 */
public class NoticeImUtill {
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public static String sendImMsg(String baseUrl,String from,String fromName, String sessionId, String contentType, String content,String businessType) {
        String imAddr = baseUrl + "/api/v2/sessions/"+sessionId+"/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("session_id", sessionId);
        params.put("business_type", businessType);
        String response = NoticeHttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public static String sendTopicIM(String baseUrl,String from,String fromName, String topicId, String contentType, String content) {
        String url = baseUrl+ ("api/v2/sessions/topic/"+topicId+"/messages");
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("topic_id", topicId);;
        String response = NoticeHttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 结束议题
     *
     * @param topicId  议题ID
     * @param endUser  结束人
     * @param endUserName 结束人名字
     * @param sessionId 会话ID
     */
    public static JSONObject endTopics(String baseUrl,String sessionId,String endUser, String endUserName,String topicId) {
        String imAddr = baseUrl + "api/v2/sessions/"+sessionId+"/topics/"+topicId+"/ended";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("end_user", endUser);
        params.put("end_user_name",endUserName);
        params.put("topic_id", topicId);
        String ret = NoticeHttpClientUtil.postBody(imAddr,params);
        JSONObject obj  = null;
        try{
            obj = new JSONObject(ret);
        }catch (Exception e){
            return null;
        }
        return obj;
    }
    /**
     * 议题邀请人员
     * @param user 结束人名字
     * @param sessionId 会话ID
     */
    public static void updateTopicUser(String baseUrl,String sessionId,String user) {
        String imAddr = baseUrl + "api/v2/sessions/"+sessionId+"/participants/"+user;
        JSONObject params = new JSONObject();
        params.put("user", user+":"+0);
        NoticeHttpClientUtil.putBody(imAddr,params);
    }
    /**
     * 创建议题
     *
     * @param topicId  议题ID
     * @param topicName  议题名称
     * @param participants 成员
     */
    public static JSONObject createTopics(String baseUrl,String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
        String imAddr = baseUrl + "api/v2/sessions/"+topicId+"/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id", topicId);
        params.put("topic_name", topicName);
        params.put("participants", participants.toString());
        params.put("messages", messages.toString());
        params.put("session_id", sessionId);
        params.put("session_type", sessionType);
        String ret = NoticeHttpClientUtil.postBody(imAddr,params);
        JSONObject obj  = null;
        try{
            obj = new JSONObject(ret);
        }catch (Exception e){
            return null;
        }
        return obj;
    }
    /**
     * 创建会话(system)
     *
     */
    public static JSONObject createSession(String baseUrl,JSONObject participants,String sessionType,String sessionName,String sessionId) {
        String imAddr = baseUrl + "api/v2/sessions";
        JSONObject params = new JSONObject();
        params.put("participants", participants.toString());
        params.put("session_name", sessionName);
        params.put("session_type", sessionType);
        params.put("session_id", sessionId);
        String ret = NoticeHttpClientUtil.postBody(imAddr,params);
        JSONObject obj  = null;
        try{
            obj = new JSONObject(ret);
        }catch (Exception e){
            return null;
        }
        return obj;
    }
    /**
     * 获取会话实例的消息对象
     * @param senderId
     * @param senderName
     * @param title
     * @param description
     * @param images
     * @return
     */
    public static JSONObject getCreateTopicMessage(String senderId,String senderName,String title,String description,String images){
        JSONObject messages = new JSONObject();
        messages.put("description",description);
        messages.put("title",title);
        messages.put("img",images);
        messages.put("sender_id",senderId);
        messages.put("sender_name",senderName);
        return messages;
    }
    public static JSONObject getTopicMessage(String baseUrl,String topicId,String startMsgId,String endMsgId,int page,int pagesize,String uid){
        String url = baseUrl
                + "api/v2/sessions/topic/"+topicId+"/messages?topic_id="+topicId+"&end="+startMsgId
                +"&start="+(endMsgId==null?"":endMsgId)+"&page="+page+"&pagesize="+pagesize+"&user="+uid;
        try{
            String ret = HttpClientUtil.get(url, "UTF-8");
            JSONObject obj = new JSONObject(ret);
            if(obj.getInt("status")==-1){
                throw new RuntimeException(obj.getString("message"));
            }else{
                return  obj.getJSONObject("data");
            }
        }catch (Exception e){
            return null;
        }
    }
    /**
     * 删除对应的成员信息在MUC模式中
     * @param userId
     * @param oldUserId
     * @param sessionId
     * @return
     */
    public static JSONObject deleteMucUser(String baseUrl,String userId,String oldUserId,String sessionId) throws  Exception{
        String url = baseUrl
                + "api/v2/sessions/"+sessionId+"/participant/update";
        try{
            JSONObject params = new JSONObject();
            params.put("user_id", userId);
            params.put("old_user_id", oldUserId);
            params.put("session_id", sessionId);
            String ret = NoticeHttpClientUtil.postBody(url,params);
            JSONObject obj = new JSONObject(ret);
            if(obj.getInt("status")==-1){
                throw new RuntimeException("人员更换失败!");
            }else{
                return obj;
            }
        }catch (Exception e){
           throw new RuntimeException("人员更换失败!");
        }
    }
    /**
     * 获取议题
     * @param topicId
     * @return
     */
    public static JSONObject getTopic(String baseUrl,String topicId) throws  Exception{
        String url =baseUrl
                + "api/v2/sessions/topics/"+topicId+"?topic_id="+topicId;
        try{
            String ret = HttpClientUtil.get(url,"utf-8");
            JSONObject obj = new JSONObject(ret);
            if(obj.getInt("status")==-1){
                throw new RuntimeException("获取议题失败!");
            }else{
                return obj;
            }
        }catch (Exception e){
            throw new RuntimeException("获取议题失败!");
        }
    }
}

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

@ -1089,7 +1089,7 @@ public class FamilyContractService extends BaseService {
//        }
        // 更新签约日期
        sf.setBegin(DateUtil.stringToDate(DateUtil.getSignYear() + "-07-01 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
        sf.setBegin(new Date());
        sf.setEnd(DateUtil.stringToDate(DateUtil.getSignYear() + 1 + "-06-30 23:59:59", "yyyy-MM-dd HH:mmm:ss"));
        sf.setOpenid(patient.getOpenid());
@ -1380,7 +1380,7 @@ public class FamilyContractService extends BaseService {
            // 更新签约日期
            //sf.setBegin(DateUtil.stringToDate(DateUtil.getSignYear() + "-07-01 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
            sf.setBegin(new Date());
            sf.setEnd(DateUtil.stringToDate(DateUtil.getSignYear() + 1 + "-07-01 00:00:00", "yyyy-MM-dd HH:mmm:ss"));
            sf.setEnd(DateUtil.stringToDate(DateUtil.getSignYear() + 1 + "-06-30 23:59:59", "yyyy-MM-dd HH:mmm:ss"));
            // 改为签约生效

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

@ -587,10 +587,10 @@ public class StatisticsESService {
    public JSONObject getRenewPercent(String level, String area, String year) throws Exception {
        String renewIndex = "";
        if ("1".equals(level)) {
        if ("5".equals(level)) {
            //团队的续签量
            renewIndex = "42";
        } else if ("2".equals(level)) {
        } else if ("4".equals(level)) {
            //社区的续签量
            renewIndex = "43";
        } else if ("3".equals(level)) {
@ -947,7 +947,9 @@ public class StatisticsESService {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String low_level = String.valueOf(org.springframework.util.StringUtils.isEmpty(lowLevel) ? (level + 1) : lowLevel);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (date.compareTo(dateFormat.format(new Date())) >= 0) {
            date = elasticsearchUtil.getQuotaTime();
        }
        List<SaveModel> esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel1(date, area, level, index, SaveModel.timeLevel_DDL, low_level, lowCode);
        if (esModelList != null && esModelList.size() > 0) {
@ -1455,6 +1457,9 @@ public class StatisticsESService {
        String low_level = String.valueOf(org.springframework.util.StringUtils.isEmpty(lowLevel) ? (level + 1) : lowLevel);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (date.compareTo(dateFormat.format(new Date())) >= 0) {
            date = elasticsearchUtil.getQuotaTime();
        }
        List<SaveModel> esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel0(date, area, level, index, SaveModel.timeLevel_DDL, low_level);
        if (esModelList != null && esModelList.size() > 0) {
@ -1548,8 +1553,10 @@ public class StatisticsESService {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String low_level = String.valueOf(org.springframework.util.StringUtils.isEmpty(lowLevel) ? (level + 1) : lowLevel);
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<SaveModel> esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel0(date, area, level, index, SaveModel.timeLevel_DDL, low_level);
        if (date.compareTo(dateFormat.format(new Date())) >= 0) {
            date = elasticsearchUtil.getQuotaTime();
        }
        List<SaveModel> esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel0( date, area, level, index, SaveModel.timeLevel_DDL, low_level);
        if (esModelList != null && esModelList.size() > 0) {
            for (SaveModel one : esModelList) {
@ -2196,13 +2203,13 @@ public class StatisticsESService {
//        Map<String, Object> expenseStatus1Sigjn = getByIndexSingle(date, area, level, "1",dateFormat);
        SaveModel expenseStatus1Sigjn = elasticsearchUtil.findOneDateQuotaLevel0(date, area, level, "1", "2");
        JSONObject jsonObject = new JSONObject();
        if (SaveModel.teamLevel.equals(level)) {
        if (Integer.valueOf(SaveModel.teamLevel)==level) {
            jsonObject.put("name", expenseStatus1Sigjn.getTeamName());
        } else if (SaveModel.OrgLevel.equals(level)) {
        } else if (Integer.valueOf(SaveModel.OrgLevel)==level) {
            jsonObject.put("name", expenseStatus1Sigjn.getHospitalName());
        } else if (SaveModel.townLevel.equals(level)) {
        } else if (Integer.valueOf(SaveModel.townLevel)==level) {
            jsonObject.put("name", expenseStatus1Sigjn.getTownName());
        } else if (SaveModel.cityLevel.equals(level)) {
        } else if (Integer.valueOf(SaveModel.cityLevel)==level) {
            jsonObject.put("name", expenseStatus1Sigjn.getCityName());
        }
        jsonObject.put("code", area);
@ -2286,14 +2293,17 @@ public class StatisticsESService {
        List<Map<String, Object>> resultList = new ArrayList<>();//续签量
        Map<String, Integer> renewMap = new HashMap<>(); //续签的的列表转map
        List<SaveModel> renewSaveModels = new ArrayList<SaveModel>();
        //签约量
        List<SaveModel> signSaveModels = new ArrayList<SaveModel>();
        if (StringUtils.isEmpty(lowCode)) {
            //续签量
            renewSaveModels = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index, "2", "", lowLevel);
            renewSaveModels = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index, "2","", low_level);
        } else {
            //续签量
            renewSaveModels = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index, "2",1, lowCode, "", low_level);
            renewSaveModels = elasticsearchUtil.findDateQuotaLevel1(DateUtil.getNextDay(new Date(),-1), DateUtil.getNextDay(new Date(),-1), area, level, index, "2",1,lowCode,"",low_level);
            //renewSaveModels = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index, "2",1,lowCode,"",low_level);
        }
        if (renewSaveModels != null && renewSaveModels.size() > 0) {
@ -2318,19 +2328,9 @@ public class StatisticsESService {
            //查询去年的签约转map
            List<SaveModel> yearsList = new ArrayList();
            if (StringUtils.isBlank(lowCode)) {
                yearsList = elasticsearchUtil.findListDateQuotaLevel0(lastDate, "", Integer.valueOf(low_level), "1", "2", "");
                yearsList = elasticsearchUtil.findDateQuotaLevel0(lastDate,lastDate, area, level, "1", "2", "",low_level);
            } else {
                if ("3".equals(lowCode)) {
                    //老年人
                    yearsList = elasticsearchUtil.findListDateQuotaLevel1(lastDate, "", Integer.valueOf(low_level), "17", "2", "", "3");
                } else if ("4".equals(lowCode)) {
                    //高血压
                    yearsList = elasticsearchUtil.findListDateQuotaLevel1(lastDate, "", Integer.valueOf(low_level), "17", "2", "", "1");
                } else if ("5".equals(lowCode)) {
                    //糖尿病
                    yearsList = elasticsearchUtil.findListDateQuotaLevel1(lastDate, "", Integer.valueOf(low_level), "17", "2", "", "2");
                } else {
                }
                yearsList = elasticsearchUtil.findDateQuotaLevel1(lastDate, lastDate, area, level, "17", "2", 1, lowCode,"",low_level);
            }
            Map<String, SaveModel> resultMap = new HashMap<>();
@ -2343,11 +2343,10 @@ public class StatisticsESService {
                    resultMap.put(one.getTown(), one);
                }
            });
            for (Map<String, Object> reMap : resultList) {
                reMap.put("amount", reMap.get("amount") != null ? Long.valueOf(reMap.get("amount").toString()) : 0L);
                int signNum = 0;
                int renewNum = 0;
                Integer renewNum = 0;
                //获取去年签约的人数 默认是上个年度的最后一天
                if (resultMap != null && resultMap.size() > 0) {
                    SaveModel one = resultMap.get(reMap.get("code").toString());
@ -2358,12 +2357,14 @@ public class StatisticsESService {
                }
                if (renewMap != null && renewMap.size() > 0) {
                    renewNum = renewMap.get(reMap.get("code").toString());
                    if (renewNum==null){
                        renewNum=0;
                    }
                } else {
                }
                reMap.put("renewNum", renewNum);
                reMap.put("signNum", signNum);
                reMap.put("rate", getRange(renewNum, signNum, 2));//续签率是 续签量/去年的签约数
            }
            if ((level == 2 && "5".equals(lowLevel)) || (level == 4) || (level == 3 && "5".equals(lowLevel))) {

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java

@ -32,7 +32,7 @@ import java.util.TreeMap;
 * Created by chenweida on 2017/10/13.
 */
@Controller
@RequestMapping(value = "/statistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = {RequestMethod.GET, RequestMethod.POST})
@RequestMapping(value = "/esstatistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = {RequestMethod.GET, RequestMethod.POST})
@Api(description = "ES统计查询")
public class EsStatisticsController extends BaseController {

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

@ -29,7 +29,7 @@ import java.util.*;
 * Created by lyr on 2016/08/16.
 */
@Controller
@RequestMapping(value = "/oldstatistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = {RequestMethod.GET,RequestMethod.POST})
@RequestMapping(value = "/statistics", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = {RequestMethod.GET,RequestMethod.POST})
@Api(description = "统计")
public class StatisticsController extends BaseController {