Bläddra i källkod

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

Shi Kejing 3 år sedan
förälder
incheckning
c8931db27f
33 ändrade filer med 4505 tillägg och 142 borttagningar
  1. 3 138
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  2. 2 1
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  3. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java
  4. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  5. 114 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/DoctorConsultEndpoint.java
  6. 196 3
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/PatientConsultEndpoint.java
  7. 543 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultService.java
  8. 155 0
      svr/svr-cloud-job/pom.xml
  9. 24 0
      svr/svr-cloud-job/src/main/java/com.yihu/CloudApplicationJob.java
  10. 54 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/async/AsyncConfig.java
  11. 25 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/quartz/JobFactory.java
  12. 56 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/quartz/SchedulerConfig.java
  13. 17 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/JobConfigDao.java
  14. 26 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuartzJobConfigDao.java
  15. 11 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuartzJobLogDao.java
  16. 11 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuotaDao.java
  17. 13 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/WlyyQuotaResultDao.java
  18. 38 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/event/ApplicationEvent.java
  19. 122 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/job/QuartzHelper.java
  20. 254 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/service/JobService.java
  21. 927 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/DateUtil.java
  22. 208 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/SystemConf.java
  23. 41 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/HttpResponse.java
  24. 382 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/HttpUtils.java
  25. 54 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/IPInfoUtils.java
  26. 110 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/vo/WlyyJobConfigVO.java
  27. 107 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/vo/WlyyQuotaVO.java
  28. 571 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/web/BaseController.java
  29. 250 0
      svr/svr-cloud-job/src/main/java/com.yihu/jw.care/web/JobController.java
  30. 115 0
      svr/svr-cloud-job/src/main/resources/application.yml
  31. 5 0
      svr/svr-cloud-job/src/main/resources/banner.txt
  32. 44 0
      svr/svr-cloud-job/src/main/resources/quartz.properties
  33. 25 0
      svr/svr-cloud-job/src/main/resources/system.properties

+ 3 - 138
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -1,10 +1,8 @@
package com.yihu.jw.im.service;
import ch.qos.logback.core.joran.conditional.ElseAction;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibm.mq.jmqi.MQPD;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
@ -56,8 +54,6 @@ import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import com.yihu.jw.wechat.service.WxTemplateService;
import com.ylzinfo.onepay.sdk.domain.ext.WaitPayDetailVO;
import com.ylzinfo.onepay.sdk.utils.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -68,7 +64,6 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.Element;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@ -488,22 +483,6 @@ public class ImService {
		String[] arr = null;
		if (type == 3) {//语音文件处理
//			if(!StringUtils.isEmpty(wechat_appid)){
//				String path = fetchWxVoices(wechat_appid);
//				JSONObject obj = new JSONObject();
//				// 将临时语音拷贝到正式存储路径下
//				if (org.apache.commons.lang3.StringUtils.isNotEmpty(path)) {
//					if("xm_ihealth_wx".equals(wechat_appid)){
//						Map<String, Object> map = fileUploadService.uploadImg(file);
//						uploadVO.setFullUri(map.get("accessory").toString());
//					}else{
//						content = fileUtil.copyTempVoice(path,fastdfs_file_url);
//					}
//					obj.put("path", path);
//					obj.put("times", times);
//					content = obj.toString();
//				}
//			}
			ConsultTeamLogDo log = new ConsultTeamLogDo();
			log.setConsult(consult);
			log.setContent(content);
@ -513,15 +492,7 @@ public class ImService {
			logs.add(log);
		} else if (type == 2) {
//			// 图片消息
//			content = fetchWxImages(wechat_appid);
//			// 将临时图片拷贝到正式存储路径下
//			if (org.apache.commons.lang3.StringUtils.isNotEmpty(content)) {
//				content = fileUtil.copyTempImage(content,upload_temp_path);
//			}
//			if (org.apache.commons.lang3.StringUtils.isEmpty(content)) {
//				throw new Exception("图片上传失败!");
////				return error(-1, "图片上传失败!");
//			}
			String[] images = content.split(",");
			for (String image : images) {
				ConsultTeamLogDo log = new ConsultTeamLogDo();
@ -549,86 +520,14 @@ public class ImService {
		List<String> failed = new ArrayList<>();
		for (ConsultTeamLogDo log : logs) {
//                String response = ImUtill.sendTopicIM(getUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent());
			String response = imUtil.sendTopicIM(patientcode, patient.getName(), consult, String.valueOf(log.getType()), log.getContent(),null,patient.getName(),Integer.parseInt(IdCardUtil.getSexForIdcard_new(patient.getIdcard())), IdCardUtil.getAgeForIdcard(patient.getIdcard()));
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(response)) {
				JSONObject resObj = JSON.parseObject(response);
				if (resObj.getInteger("status")  == -1) {
					throw new Exception("追问失败!" + resObj.getString("message"));
//					return invalidUserException(new RuntimeException(resObj.getString("message")), -1, "追问失败!" + resObj.getString("message"));
				}
				failed.add(String.valueOf(resObj.get("data")));
//				try {
//
//					String sql = "";
//					if (consultModel.getType() == 2){
//						//家庭咨询
//						sql = "SELECT t.participant_id FROM " + data_base_name +
//								".participants t where t.session_id = '" +
//								patient.getId() + "_" + consultModel.getTeam() + "_" + consultModel.getType() +
//								"' and t.participant_role = 0";
//					}else if (consultModel.getType() == 8 || consultModel.getType() == 9 || consultModel.getType() == 11){
//						//8-续方咨询 9-在线复诊咨询 11-上门预约服务
//						sql = "SELECT t.participant_id FROM " + data_base_name +
//								".participants t where t.session_id = '" +
//								patient.getId() + "_" + consultModel.getConsult() + "_" + consultModel.getType() +
//								"' and t.participant_role = 0";
//					}
//					if(org.apache.commons.lang3.StringUtils.isEmpty(sql)){
//						throw new Exception("追问失败!不存在该类型!【type】:" + type);
//						return write(-1, "追问失败!", "data", "不存在该类型!【type】:" + type);
//					}
//					List<Map<String, Object>> participants = jdbcTemplate.queryForList(sql);
//
//					for (Map<String, Object> participant : participants) {
//                          //有居民、健管、全科
//						String doctorCode = participant.get("participant_id").toString();
//						if (doctorCode.equals(patient.getCode())) {
//							continue;
//						}
				//健管
//						Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
				//全科
//                            Boolean flag2 = !messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue());
//						if (flag) {
//							//            新增发送医生助手模板消息 v1.4.0 by wujunjie
//							Doctor doctor = doctorDao.findByCode(doctorCode);
//							String doctorOpenID = doctor.getOpenid();
//							if (org.apache.commons.lang3.StringUtils.isNotEmpty(doctorOpenID)) {
//								String title = "";
//								Consult consultSingle = consultDao.findByCode(log.getConsult());
//								if (consultSingle != null) {
//									Integer singleType = consultSingle.getType();
//									if (singleType != null && singleType == 8) {
//										title = consultSingle.getTitle();
//									} else if (singleType != null && singleType != 8) {
//										title = consultSingle.getSymptoms();
//									}
//									String repContent = parseContentType(type + "", content);
//									String first = "居民" + patient.getName() + "的咨询有新的回复。";
//									String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//									List<NameValuePair> params = new ArrayList<>();
//									params.add(new BasicNameValuePair("type", "8"));
//									params.add(new BasicNameValuePair("openId", doctorOpenID));
//									params.add(new BasicNameValuePair("url", targetUrl));
//									params.add(new BasicNameValuePair("first", first));
//									params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
//									String keywords = title + "," + repContent + "," + doctor.getName();
//									params.add(new BasicNameValuePair("keywords", keywords));
//
//									httpClientUtil.post(url, params, "UTF-8");
//									System.out.println("发送对象:"+doctorCode);
//									System.out.println("发送对象名字:"+doctor.getName());
//								}
//							}
//						}
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
			}
		}
		return failed;
@ -1048,7 +947,7 @@ public class ImService {
	 * 添加一条咨询记录
	 * @param patient 患者信息
	 * @param title 咨询标题
	 * @param type 咨询类型:9在线复诊,13专家咨询
	 * @param type 咨询类型:9在线复诊,13专家咨询,23在线咨询
	 * @return
	 */
	public ConsultDo addConsult(String patient, String title, String symptoms, String images, int type,String source) {
@ -1072,7 +971,7 @@ public class ImService {
	 * @param ct
	 * @throws Exception
	 */
	private String addLogs(ConsultTeamDo ct) throws Exception {
	public String addLogs(ConsultTeamDo ct) throws Exception {
		List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
		// 添加问题咨询日志
		String content = "";
@ -1687,9 +1586,6 @@ public class ImService {
		evalueContent.put("doctorPhoto",doctor.getPhoto());
		evalueContent.put("consultCode",consult);
//		returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "28", evalueContent.toString());
//		String response = imUtil.sendTopicIM(consultTeam.getDoctor(), doctor.getName(), consult, "28", evalueContent.toString(),null);
//		String response = imUtil.sendImMsg(consultTeam.getDoctor(), doctor.getName(), session_id, "28", evalueContent.toString(),null);
		//保存系统消息服务评价
		systemMsgEvaluation(doctor,patient,cons,consultTeam,consult,wxId);
@ -1722,37 +1618,6 @@ public class ImService {
			throw new RuntimeException(String.valueOf(null==obj.get("message")?"无失败信息":obj.get("message")));
		}
//		//推送给IM文字消息
//		if (endType == 1) {
//			BasePatientDO p = basePatientDao.findById(endOperator);
//			name = p.getName();
//			returnJson = imUtil.sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
//		} else {
//			BaseDoctorDO d = baseDoctorDao.findById(endOperator);
//			name = d.getName();
//			returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
//		}
//		if (org.apache.commons.lang3.StringUtils.isEmpty(returnJson)) {
//			throw new RuntimeException("send consult finished IM message failed!");
////			throw new Exception("send consult finished IM message failed");
//		} else {
//			JSONObject jo = JSON.parseObject(returnJson);            //设置消息ID
//			consultTeam.setEndMsgId(jo.getInteger("startId") + "");
//			consultTeam.setEndOperator(endOperator);
//			consultTeam.setEndType(endType);
//		}
//		org.json.JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());
//
//		if (group != null) {
//			String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");
//
//			if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
//				throw new Exception("send consult finished IM message failed");
//			}
//		}
		consultTeam.setEndMsgId(obj.getString("id"));
		cons.setEndTime(new Date());
		consultTeam.setEndTime(new Date());

+ 2 - 1
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -758,7 +758,8 @@ public class ImUtil {
	public static final String SESSION_TYPE_EMERGENCY_ASSISTANCE = "20";//紧急救助
	public static final String SESSION_TYPE_DOOR_COACH = "21";//上门辅导(上门预约)
	public static final String SESSION_TYPE_SECURITY_WARN = "22";//安防咨询
	
	public static final String SESSION_TYPE_ONLINE = "23";//在线咨询
	public static final String CONTENT_TYPE_TEXT = "1";
	
	

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java

@ -24,6 +24,7 @@ public class ConsultTeamDo extends UuidIdentityEntity {
	// 6、患者名医咨询 7医生名医咨询 8续方咨询 9、16在线复诊咨询(居民直接咨询专家)
	// 10医生发起的求助 11思明区上门服务在线咨询
	// 13、互联网医院专家咨询, 20紧急救助咨询, 21上门辅导咨询, 22安防警报咨询
	// 23 在线咨询
	private String patient;         // 提问者标识
	private String name;            // 患者姓名
	private Integer sex;            // 患者性别

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java

@ -19,6 +19,7 @@ public class SystemMessageDO extends UuidIdentityEntity {
    /**
     *消息类型 上门服务400开头,生活照料500开头 ,安防监控600开头, 上门辅导700开头,紧急救助800开头
     * 在线咨询 850
     */
    private String type;
    /**

+ 114 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/DoctorConsultEndpoint.java

@ -0,0 +1,114 @@
package com.yihu.jw.care.endpoint.consult;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.consult.ConsultService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/5/29
 * @Description:
 */
@RestController
@RequestMapping(value = "/im/doctor")
@Api(value = "医生端咨询IM接口", description = "医生端咨询IM接口", tags = {"医生端咨询IM接口"})
public class DoctorConsultEndpoint extends EnvelopRestEndpoint {
    private static final Logger logger = LoggerFactory.getLogger(DoctorConsultEndpoint.class);
    @Autowired
    private ConsultService consultService;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private ImService imService;
    @PostMapping(value = "finish")
    @ApiOperation(value = "医生结束咨询", notes = "医生结束咨询")
    public Envelop finish(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult",required = true) String consult,
            @ApiParam(name = "doctorCode", value = "医生COEE")
            @RequestParam(value = "doctorCode",required = true) String doctorCode) throws Exception {
        int resutl = consultService.finish(consult,doctorCode,2);
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctorCode);
        JSONObject msgObj = new JSONObject();
        msgObj.put("msg",baseDoctorDO.getName()+"结束了咨询");
        msgObj.put("consultcode",consult);
        String jsonStr = "";
        if(1 == resutl){
            jsonStr = "{\"id\":\""+ UUID.randomUUID().toString()+"\",\"sender_id\":\""+doctorCode+"\",\"sender_name\":\"系统\",\"timestamp\":"+System.currentTimeMillis()+",\"content_type\":7,\"content\":"+msgObj.toString()+",\"business_type\":1}";
        }
        return success(jsonStr);
    }
    @GetMapping(value = "getConsultInfoAndPatientInfo")
    @ApiOperation(value = "获取咨询问题,图片,居民信息", notes = "获取咨询问题,图片,居民信息")
    public Envelop getConsultInfoAndPatientInfo(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult",required = false) String consult,
            @ApiParam(name = "patientCode", value = "居民COEE")
            @RequestParam(value = "patientCode",required = false) String patientCode)throws Exception {
        try {
            return success("请求成功",imService.getConsultInfoAndPatientInfo(consult,patientCode));
        }catch (Exception e){
            return failedException(e);
        }
    }
    @GetMapping(value = "records")
    @ApiOperation(value = "医生咨询记录查询")
    public Envelop records(
            @ApiParam(name = "doctor", value = "医生id")
            @RequestParam(value = "doctor",required = false) String doctor,
            @ApiParam(name = "symptoms", value = "咨询内容")
            @RequestParam(value = "symptoms",required = false) String symptoms,
            @ApiParam(name = "name", value = "居民姓名")
            @RequestParam(value = "name",required = false) String name,
            @ApiParam(name = "id", value = "咨询ID")
            @RequestParam(value = "id",required = false) String id,
            @ApiParam(name = "type", value = "咨询类型")
            @RequestParam(value = "type",required = true) String type,
            @ApiParam(name = "status", value = "咨询状态:0进行中,1已完成,-1患者取消,-2超时未响应自动关闭")
            @RequestParam(value = "status",required = false) Integer status,
            @ApiParam(name = "start_time", value = "开始时间 YYYY-MM-DD HH:MM:SS")
            @RequestParam(value = "start_time",required = false) String start_time,
            @ApiParam(name = "end_time", value = "结束时间 YYYY-MM-DD HH:MM:SS")
            @RequestParam(value = "end_time",required = false) String end_time,
            @ApiParam(name = "page", value = "第几页")
            @RequestParam(value = "page",required = false) int page,
            @ApiParam(name = "pagesize", value = "分页大小")
            @RequestParam(value = "pagesize",required = false) int pagesize
    )throws Exception{
        try {
            List<Map<String,Object>>  data = consultService.findConsultRecordByDoctor(doctor, id,type,status, page,pagesize, symptoms,start_time,end_time,name);
            Long total = consultService.countConsultRecordByDoctor(doctor, id,type,symptoms,status,start_time,end_time,name);
            JSONObject result = new JSONObject();
            result.put("total",total);
            result.put("list",data);
            return success(result);
        }catch (Exception e){
            return failedException(e);
        }
    }
}

+ 196 - 3
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/PatientConsultEndpoint.java

@ -2,11 +2,15 @@ package com.yihu.jw.care.endpoint.consult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.consult.ConsultService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.family.service.WlyyFamilyMemberService;
import com.yihu.jw.hospital.message.service.SystemMessageService;
@ -20,12 +24,14 @@ import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.patient.PatientRequestMapping;
import com.yihu.jw.util.common.FileUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.service.WechatInfoService;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -36,10 +42,10 @@ import java.security.MessageDigest;
import java.util.*;
/**
 * @author huangwenjie
 * @author yeshijie
 */
@RestController
@RequestMapping(value = BaseHospitalRequestMapping.PatientIM.PREFIX)
@RequestMapping(value = "/im/patient")
@Api(value = "居民端咨询IM接口", description = "居民端咨询IM接口", tags = {"居民端咨询IM接口"})
public class PatientConsultEndpoint extends EnvelopRestEndpoint {
@ -94,7 +100,194 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	private String wechat_appid;
	@Autowired
	private FileUtil fileUtil;
	
	@Autowired
	private ConsultService consultService;
	@GetMapping(value = "isExistsUnfinishedOnline")
	@ApiOperation(value = "查询居民是否存在未结束的在线咨询")
	public Envelop isExistsUnfinishedOnline(
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = false) String doctor,
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = true) String patient)throws Exception {
		try {
			String consultCode = consultService.getUnfinishedConsult(patient, doctor);
			return success("请求成功",consultCode);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "addOnlineConsult")
	@ApiOperation(value = "新增在线咨询")
	public Envelop addOnlineConsult(
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = true) String patient,
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor,
			@ApiParam(name = "symptoms", value = "咨询问题")
			@RequestParam(value = "symptoms",required = false) String symptoms,
			@ApiParam(name = "images", value = "图片")
			@RequestParam(value = "images",required = false) String images,
			@ApiParam(name = "voice", value = "语音")
			@RequestParam(value = "voice",required = false) String voice,
			@ApiParam(name = "type", value = "咨询类型:23在线咨询")
			@RequestParam(value = "type",required = false) Integer type,
			@ApiParam(name = "source", value = "咨询类型来源")
			@RequestParam(value = "source",required = false) String source)throws Exception{
		System.out.println("symptoms="+symptoms);
		if (type == null) {
			type = 23;
		}
		ConsultTeamDo consult = new ConsultTeamDo();
		// 设置咨询类型:23 在线咨询
		consult.setType(type);
		// 设置主要症状
		consult.setSymptoms(symptoms);
		// 设置咨询图片URL
		consult.setImages(images);
		// 设置咨询语音URL
		consult.setVoice(voice);
		consult.setDoctor(doctor);
		consult.setPatient(patient);
		// 保存到数据库
		synchronized (patient.intern()){//新增同步方法
			JSONObject re = null;
			re = consultService.addTeamConsult(consult, patient,doctor,source);
			//发送系统消息
			SystemMessageDO systemMessageDO = new SystemMessageDO();
			systemMessageDO.setTitle("新增在线咨询");
			systemMessageDO.setType("850");
			systemMessageDO.setReceiver(re.getString("doctor"));
			systemMessageDO.setReceiverName(re.getString("doctorName"));
			systemMessageDO.setRelationCode(re.getString("sessiond_id"));
			systemMessageDO.setSender(re.getString("patient"));
			systemMessageDO.setSenderName(re.getString("patientName"));
			net.sf.json.JSONObject data = new net.sf.json.JSONObject();
			data.put("name",re.getString("patientName"));
			data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
			data.put("gender",IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
			data.put("question",symptoms);
			data.put("type",1);
			systemMessageDO.setData(data.toString());
			consultService.saveMessage(systemMessageDO);
		}
		return success("操作成功", consult);
	}
	@GetMapping(value = "records")
	@ApiOperation(value = "患者咨询记录查询")
	public Envelop records(
			@ApiParam(name = "patient", value = "居民id")
			@RequestParam(value = "patient",required = true) String patient,
			@ApiParam(name = "title", value = "咨询标题关键字")
			@RequestParam(value = "title",required = false) String title,
			@ApiParam(name = "symptoms", value = "咨询内容")
			@RequestParam(value = "symptoms",required = false) String symptoms,
			@ApiParam(name = "id", value = "咨询ID")
			@RequestParam(value = "id",required = false) String id,
			@ApiParam(name = "type", value = "咨询类型")
			@RequestParam(value = "type",required = true) String type,
			@ApiParam(name = "status", value = "咨询状态:0进行中,1已完成,-1患者取消,-2超时未响应自动关闭")
			@RequestParam(value = "status",required = false) Integer status,
			@ApiParam(name = "page", value = "第几页")
			@RequestParam(value = "page",required = false) int page,
			@ApiParam(name = "pagesize", value = "分页大小")
			@RequestParam(value = "pagesize",required = false) int pagesize,
			@ApiParam(name = "doctorName", value = "医生名字")
			@RequestParam(value = "doctorName",required = false) String doctorName)throws Exception{
		try {
			List<Map<String,Object>>  data = consultService.findConsultRecordByPatient(patient, id,type, page,pagesize, title,symptoms,status,doctorName);
			Long total = consultService.countConsultRecordByPatient(patient, id,type,title,symptoms,doctorName,status);
			JSONObject result = new JSONObject();
			result.put("total",total);
			result.put("list",data);
			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "finish")
	@ApiOperation(value = "居民结束咨询", notes = "居民结束咨询")
	public Envelop finish(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult,
			@ApiParam(name = "patientCode", value = "居民COEE")
			@RequestParam(value = "patientCode",required = false) String patientCode) throws Exception {
		int resutl = consultService.finish(consult,patientCode,1);
		BasePatientDO basePatientDO = basePatientService.findByIdAndDel(patientCode);
		JSONObject msgObj = new JSONObject();
		msgObj.put("msg",basePatientDO.getName()+"结束了咨询");
		msgObj.put("consultcode",consult);
		String jsonStr = "";
		if(1 == resutl){
			jsonStr = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"sender_id\":\""+patientCode+"\",\"sender_name\":\"系统\",\"timestamp\":"+System.currentTimeMillis()+",\"content_type\":7,\"content\":"+msgObj.toString()+",\"business_type\":1}";
		}
		return success(jsonStr);
	}
	@GetMapping(value = "getTopic")
	@ApiOperation(value = "根据咨询CODE获取session_id", notes = "根据咨询CODE获取session_id")
	public Envelop getTopic(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult)throws Exception {
		try {
			return success("请求成功",imService.getTopic(consult));
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "append")
	@ApiOperation(value = "居民咨询发消息(追问接口)")
	public ListEnvelop append(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult,
			@ApiParam(name = "content", value = "追问内容")
			@RequestParam(value = "content",required = true) String content,
			@ApiParam(name = "type", value = "追问内容类型:1文字,2图片,3语音  ... (im消息类型)")
			@RequestParam(value = "type",required = true) Integer type,
			@ApiParam(name = "times", value = "")
			@RequestParam(value = "times",required = false) Integer times,
			@ApiParam(name = "patientCode", value = "居民CODE")
			@RequestParam(value = "patientCode",required = false) String patientCode) throws Exception {
		try {
			List<String> failed = new ArrayList<>();
			//处理语音文件
			if(3 == type){//语音文件
				String voicepath = imService.fetchWxVoices(wechat_appid);
				logger.info("voice_path:"+voicepath);
				JSONObject obj = new JSONObject();
				String voiceurl = "";
				// 将临时语音拷贝到正式存储路径下
				if (StringUtils.isNotEmpty(voicepath)) {
					voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
					obj.put("path", voiceurl);
					obj.put("times", times);
					content = obj.toString();
				}
			}else if(2 == type){//图片文件
				String imagepath = imService.fetchWxImages(wechat_appid);
				logger.info("image_path:"+imagepath);
				// 将临时语音拷贝到正式存储路径下
				if (StringUtils.isNotEmpty(imagepath)) {
					content = fileUploadService.uploadWxImage(imagepath);
				}
			}else{}
			failed = imService.append(consult,content,type,times,patientCode,wechat_appid);
			return success(failed);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.participants)
	@ApiOperation(value = "获取会话成员")

+ 543 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultService.java

@ -0,0 +1,543 @@
package com.yihu.jw.care.service.consult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamDoctorDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.sms.dao.HospitalSysDictDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static jxl.biff.FormatRecord.logger;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/5/28
 * @Description:
 */
@Service
public class ConsultService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private ImService imService;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    /**
     * 居民结束咨询
     * @param consult 咨询CODE
     * @param endOperator 操作人
     * @param endType 1居民 2医生
     * @return
     */
    public int finish(String consult, String endOperator, int endType) {
        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);
        ConsultDo cons = consultDao.findOne(consult);
        if (consultTeam.getStatus() == 1) {
            return -1;
        }
        String endName = "";
        String endId = "";
        JSONObject obj = new JSONObject();
        //结束咨询才发送推送给IM文字消息
        if (endType == 1) {
            BasePatientDO p = basePatientDao.findById(endOperator);
            endName = p.getName();
            endId = p.getId();
            obj = imUtil.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
        } else {
            BaseDoctorDO d = baseDoctorDao.findById(endOperator);
            if (endOperator.equals("admin")) {
                endId = "system";
                endName = "超时,系统自动";
            } else {
                endId = d.getId();
                endName = d.getName();
            }
            obj = imUtil.endTopics(consultTeam.getDoctor(), endId, endName, consultTeam.getConsult());
        }
        if (obj == null) {
            throw new RuntimeException("IM消息结束异常!");
        }
        if (obj.getInteger("status") == -1) {
            throw new RuntimeException(String.valueOf(null==obj.get("message")?"无失败信息":obj.get("message")));
        }
        consultTeam.setEndMsgId(obj.getString("id"));
        cons.setEndTime(new Date());
        consultTeam.setEndTime(new Date());
        consultTeam.setStatus(1);
        consultDao.save(cons);
        consultTeamDao.save(consultTeam);
        return 1;
    }
    /**
     * 查询患者所有的咨询记录
     * @param patient 患者标识
     * @param id 会话ID(等同IM表topicId)
     * @param type 咨询会话类型
     * @param pagesize 分页大小
     * @param title 标题关键字
     * @param status 状态
     * @param doctorName 医生名字
     * @return
     */
    public List<Map<String,Object>>  findConsultRecordByPatient(String patient, String id,String type, int page
            ,int pagesize, String title, String symptoms,Integer status,String doctorName) {
        String  sql = "SELECT " +
                "a.id AS \"id\"," +
                "a.type AS \"type\"," +
                "a.title AS \"title\"," +
                "a.symptoms AS \"symptoms\","+
                "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\","+
                "b.status AS \"status\"," +
                "b.evaluate AS \"evaluate\"," +
                "d.name AS \"doctorName\"," +
                "d.photo AS \"doctorphoto\"," +
                "d.id AS \"doctorCode\"," +
                "d.job_title_name AS \"jobTitleName\", " +
                "h.dept_name AS \"deptName\", " +
                "h.org_name AS \"hospitalName\", " +
                "a.pay_status AS \"payStatus\", "+
                "a.source AS \"source\" "+
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_doctor d, " +
                "base_doctor_hospital h " +
                "WHERE a.id=b.consult and d.id = h.doctor_code " +
                "AND b.doctor=d.id AND a.patient='"+patient+"' AND a.type in ("+type+")";
        if(!StringUtils.isEmpty(title)){
            title="%"+title+"%";
            sql +=" and a.title like '"+title+"'";
        }
        if(!StringUtils.isEmpty(symptoms)){
            symptoms="%"+symptoms+"%";
            sql +=" and a.symptoms like '"+symptoms+"'";
        }
        if(!StringUtils.isEmpty(doctorName)){
            doctorName="%"+doctorName+"%";
            sql +=" and d.name like '"+doctorName+"'";
        }
        //咨询状态
        if(status != null && status != 0){
            sql +=" and b.status ="+status;
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql += " ORDER BY a.czrq desc ";
        logger.info("sql="+sql);
        List<Map<String,Object>> result = hibenateUtils.createSQLQuery(sql,page,pagesize);
        return result;
    }
    /**
     * 查询患者所有的咨询记录总数
     * @param patient 患者标识
     * @param id 会话ID(等同IM表topicId)
     * @param type 咨询会话类型
     * @param title 标题关键字
     * @return
     */
    public Long countConsultRecordByPatient(String patient, String id,String type, String title,String symptoms,String doctorName,Integer status) {
        String  sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_doctor d " +
                "WHERE a.id=b.consult " +
                "AND b.doctor=d.id AND a.patient='"+patient+"' AND a.type in ("+type+") ";
        if(!StringUtils.isEmpty(title)){
            title="%"+title+"%";
            sql +=" and a.title like '"+title+"'";
        }
        if(!StringUtils.isEmpty(symptoms)){
            symptoms="%"+symptoms+"%";
            sql +=" and a.symptoms like '"+symptoms+"'";
        }
        if(!StringUtils.isEmpty(doctorName)){
            doctorName="%"+doctorName+"%";
            sql +=" and d.name like '"+doctorName+"'";
        }
        //咨询状态
        if(status != null && status != 0){
            sql +=" and b.status ="+status;
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        return count;
    }
    /**
     * 查询患者所有的咨询记录总数
     * @param doctor 患者标识
     * @param id 会话ID(等同IM表topicId)
     * @param type 咨询会话类型
     * @param symptoms 标题关键字
     * @return
     */
    public Long countConsultRecordByDoctor(String doctor, String id,String type, String symptoms,Integer status,String start_time,String end_time,String name) {
        String  sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_patient d " +
                "WHERE a.id=b.consult " +
                "AND b.patient=d.id AND b.doctor='"+doctor+"' AND a.type in ("+type+") ";
        if (!StringUtils.isEmpty(symptoms)) {
            symptoms = "%" + symptoms + "%";
            sql += " and a.symptoms like '" + symptoms + "'";
        }
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name + "%";
            sql += " and b.name like '" + name + "'";
        }
        if (!StringUtils.isEmpty(start_time)) {
            sql += " and a.czrq >= '" + start_time + "'";
        }
        if (!StringUtils.isEmpty(end_time)) {
            sql += " and a.czrq <= '" + end_time + "'";
        }
        //咨询状态
        if (status != null) {
            sql += " and b.status = "+status;
        }
        //咨询类型
        if (!StringUtils.isEmpty(type)) {
            sql += " AND a.type in (" + type + ")";
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        return count;
    }
    /**
     * 查询医生所有的咨询记录
     * @param doctor 医生标识
     * @param id 会话ID(等同IM表topicId)
     * @param type 咨询会话类型 : 0 全部
     * @param status 咨询状态:0全部,1候诊中,2就诊中,3结束
     * @param pagesize 分页大小
     * @param symptoms 标题关键字
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @return
     */
    public List<Map<String,Object>>  findConsultRecordByDoctor(String doctor, String id,
                                                               String type, Integer status,
                                                               int page,int pagesize,
                                                               String symptoms,String start_time,String end_time,String name) {
        String sql = "SELECT " +
                    "a.id AS \"id\"," +
                    "a.type AS \"type\"," +
                    "a.title AS \"title\"," +
                    "a.symptoms AS \"symptoms\","+
                    "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\","+
                	"b.status AS \"status\"," +
                    "b.evaluate AS \"evaluate\"," +
                    "d.name AS \"patientName\"," +
                    "d.id as \"patientId\"," +
                    "d.idcard as \"patientIdcard\"," +
                    "d.sex as \"patientSex\"," +
                    "d.photo AS \"patientPhoto\", " +
                    "b.doctor as \"doctor\" ,"+
                    "a.source as \"source\"  "+
                    "FROM wlyy_consult a," +
                    "wlyy_consult_team b," +
                    "base_patient d " +
                    "WHERE a.id=b.consult " +
                    "AND b.patient=d.id ";
            if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                sql += " AND b.doctor='" + doctor + "' ";
            }
            if (!StringUtils.isEmpty(symptoms)) {
                symptoms = "%" + symptoms + "%";
                sql += " and a.symptoms like '" + symptoms + "'";
            }
            if (!StringUtils.isEmpty(start_time)) {
                sql += " and a.czrq >= '" + start_time + "'";
            }
            if (!StringUtils.isEmpty(end_time)) {
                sql += " and a.czrq <= '" + end_time + "'";
            }
            //咨询状态
            if (status != null) {
                sql += " and b.status = "+status;
            }
            //咨询类型
            if (!StringUtils.isEmpty(type)) {
                sql += " AND a.type in (" + type + ")";
            }
            if (!StringUtils.isEmpty(id)) {
                sql += " and a.id = '" + id + "'";
            }
            sql += " ORDER BY a.czrq desc ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql,page,pagesize);
        for (Map<String,Object> map:mapList){
            if (map.get("patientIdcard")!=null){
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge",age);
            }else {
                map.put("patientAge",null);
            }
            if (map.get("doctor")!=null){
                String doctorId = map.get("doctor").toString();
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctorId);
                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(doctorId);
                if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                    map.put("deptName",doctorHospitalDOS.get(0).getDeptName());
                }
                if (baseDoctorDO!=null){
                    map.put("doctorName",baseDoctorDO.getName());
                }
            }
        }
        return mapList;
    }
    /**
     * 保存系统消息&发送IM外层刷新事件的消息
     * @param systemMessageDO
     * @throws Exception
     */
    public void saveMessage(SystemMessageDO systemMessageDO) throws Exception{
        //发送系统消息
        systemMessageDO.setIsRead("0");
        systemMessageDO.setDel("1");
        systemMessageDO.setCreateTime(new Date());
        systemMessageDao.save(systemMessageDO);
        //发型IM外层消息
        JSONObject object = new JSONObject();
        object.put("socket_sms_type",11);//系统消息刷新事件
        object.put("relation_code",systemMessageDO.getType());
        imService.sendWaiSocketMessage(systemMessageDO.getSender(),systemMessageDO.getReceiver(),object.toString(),"1");
    }
    /**
     * 患者端
     * 发起在线咨询
     * @param ct      在线咨询对象
     * @param patient 患者标识
     * @return
     * @throws Exception
     */
    public JSONObject addTeamConsult(ConsultTeamDo ct, String patient, String doctor, String source) throws Exception {
        JSONObject re = new JSONObject();
        boolean boo = StringUtils.isEmpty(getUnfinishedConsult(patient, doctor));
        logger.info("boo"+boo);
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("consultClose");
        boolean flag = false;
        if (sysDictDO!=null){
            if (sysDictDO.getDictCode().equalsIgnoreCase("1")){
                flag = true;
            }
        }
        if (!flag){
            if (!StringUtils.isEmpty(getUnfinishedConsult(patient, doctor))) {
                throw new RuntimeException("居民还有未结束的在线咨询!");
            }
        }
        JSONObject users = new JSONObject();
        users.put(doctor,0);
        // 设置医生名称
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        // 设置患者信息
        ct.setPatient(patient);
        // 查询患者信息
        BasePatientDO tempPatient = basePatientDao.findById(patient);
        // 设置患者姓名
        ct.setName(tempPatient.getName());
        // 设置患者生日
        ct.setBirthday(tempPatient.getBirthday());
        //新增性别
        ct.setSex(tempPatient.getSex());
        // 设置患者头像
        ct.setPhoto(tempPatient.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        ct.setEvaluate(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 添加咨询记录
        ConsultDo consult = imService.addConsult(ct.getPatient(), "在线咨询", ct.getSymptoms(), ct.getImages(), ct.getType(),source);
//		// 设置关联指导
//		consult.setGuidance(ct.getGuidance());
        // 设置咨询标识
        ct.setConsult(consult.getId());
        // 设置医生CODE
        ct.setDoctor(doctor);
        // 设置医生名称
        ct.setDoctorName(baseDoctorDO.getName());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", tempPatient.getName() + "申请在线咨询");
        jsonObject.put("content",ct.getSymptoms());
        jsonObject.put("age", DateUtil.getAgeForIdcard(tempPatient.getIdcard()));
        jsonObject.put("sex",tempPatient.getSex());
        jsonObject.put("name",tempPatient.getName());
        //推送给IM去创建议题,取得成员消息
        JSONObject messages = imUtil.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), jsonObject.toJSONString(), consult.getImages(), doctor);
        users.put(patient, 0);
        users.put(doctor, 0);
        String session_type = ImUtil.SESSION_TYPE_ONLINE;
        JSONObject obj = imUtil.createTopics(patient + "_" + doctor + "_" + ct.getType(), consult.getId(), tempPatient.getName(), users, messages, session_type);
        if (obj == null) {
            throw new RuntimeException("IM消息发送异常!");
        }
        if (obj.getInteger("status") == -1) {//im议题创建失败
            throw new RuntimeException(obj.getString("message"));
        }
        ct.setStartMsgId(obj.get("start_msg_id").toString());
        consultTeamDao.save(ct);
        consultDao.save(consult);
        JSONArray doctors = new JSONArray();
        for (String key : users.keySet()) {
            if (patient.equals(key)) {
                continue;
            }
            doctors.add(key);
            //记录咨询的医生详情误删
            ConsultTeamDoctorDo cd = new ConsultTeamDoctorDo();
            cd.setConsult(consult.getId());
            cd.setDel("1");
            cd.setCzrq(new Date());
            cd.setTo(key);
            consultTeamDoctorDao.save(cd);
        }
        // 保存医生咨询信息
        // 添加咨询转发记录
        // 添加医生咨询日志
        String content = imService.addLogs(ct);
        re.put("doctor", doctor);
        re.put("doctorName", baseDoctorDO.getName());
        re.put("status", 1);
        re.put("sessiond_id",patient + "_" + doctor + "_" + ct.getType());
        re.put("patient",patient);
        re.put("patientName",tempPatient.getName());
        re.put("patient_idcard",tempPatient.getIdcard());
        re.put("consult",consult.getId());
        return re;
    }
    /**
     * 查询居民是否有未结束的在线咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public String  getUnfinishedConsult(String patient, String doctor) {
        String totalSql = "SELECT a.consult as \"consultCode\" " +
                "FROM wlyy_consult_team a,wlyy_consult_team_doctor b " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" +patient+"' "+
//                "AND b.to_doctor='" +doctor+"' "+
                "AND a.del='1' " +
                "AND type = 23 " +
                "AND a.status=0";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
        }
        logger.info("未结束判断语句"+totalSql+"======consultCode"+consultCode);
        return consultCode;
    }
}

+ 155 - 0
svr/svr-cloud-job/pom.xml

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-cloud-job</artifactId>
    <packaging>jar</packaging>
    <version>${parent.version}</version>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-exception</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <!-- Jzkl Starter -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <!-- quartz start  -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <!-- quartz end  -->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.4.4</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-cloud-job</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.yihu.CloudApplicationJob</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <!--指定资源的位置-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/**.**</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

+ 24 - 0
svr/svr-cloud-job/src/main/java/com.yihu/CloudApplicationJob.java

@ -0,0 +1,24 @@
package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
 * Created by yeshijie on 2021/5/28.
 */
@SpringBootApplication
@EnableJpaAuditing
public class CloudApplicationJob extends SpringBootServletInitializer {
    public static void main(String[] args)  {
        SpringApplication.run(CloudApplicationJob.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(CloudApplicationJob.class);
    }
}

+ 54 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/async/AsyncConfig.java

@ -0,0 +1,54 @@
package com.yihu.jw.care.config.async;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
 * Created by chenweida on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig {
    /**
     * 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程
     */
    private int corePoolSize = 5;
    /**
     * 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity.
     * 设定 比 系统native thread个数要大的话,会优先抛出Java.lang.OutOfMemoryError: unable to create new native thread
     */
    private int maxPoolSize = 10;
    /**
     * 缓冲队列大小
     */
    private int queueCapacity = 100;
    /**
     * 线程池维护线程所允许的空闲时间  秒
     */
    private int keepAliveSeconds = 300;
    @Bean
    public Executor wlyyExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        /** Reject策略预定义有四种:
         (1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
         (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
         (3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃.
         (4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

+ 25 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/quartz/JobFactory.java

@ -0,0 +1,25 @@
package com.yihu.jw.care.config.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * Created by Administrator on 2016.10.12.
 * 為了讓quartz種可以使用Spring的注入
 */
@Component("jobFactory")
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
       // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

+ 56 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/config/quartz/SchedulerConfig.java

@ -0,0 +1,56 @@
package com.yihu.jw.care.config.quartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
public class SchedulerConfig {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private org.quartz.spi.JobFactory jobFactory;
    @Autowired
    private DataSource dataSource;
    @Value("${quartz.name}")
    private String schedulerFactoryBeanName;
    @Bean
    SchedulerFactoryBean schedulerFactoryBeanWlyy() throws IOException {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setJobFactory(jobFactory);
        bean.setApplicationContext(this.applicationContext);
        bean.setOverwriteExistingJobs(true);
        bean.setStartupDelay(20);// 延时启动
        bean.setBeanName(schedulerFactoryBeanName);
        bean.setAutoStartup(true);
        bean.setDataSource(dataSource);
        bean.setQuartzProperties(quartzProperties());
        return bean;
    }
    /**
     * quartz配置文件
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}

+ 17 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/JobConfigDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.care.dao;
import com.yihu.jw.entity.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface JobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>,JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" from QuartzJobConfig p where p.status=?1 and p.del='1'")
    List<QuartzJobConfig> findByStatus(String s);
}

+ 26 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuartzJobConfigDao.java

@ -0,0 +1,26 @@
package com.yihu.jw.care.dao;
import com.yihu.jw.entity.job.QuartzJobConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/17.
 */
public interface QuartzJobConfigDao extends PagingAndSortingRepository<QuartzJobConfig, String>, JpaSpecificationExecutor<QuartzJobConfig> {
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.status=?2 and a.del='1'")
    QuartzJobConfig findById(String code, String status);
    @Query(" FROM QuartzJobConfig a WHERE a.status=?1 and a.del='1'")
    List<QuartzJobConfig> findByAll(String s);
    @Query(" FROM QuartzJobConfig a WHERE a.id in (1,2,3,4,5,6,7,8,9,10,12,13,14)  and a.del='1' ")
    List<QuartzJobConfig> findByIds();
    @Query(" FROM QuartzJobConfig a WHERE a.id=?1 and a.del='1'")
    QuartzJobConfig findById(String id);
}

+ 11 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuartzJobLogDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.care.dao;
import com.yihu.jw.entity.job.QuartzJobLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuartzJobLogDao extends PagingAndSortingRepository<QuartzJobLog, String>, JpaSpecificationExecutor<QuartzJobLog> {
}

+ 11 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/QuotaDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.care.dao;
import com.yihu.jw.entity.quota.WlyyQuota;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface QuotaDao  extends PagingAndSortingRepository<WlyyQuota, String>, JpaSpecificationExecutor<WlyyQuota> {
}

+ 13 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/dao/WlyyQuotaResultDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.care.dao;
import com.yihu.jw.entity.quota.WlyyQuotaResult;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/16.
 */
public interface WlyyQuotaResultDao extends PagingAndSortingRepository<WlyyQuotaResult, String>, JpaSpecificationExecutor<WlyyQuotaResult> {
}

+ 38 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/event/ApplicationEvent.java

@ -0,0 +1,38 @@
package com.yihu.jw.care.event;
import com.yihu.jw.care.job.QuartzHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
/**
 * Created by zdm on 2017/3/10.
 */
@Service
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
    private Logger logger = LoggerFactory.getLogger(ApplicationEvent.class);
    @Autowired
    QuartzHelper quartzHelper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent ContextRefreshedEvent) {
        try {
//            //设备库存预警提醒
//            if (!quartzHelper.isExistJob("device_inventory_warning_job")) {
//                String trigger = SystemConf.getInstance().getSystemProperties().getProperty("device_inventory_warning_job");
//                quartzHelper.addJob(InventoryWarningJob.class, trigger, "device_inventory_warning_job", new HashMap<String, Object>());
//                logger.info("device_inventory_warning_job  job success");
//            } else {
//                logger.info("device_inventory_warning_job  job exist");
//            }
        } catch (Exception e) {
            logger.info(" job start failed");
        }
    }
}

+ 122 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/job/QuartzHelper.java

@ -0,0 +1,122 @@
package com.yihu.jw.care.job;
import org.apache.commons.collections.map.HashedMap;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@Component("quartzHelper")
public class QuartzHelper {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private Scheduler scheduler = null;
    @PostConstruct
    public void init() {
        try {
            scheduler = schedulerFactoryBean.getScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public Map<String,Object> getCalendar()throws Exception{
        Map<String,Object> rs = new HashedMap();
        rs.put("JobGroupNames ",scheduler.getJobGroupNames());
        rs.put("SchedulerName ",scheduler.getSchedulerName());
        rs.put("TriggerGroups ",scheduler.getPausedTriggerGroups());
        return rs;
    }
    public void addJob(Class jobClass, String cronString, String jobKey,
                       Map<String, Object> params) throws Exception {
        if (!CronExpression.isValidExpression(cronString)) {
            throw new Exception("cronExpression is not a valid Expression");
        }
        try {
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity("job-id:" + jobKey, "job-group:" + jobKey)
                    .build();
            JobDataMap jobDataMap = job.getJobDataMap();
            jobDataMap.putAll(params);
            CronTrigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("trigger-name:" + jobKey,
                            "trigger-group:" + jobKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                    .build();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public void removeJob(String jobKeyString) throws Exception {
        TriggerKey triggerKey = new TriggerKey("trigger-name:" + jobKeyString,
                "trigger-group:" + jobKeyString);
//        JobKey jobName = new JobKey("job-group:" + jobKeyString, "job-id:"
//                + jobKeyString);
        JobKey jobName = new JobKey("job-id:" + jobKeyString, "job-group:"
                + jobKeyString);
        scheduler.pauseTrigger(triggerKey);// 停止触发器
        scheduler.unscheduleJob(triggerKey);// 移除触发器
        scheduler.deleteJob(jobName);// 删除任务
    }
    public boolean isExistJob(String jobKey) throws SchedulerException {
        JobKey jk = new JobKey("job-id:" + jobKey, "job-group:" + jobKey);
        if (scheduler.checkExists(jk)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 立即执行任务。
     *
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startNow(Class jobClass, String id, Map<String, Object> params) throws Exception {
        startAt(new Date(), jobClass, id, params);
    }
    /**
     * 在指定时间点执行。
     *
     * @param time
     * @param jobClass
     * @param id
     * @param params
     * @throws Exception
     */
    public void startAt(Date time, Class jobClass, String id, Map<String, Object> params) throws Exception {
        JobDetail job = JobBuilder.newJob(jobClass).
                withIdentity("job-id:" + id, "job-group:" + id)
                .build();
        JobDataMap jobDataMap = job.getJobDataMap();
        if(null != params) jobDataMap.putAll(params);
        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger-id:" + id, "group-group:" + id)
                .startAt(time)
                .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(0))
                .build();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    }
}

+ 254 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/service/JobService.java

@ -0,0 +1,254 @@
package com.yihu.jw.care.service;
import com.yihu.jw.care.dao.QuartzJobConfigDao;
import com.yihu.jw.care.dao.QuotaDao;
import com.yihu.jw.care.job.QuartzHelper;
import com.yihu.jw.care.vo.WlyyJobConfigVO;
import com.yihu.jw.care.vo.WlyyQuotaVO;
import com.yihu.jw.entity.job.QuartzJobConfig;
import com.yihu.jw.entity.quota.WlyyQuota;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author chenweida
 */
@Service
public class JobService {
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private QuartzJobConfigDao wlyyJobConfigDao;
    @Autowired
    private QuotaDao quotaDao;
    @Transactional
    public void stopById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "1");
        if (quartzJobConfig != null) {
            quartzHelper.removeJob(quartzJobConfig.getId());
            quartzJobConfig.setStatus("0");
        } else {
            throw new Exception("任务已经停止");
        }
    }
    @Transactional
    public void startById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "0");
        if (quartzJobConfig != null) {
            startOneJob(quartzJobConfig);
        } else {
            throw new Exception("任务已经启动");
        }
    }
    @Transactional
    public void stopAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("1");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                quartzHelper.removeJob(quartzJobConfig.getId());
                quartzJobConfig.setStatus("0");
            }
        } else {
            throw new Exception("任务已经全部停止");
        }
    }
    @Transactional
    public void startAll() throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByAll("0");
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                startOneJob(quartzJobConfig);
            }
        } else {
            throw new Exception("任务已经全部启动");
        }
    }
    /**
     * 启动单个任务
     *
     * @param quartzJobConfig
     * @throws Exception
     */
    private void startOneJob(QuartzJobConfig quartzJobConfig) throws Exception {
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            //往quartz框架添加任务
            quartzHelper.addJob(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getQuartzCron(), quartzJobConfig.getId(), params);
            quartzJobConfig.setStatus("1");//设置任务状态是启动
        }
    }
    public void startNowById(String id) throws Exception {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findOne(id);
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId()+ UUID.randomUUID(), params);
        }
    }
    public void productDataByDay(Integer day) throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                params.put("yesterday", getYesterday(0 - i));
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                    Thread.sleep(15000L);
                }
            }
        }
    }
    public static String getYesterday(Integer day) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public void productDataByOneDay(String yesterday) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            //往quartz框架添加任务
            params.put("now", now);
            params.put("yesterday", yesterday);
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                Thread.sleep(15000L);
            }
        }
    }
    public void productDataByOneDayWithId(String yesterday, String id) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
            throw new Exception("时间格式错误");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String now = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
        }
        WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
        WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
        WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
        BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
        BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("quota", wlyyQuotaVO);
        params.put("jobConfig", wlyyJobConfigVO);
        //往quartz框架添加任务
        params.put("now", now);
        params.put("yesterday", yesterday);
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
            Thread.sleep(15000L);
        }
    }
    public void productDataByDayAndId(Integer day, String id) throws Exception{
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if(quartzJobConfig==null){
            throw new Exception("id不存在");
        }
            WlyyQuota wlyyQuota = quotaDao.findOne(quartzJobConfig.getQuotaId());
            WlyyQuotaVO wlyyQuotaVO = new WlyyQuotaVO();
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
            BeanUtils.copyProperties(wlyyQuota, wlyyQuotaVO);
            BeanUtils.copyProperties(quartzJobConfig, wlyyJobConfigVO);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("quota", wlyyQuotaVO);
            params.put("jobConfig", wlyyJobConfigVO);
            for (int i = 1; i <= day; i++) {
                //往quartz框架添加任务
                params.put("now", getYesterday(0 - i + 1));
                params.put("yesterday", getYesterday(0 - i));
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getId() + UUID.randomUUID(), params);
                    Thread.sleep(15000L);
                }
            }
    }
}

+ 927 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/DateUtil.java

@ -0,0 +1,927 @@
package com.yihu.jw.care.util;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateUtil {
	public static final String HH_MM = "HH:mm";
	public static final String HH_MM_SS = "HH:mm:ss";
	public static final String YY = "yy";
	public static final String YYYYMM = "yyyyMM";
	public static final String YYYYMMDD = "yyyyMMdd";
	public static final String YYYY_MM_DD = "yyyy-MM-dd";
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
	public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYY_M_D_HH_MM_SS = "yyyy/M/d HH:mm:ss";
	/**
	 * 时间格式转中文格式
	 */
	public static String dateToChinese(Date date) {
		SimpleDateFormat formatter =   new SimpleDateFormat( "yyyy年MM月dd日 EEEEaaaa hh:mm", Locale.CHINA);
		return formatter.format(date);
	}
	/*public static void main(String[] args)
	{
	   System.out.print(dateToChinese(new Date()));
	}*/
	/**
	 * 字符串转时间格式
	 */
	public static Date strToDate(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		else{
			int length = strDate.length();
			if(strDate.contains("/"))
			{
				strDate = strDate.replace("/","-");
			}
			if(strDate.contains("-"))
			{
				if(length == 10)
				{
					 return strToDate(strDate,YYYY_MM_DD);
				}
				else if(length == 19)
				{
					return strToDate(strDate,YYYY_MM_DD_HH_MM_SS);
				}
			}
			else{
				if(length == 8)
				{
					return strToDate(strDate,YYYYMMDD);
				}
				else if(length == 14)
				{
					return strToDate(strDate,YYYYMMDDHHMMSS);
				}
			}
		}
		return null;
	}
	/**
	  * 获取现在时间
	  * 
	  * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
	  */
	public static Date getNowDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(dateString, pos);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回短时间格式 yyyy-MM-dd
	 */
	public static Date getNowDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		String dateString = formatter.format(currentTime);
		return strToDate(dateString, YYYY_MM_DD);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
	 */
	public static String getStringDate(String format) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(currentTime);
	}
	/**
	 * 获取现在时间
	 * 
	 * @return 返回短时间字符串格式yyyy-MM-dd
	 */
	public static String getStringDateShort() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(currentTime);
	}
	/**
	 * 获取时间 小时:分;秒 HH:mm:ss
	 * 
	 * @return
	 */
	public static String getTimeShort() {
		SimpleDateFormat formatter = new SimpleDateFormat(HH_MM_SS);
		Date currentTime = new Date();
		return formatter.format(currentTime);
	}
	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDateLong(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateShort(String strDate) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrLong(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return formatter.format(dateDate);
	}
	public static String dateToStrNoSecond(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM);
		return formatter.format(dateDate);
	}
	/**
	 * 将长时间格式时间转换为字符串 yyyy-MM-dd
	 *
	 * @param dateDate
	 * @return
	 */
	public static String dateToStrShort(Date dateDate) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式时间转换为字符串 yyyy-MM-dd
	 */
	public static String dateToStr(Date dateDate, String format) {
		if (dateDate == null) {
			return "";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(dateDate);
	}
	/**
	 * 将短时间格式字符串转换为时间
	 *
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	public static Date strToDateAppendNowTime(String strDate, String format) {
		if (StringUtils.isEmpty(strDate)) {
			return null;
		}
		strDate += " " + getTimeShort();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);
		return formatter.parse(strDate, pos);
	}
	/**
	 * 得到现在时间
	 *
	 * @return
	 */
	public static Date getNow() {
		Date currentTime = new Date();
		return currentTime;
	}
	/**
	 * 提取一个月中的最后一天
	 *
	 * @param day
	 * @return
	 */
	public static Date getLastDate(long day) {
		Date date = new Date();
		long date_3_hm = date.getTime() - 3600000 * 34 * day;
		Date date_3_hm_date = new Date(date_3_hm);
		return date_3_hm_date;
	}
	/**
	 * 得到现在时间
	 *
	 * @return 字符串 yyyyMMdd HHmmss
	 */
	public static String getStringToday() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 得到现在小时
	 */
	public static String getHour() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String hour;
		hour = dateString.substring(11, 13);
		return hour;
	}
	/**
	 * 得到现在分钟
	 *
	 * @return
	 */
	public static String getTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String dateString = formatter.format(currentTime);
		String min;
		min = dateString.substring(14, 16);
		return min;
	}
	/**
	 * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
	 *
	 * @param sformat
	 *            yyyyMMddhhmmss
	 * @return
	 */
	public static String getUserDate(String sformat) {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(sformat);
		String dateString = formatter.format(currentTime);
		return dateString;
	}
	/**
	 * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
	 */
	public static String getTwoHour(String st1, String st2) {
		String[] kk = null;
		String[] jj = null;
		kk = st1.split(":");
		jj = st2.split(":");
		if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
			return "0";
		else {
			double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
			double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
			if ((y - u) > 0)
				return y - u + "";
			else
				return "0";
		}
	}
	/**
	 * 得到二个日期间的间隔天数
	 */
	public static String getTwoDay(String sj1, String sj2) {
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		long day = 0;
		try {
			Date date = myFormatter.parse(sj1);
			Date mydate = myFormatter.parse(sj2);
			day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		} catch (Exception e) {
			return "";
		}
		return day + "";
	}
	/**
	 * 时间前推或后推分钟,其中JJ表示分钟.
	 */
	public static String getPreTime(String sj1, String jj) {
		SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		String mydate1 = "";
		try {
			Date date1 = format.parse(sj1);
			long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
			date1.setTime(Time * 1000);
			mydate1 = format.format(date1);
		} catch (Exception e) {
		}
		return mydate1;
	}
	/**
	 * 时间前推或后推天数(负数前推正数后推)
	 * date 基准时间
	 */
	public static Date getPreDays(Date date, int days) {
		Date day = null;
		try {
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			c.add(Calendar.DATE, days);
			day = c.getTime();
		} catch (Exception e) {
		}
		return day;
	}
	/**
	 * 得到一个时间延后或前移几分钟的时间,nowdate为时间,delay为前移或后延的分钟数
	 */
	public static Date getNextMin(Date date, int delay) {
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.MINUTE, delay);
			return cal.getTime();
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
	 */
	public static String getNextDay(String nowdate, int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
			String mdate = "";
			Date d = strToDate(nowdate, YYYY_MM_DD);
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			return "";
		}
	}
	// public static String getNextDay(Date d, int delay) {
	// try {
	// SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
	// String mdate = "";
	// long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
	// d.setTime(myTime * 1000);
	// mdate = format.format(d);
	// return mdate;
	// } catch (Exception e) {
	// return "";
	// }
	// }
	public static String getNextDay(Date d, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.DATE, days);
		return dateToStrShort(c.getTime());
	}
	public static String getNextMonth(Date d, int months) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MONTH, months);
		return dateToStrShort(c.getTime());
	}
	public static String getNextYear(Date d, int year) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.YEAR, year);
		return dateToStrShort(c.getTime());
	}
	/**
	 * 获取本月第一天
	 * @return
     */
	public static String getCurMonthFirstDayShort(){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		return dateToStrShort(c.getTime());
	}
	/**
	 * 判断是否润年
	 *
	 * @param ddate
	 * @return
	 */
	public static boolean isLeapYear(String ddate) {
		/**
		 * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
		 * 3.能被4整除同时能被100整除则不是闰年
		 */
		Date d = strToDate(ddate, YYYY_MM_DD);
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(d);
		int year = gc.get(Calendar.YEAR);
		if ((year % 400) == 0)
			return true;
		else if ((year % 4) == 0) {
			if ((year % 100) == 0)
				return false;
			else
				return true;
		} else
			return false;
	}
	/**
	 * 返回美国时间格式 26 Apr 2006
	 *
	 * @param str
	 * @return
	 */
	public static String getEDate(String str) {
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD);
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(str, pos);
		String j = strtodate.toString();
		String[] k = j.split(" ");
		return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
	}
	/**
	 * 获取一个月的最后一天
	 *
	 * @param dat
	 * @return
	 */
	public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
		String str = dat.substring(0, 8);
		String month = dat.substring(5, 7);
		int mon = Integer.parseInt(month);
		if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
			str += "31";
		} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
			str += "30";
		} else {
			if (isLeapYear(dat)) {
				str += "29";
			} else {
				str += "28";
			}
		}
		return str;
	}
	/**
	 * 判断二个时间是否在同一个周
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isSameWeekDates(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
		if (0 == subYear) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
			// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}
		return false;
	}
	/**
	 * 产生周序列,即得到当前时间所在的年度是第几周
	 *
	 * @return
	 */
	public static String getSeqWeek() {
		Calendar c = Calendar.getInstance(Locale.CHINA);
		String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
		if (week.length() == 1)
			week = "0" + week;
		String year = Integer.toString(c.get(Calendar.YEAR));
		return year + week;
	}
	/**
	 * 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
	 *
	 * @param sdate
	 * @param num
	 * @return
	 */
	public static String getWeek(String sdate, String num) {
		// 再转换为时间
		Date dd = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(dd);
		if (num.equals("1")) // 返回星期一所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		else if (num.equals("2")) // 返回星期二所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
		else if (num.equals("3")) // 返回星期三所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
		else if (num.equals("4")) // 返回星期四所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
		else if (num.equals("5")) // 返回星期五所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		else if (num.equals("6")) // 返回星期六所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
		else if (num.equals("0")) // 返回星期日所在的日期
			c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}
	/**
	 * 获取2个时间点的工作日天数
	 * @param startDate 开始时间
	 * @param endDate 结束时间
	 * @return
	 */
	public static int getDutyDays(Date startDate, Date endDate) {
		int result = 0;
        Date  startTime = new Date(startDate.getTime());
		while (startTime.compareTo(endDate) <= 0) {
			if (startTime.getDay() != 6 && startTime.getDay() != 0) {
				result++;
			}
            startTime.setDate(startTime.getDate() + 1);
		}
		return result;
	}
	/**
	 * 根据一个日期,返回是星期几的字符串
	 *
	 * @param sdate
	 * @return
	 */
	public static String getWeek(String sdate) {
		// 再转换为时间
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了,其范围 1~7
		// 1=星期日 7=星期六,其他类推
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}
	public static String getWeekStr(String sdate) {
		String str = "";
		str = DateUtil.getWeek(sdate);
		if ("1".equals(str)) {
			str = "星期日";
		} else if ("2".equals(str)) {
			str = "星期一";
		} else if ("3".equals(str)) {
			str = "星期二";
		} else if ("4".equals(str)) {
			str = "星期三";
		} else if ("5".equals(str)) {
			str = "星期四";
		} else if ("6".equals(str)) {
			str = "星期五";
		} else if ("7".equals(str)) {
			str = "星期六";
		}
		return str;
	}
	/**
	 * 两个时间之间的天数
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(String date1, String date2) {
		if (date1 == null || date1.equals(""))
			return 0;
		if (date2 == null || date2.equals(""))
			return 0;
		// 转换为标准时间
		SimpleDateFormat myFormatter = new SimpleDateFormat(YYYY_MM_DD);
		Date date = null;
		Date mydate = null;
		try {
			date = myFormatter.parse(date1);
			mydate = myFormatter.parse(date2);
		} catch (Exception e) {
		}
		long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 返回两个日期相差的天数
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays(Date date1, Date date2) {
		if (date1 == null || date2 == null)
			return 0;
		long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
		return day;
	}
	/**
	 * 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
	 * 此函数返回该日历第一行星期日所在的日期
	 * 
	 * @param sdate
	 * @return
	 */
	public static String getNowMonth(String sdate) {
		// 取该时间所在月的一号
		sdate = sdate.substring(0, 8) + "01";
		// 得到这个月的1号是星期几
		Date date = DateUtil.strToDate(sdate, YYYY_MM_DD);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int u = c.get(Calendar.DAY_OF_WEEK);
		String newday = DateUtil.getNextDay(sdate, 1 - u);
		return newday;
	}
	/**
	 * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
	 * 
	 * @param k 表示是取几位随机数,可以自己定
	 */
	public static String getNo(int k) {
		return getUserDate("yyyyMMddhhmmss") + getRandom(k);
	}
	/**
	 * 返回一个随机数
	 * 
	 * @param i
	 * @return
	 */
	public static String getRandom(int i) {
		Random jjj = new Random();
		if (i == 0)
			return "";
		String jj = "";
		for (int k = 0; k < i; k++) {
			jj = jj + jjj.nextInt(9);
		}
		return jj;
	}
	/**
	 * 根据用户生日计算年龄
	 */
	public static int getAgeByBirthday(Date birthday) {
		try {
			int age = 0;
			if (birthday == null) {
				return age;
			}
			String birth = new SimpleDateFormat("yyyyMMdd").format(birthday);
			int year = Integer.valueOf(birth.substring(0, 4));
			int month = Integer.valueOf(birth.substring(4, 6));
			int day = Integer.valueOf(birth.substring(6));
			Calendar cal = Calendar.getInstance();
			age = cal.get(Calendar.YEAR) - year;
			//周岁计算
			if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
				age--;
			}
			return age;
		} catch (Exception e) {
			return 0;
		}
	}
	/**
	 *  字符串转时间
	 * @param str 时间字符串
	 * @param eg 格式
	 * @return
	 */
	public static Date stringToDate(String str, String eg) {
		DateFormat format = new SimpleDateFormat(eg);
		Date date = null;
		if (str != null && !"".equals(str)) {
			try {
				date = format.parse(str);
			} catch (Exception e) {
				return null;
			}
		}
		return date;
	}
	public static int getNowMonth(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MONTH)+1;
	}
	public static int getNowYear(){
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR);
	}
	/**
	 * 获取周一
	 * @return
     */
	public static String getMondayOfThisWeek() {
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 1);
		return df2.format(c.getTime());
	}
	/**
	 * 得到本周周日
	 *
	 * @return yyyy-MM-dd
	 */
	public static String getSundayOfThisWeek() {
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 7);
		return df2.format(c.getTime());
	}
	/**
	 * 获取当月第一天
	 * @return
     */
	public static String getFristDayOfMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取前月的第一天
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		return format.format(c.getTime());
	}
	/**
	 * 获取当月最后一天
	 */
	public static String getLastDayOfMonth(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取前月的第一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		return format.format(ca.getTime());
	}
	public static int getSignYear(){
		Calendar ca = Calendar.getInstance();
		if(getNowMonth()>=4){
			return getNowYear();
		}
		return getNowYear()-1;
	}
	/**
	 * 计算预产期
	 * 末次月经开始日期(第一天),月份+9,日期+7
	 * @param date
	 * @return
	 */
	public static Date getDueDate(Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH,9);
		cal.add(Calendar.DAY_OF_YEAR,7);
		return cal.getTime();
	}
	/**
	 * 计算产检时间
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date getPrenatalInspectorDate(Date date,Integer day){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR,day);
		return cal.getTime();
	}
	
	/**
	 * 转换日期字符串为Timestamp YYYY-MM-DD HH:MM:SS
	 * @return
	 */
	public static Timestamp fomrmatStringToTimeStamp(String dateStr){
		
		Timestamp ts = Timestamp.valueOf(dateStr);
		
		return ts;
	}
	
	/**
	 * 获取当前时间的Timestamp
	 * @return
	 */
	public static Timestamp getNowTimestamp(){
		Date date = new Date();
		Timestamp nousedate = new Timestamp(date.getTime());
		return nousedate;
	}
	/**
	 * 获取周一
	 * @return
	 */
	public static String getSundayOfThisDate(Date date) {
		SimpleDateFormat df2 = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return df2.format(getSundayOfThisDateToDate(date));
	}
	/**
	 * 得到本周周日
	 *
	 * @return yyyy-MM-dd
	 */
	public static Date getSundayOfThisDateToDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 7);
		return c.getTime();
	}
}

+ 208 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/SystemConf.java

@ -0,0 +1,208 @@
package com.yihu.jw.care.util;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Component
public class SystemConf {
    // 别处登录
    public static final int LOGIN_OTHER = 999;
    // 登录超时
    public static final int LOGIN_TIMEOUT = 998;
    // 未登录
    public static final int NOT_LOGIN = 997;
    // 文件保存临时路径
    private static final String TEMP_PATH = "upload_temp_path";
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    // 同一手机号大最短信数
    public static final int MAX_SMS_MOBILE = 5;
    // 发送短信验证码间隔(分钟)
    public static final int SMS_INTERVAL = 2;
    private static Object lock = new Object();
    // 全局系统配置信息
    private static SystemConf systemConf;
    // 系统配置文件
    private Properties systemProperties;
    //im列表
    private String imListGet;
    public static SystemConf getInstance() {
        if (systemConf == null) {
            synchronized (lock) {
                systemConf = new SystemConf();
            }
        }
        return systemConf;
    }
    /**
     * 加载系统配置文件
     *
     * @return
     */
    public Properties getSystemProperties() {
        if (systemProperties == null) {
            InputStream is = null;
            try {
                is = this.getClass().getResourceAsStream("/system.properties");
                systemProperties = new Properties();
                systemProperties.load(is);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return systemProperties;
    }
    /**
     * 短信接口地址
     */
    public String getSmsUrl() {
        return getSystemProperties().getProperty("yihu_sms_url");
    }
    /**
     * 短信企业编号
     */
    public String getSmsCode() {
        return getSystemProperties().getProperty("yihu_sms_code");
    }
    /**
     * 短信用户名
     */
    public String getSmsName() {
        return getSystemProperties().getProperty("yihu_sms_name");
    }
    /**
     * 短信登录密码
     */
    public String getSmsPassword() {
        return getSystemProperties().getProperty("yihu_sms_password");
    }
    ;
    /**
     * 挂号接口地址
     */
    public String getGuahaoUrl() {
        return getSystemProperties().getProperty("yihu_guahao_url");
    }
    /**
     * 挂号接口对接appid
     */
    public String getGuahaoAppid() {
        return getSystemProperties().getProperty("yihu_guahao_appid");
    }
    /**
     * 挂号接口对接app secret
     */
    public String getGuahaoSecret() {
        return getSystemProperties().getProperty("yihu_guahao_secret");
    }
    /**
     * 获取文件保存的临时路径
     *
     * @return
     */
    public String getTempPath() {
        return getSystemProperties().getProperty(TEMP_PATH);
    }
    /**
     * 获取图片存在地址
     *
     * @return
     */
    /**
     * 获取服务全路径
     *
     * @return
     */
    /******************************** 挂号配置 ********************************************/
    /**
     * 获取厦门预约服务地址
     */
    public String getXMGuahaoUrl() {
        return getSystemProperties().getProperty("guahao_url");
    }
    /**
     * 获取厦门预约服务命名空间
     */
    public String getXMGuahaoNamespace() {
        return getSystemProperties().getProperty("guahao_namespace");
    }
    /****************************************************************************************/
    /********************************* EHR配置 **********************************************/
    /**
     * 是否启用EHR演示
     */
    public Boolean getEhrUsed() {
        return Boolean.valueOf(getSystemProperties().getProperty("ehr_used"));
    }
    /**
     * EHR档案服务地址
     */
    public String getEhrServices() {
        return getSystemProperties().getProperty("ehr_services");
    }
    /**
     * EHR底层地址
     */
    public String getEhrServicesBase() {
        return getSystemProperties().getProperty("ehr_services_base");
    }
    /**************************************************************************************/
    /**************************************************************************************/
}

+ 41 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/HttpResponse.java

@ -0,0 +1,41 @@
package com.yihu.jw.care.util.http;
/**
 * Utils - Http请求辅助类,简化页面页面判断逻辑
 * Created by progr1mmer on 2018/1/16.
 */
public class HttpResponse {
    private int status;
    private String content;
    public HttpResponse(int status, String content) {
        this.status = status;
        this.content = content;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public boolean isSuccessFlg() {
        return status == 200;
    }
    public String getErrorMsg() {
        return content;
    }
}

+ 382 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/HttpUtils.java

@ -0,0 +1,382 @@
package com.yihu.jw.care.util.http;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Utils - HTTP请求辅助工具类
 * Created by progr1mmer on 2017/9/27.
 */
public class HttpUtils {
    public static HttpResponse doGet(String url, Map<String, Object> params) throws Exception {
        return doGet(url, params, null);
    }
    public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doGet(url, params, headers, null, null);
    }
    public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        HttpGet httpGet = new HttpGet(url + "?" + paramStr);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpGet.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpGet);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" GET: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doPost(String url, Map<String, Object> params) throws Exception {
        return doPost(url, params, null);
    }
    public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception{
        return doPost(url, params, headers, null, null);
    }
    public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception{
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPost);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" POST: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doJsonPost(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception{
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPost);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" POST: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doPut(String url, Map<String, Object> params) throws Exception {
        return doPut(url, params, null);
    }
    public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doPut(url, params, headers, null, null);
    }
    public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPut httpPut = new HttpPut(url);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPut.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPut);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" PUT: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doJsonPut(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPut.setEntity(new StringEntity(jsonData, "UTF-8"));
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPut.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpPut);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" PUT: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params) throws Exception {
        return doDelete(url, params, null);
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        return doDelete(url, params, headers, null, null);
    }
    public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
        String response;
        int status;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse closeableHttpResponse = null;
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                Object value = params.get(key);
                if (value != null) {
                    nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
            }
        }
        String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        HttpDelete httpDelete = new HttpDelete(url + "?" + paramStr);
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpDelete.addHeader(key, headers.get(key));
            }
        }
        try {
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
                httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            closeableHttpResponse = httpClient.execute(httpDelete);
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            status = closeableHttpResponse.getStatusLine().getStatusCode();
            response = getRespString(resEntity);
        } finally {
            try {
                if (closeableHttpResponse != null) {
                    closeableHttpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (status != HttpStatus.SC_OK) {
//            LogService.getLogger().error(" DELETE: " + url + " " + status);
        }
        HttpResponse httpResponse = new HttpResponse(status, response);
        return httpResponse;
    }
    private static String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}

+ 54 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/util/http/IPInfoUtils.java

@ -0,0 +1,54 @@
package com.yihu.jw.care.util.http;
import javax.servlet.http.HttpServletRequest;
/**
 * Utils - ip信息辅助工具类
 * Created by progr1mmer on 2018/1/18.
 */
public class IPInfoUtils {
    private static final long A1 = getIpNum("10.0.0.0");
    private static final long A2 = getIpNum("10.255.255.255");
    private static final long B1 = getIpNum("172.16.0.0");
    private static final long B2 = getIpNum("172.31.255.255");
    private static final long C1 = getIpNum("192.168.0.0");
    private static final long C2 = getIpNum("192.168.255.255");
    private static final long D1 = getIpNum("10.44.0.0");
    private static final long D2 = getIpNum("10.69.0.255");
    private static long getIpNum(String ipAddress) {
        String [] ip = ipAddress.split("\\.");
        long a = Integer.parseInt(ip[0]);
        long b = Integer.parseInt(ip[1]);
        long c = Integer.parseInt(ip[2]);
        long d = Integer.parseInt(ip[3]);
        return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
    }
    public static boolean isInnerIP(String ip){
        long n = getIpNum(ip);
        return (n >= A1 && n <= A2) || (n >= B1 && n <= B2) || (n >= C1 && n <= C2) || (n >= D1 && n <= D2);
    }
    public static String getIPAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

+ 110 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/vo/WlyyJobConfigVO.java

@ -0,0 +1,110 @@
package com.yihu.jw.care.vo;
import java.io.Serializable;
/**
 * Created by Administrator on 2016/8/16.
 */
public class WlyyJobConfigVO implements  Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String quotaId;//指标id
    private String jobName;//任务名称
    private String jobInfo;//任务描述
    private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
    private String jobClass;//任务执行的class
    private String quartzCron;//quartz表达式
    private String status;//1 启动 0停止
    private String del;//是否删除 1正常 0删除
    public WlyyJobConfigVO() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getQuotaId() {
        return quotaId;
    }
    public void setQuotaId(String quotaId) {
        this.quotaId = quotaId;
    }
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobInfo() {
        return jobInfo;
    }
    public void setJobInfo(String jobInfo) {
        this.jobInfo = jobInfo;
    }
    public String getJobType() {
        return jobType;
    }
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }
    public String getJobClass() {
        return jobClass;
    }
    public void setJobClass(String jobClass) {
        this.jobClass = jobClass;
    }
    public String getQuartzCron() {
        return quartzCron;
    }
    public void setQuartzCron(String quartzCron) {
        this.quartzCron = quartzCron;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Override
    public String toString() {
        return "WlyyJobConfigVO{" +
                "id='" + id + '\'' +
                ", quotaId='" + quotaId + '\'' +
                ", jobName='" + jobName + '\'' +
                ", jobInfo='" + jobInfo + '\'' +
                ", jobType='" + jobType + '\'' +
                ", jobClass='" + jobClass + '\'' +
                ", quartzCron='" + quartzCron + '\'' +
                ", status='" + status + '\'' +
                ", del='" + del + '\'' +
                '}';
    }
}

+ 107 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/vo/WlyyQuotaVO.java

@ -0,0 +1,107 @@
package com.yihu.jw.care.vo;
import java.io.Serializable;
import java.util.Date;
/**
 * Created by Administrator on 2016/8/16.
 */
public class WlyyQuotaVO implements Serializable {
    private static final long serialVersionUID = 2L;
    private String id;
    private String name;//指标名称
    private String level1;//指标维度(1:机构维度)
    private String level2;//2级维度 (1:患者性别 2:患者分组 3:患者年龄)
    private String cycle;//统计周期( 1:天 )
    private String type;//尺度(1 新增 2是累计)
    private Date createTime;//创建时间
    private Date modifyTime;//修改时间
    private String del;//1: 正常 0: 删除
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLevel1() {
        return level1;
    }
    public void setLevel1(String level1) {
        this.level1 = level1;
    }
    public String getLevel2() {
        return level2;
    }
    public void setLevel2(String level2) {
        this.level2 = level2;
    }
    public String getCycle() {
        return cycle;
    }
    public void setCycle(String cycle) {
        this.cycle = cycle;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getModifyTime() {
        return modifyTime;
    }
    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @Override
    public String toString() {
        return "WlyyQuotaVO{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", level1='" + level1 + '\'' +
                ", level2='" + level2 + '\'' +
                ", cycle='" + cycle + '\'' +
                ", type='" + type + '\'' +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                ", del='" + del + '\'' +
                '}';
    }
}

+ 571 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/web/BaseController.java

@ -0,0 +1,571 @@
package com.yihu.jw.care.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    protected HttpServletRequest request;
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("lastUid");
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
 /*   *//**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     *//*
    public String write(int code, String msg, String key, IdEntity entity) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, entity);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }*/
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return error(defaultCode, defaultMsg);
        } catch (Exception e2) {
            return null;
        }
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    protected <J> ObjEnvelop<J> success(J obj){
        return success("success", obj);
    }
    protected <J> ObjEnvelop<J> success(String message, J obj){
        return success(message, 200, obj);
    }
    protected <J> ObjEnvelop<J> success(String message, int status, J obj){
        ObjEnvelop<J> objEnvelop = new ObjEnvelop<>();
        objEnvelop.setMessage(message);
        objEnvelop.setStatus(status);
        objEnvelop.setObj(obj);
        return objEnvelop;
    }
}

+ 250 - 0
svr/svr-cloud-job/src/main/java/com.yihu/jw.care/web/JobController.java

@ -0,0 +1,250 @@
package com.yihu.jw.care.web;
import com.yihu.jw.care.job.QuartzHelper;
import com.yihu.jw.care.service.JobService;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import io.swagger.annotations.Api;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
 * 任务启动
 *
 * @author chenweida
 */
@RestController
@RequestMapping(value = "/job", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "后台-任务控制")
public class JobController extends BaseController {
    private org.slf4j.Logger logger = LoggerFactory.getLogger(JobController.class);
    private final JobService jobService;
    private final QuartzHelper quartzHelper;
    @Autowired
    public JobController(JobService jobService, QuartzHelper quartzHelper) {
        this.jobService = jobService;
        this.quartzHelper = quartzHelper;
    }
    @RequestMapping(value = "removeJob", method = RequestMethod.GET)
    public String removeJob(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                quartzHelper.removeJob(taskId);
                return success("删除成功!");
            }
            return success("删除成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "删除失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "getCalendar", method = RequestMethod.GET)
    public ObjEnvelop getCalendar() throws Exception{
       return success(quartzHelper.getCalendar());
    }
    @RequestMapping(value = "isExist", method = RequestMethod.GET)
    public String isExist(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                return success("job已经存在!");
            }
            return success("job不存在!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "执行失败:" + e.getMessage());
        }
    }
    @RequestMapping(value = "reStartById", method = RequestMethod.GET)
    public String reStartById(String taskId) {
        try {
            if(quartzHelper.isExistJob(taskId)){
                quartzHelper.removeJob(taskId);
            }
            switch(taskId){
//                case "data_device_quality_plan_job":
//                    if (!quartzHelper.isExistJob("data_device_quality_plan_job")) {
//                        String trigger = SystemConf.getInstance().getSystemProperties().getProperty("data_device_quality_plan_job");
//                        quartzHelper.addJob(DeviceQualityPlanJob.class, trigger, "data_device_quality_plan_job", new HashMap<String, Object>());
//                        logger.info("data_device_quality_plan_job  job success");
//                    } else {
//                        logger.info("data_device_quality_plan_job  job exist");
//                    }
//                    break;
//                case "data_sim_Balance_remind_job":
//                    if (!quartzHelper.isExistJob("data_sim_Balance_remind_job")) {
//                        String trigger = simBalanceService.getCron();
//                        quartzHelper.addJob(SimBalanceJob.class, trigger, "data_sim_Balance_remind_job", new HashMap<String, Object>());
//                        logger.info("data_sim_Balance_remind_job  job success");
//                    } else {
//                        logger.info("data_sim_Balance_remind_job  job exist");
//                    }
//                    break;
//                case "data_sim_set_meal_job":
//                    if (!quartzHelper.isExistJob("data_sim_set_meal_job")) {
//                        String trigger = simBalanceService.getCron();
//                        quartzHelper.addJob(SimSetMealJob.class, trigger, "data_sim_set_meal_job", new HashMap<String, Object>());
//                        logger.info("data_sim_set_meal_job  job success");
//                    } else {
//                        logger.info("data_sim_set_meal_job  job exist");
//                    }
//                    break;
                default :
            }
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去几天的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByDay", method = RequestMethod.GET)
    public String productDataByDay(Integer day) {
        try {
            jobService.productDataByDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的全部的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByOneDay", method = RequestMethod.GET)
    public String productDataByOneDay(String day) {
        try {
            jobService.productDataByOneDay(day);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某一天的某一个指标的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByOneDayWithId", method = RequestMethod.GET)
    public String productDataByOneDayWithId(String day, String id) {
        try {
            jobService.productDataByOneDayWithId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 生成过去某几天的某一个指标的数据
     *
     * @param day
     * @return
     */
    @RequestMapping(value = "productDataByDayAndId", method = RequestMethod.GET)
    public String productDataByDayAndId(Integer day, String id) {
        try {
            jobService.productDataByDayAndId(day, id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动任务
     *
     * @param id id
     * @return
     */
    @RequestMapping(value = "startById", method = RequestMethod.GET)
    public String startById(String id) {
        try {
            jobService.startById(id);
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止任务
     *
     * @param id id
     * @return
     */
    @RequestMapping(value = "stopById", method = RequestMethod.GET)
    public String stopById(String id) {
        try {
            jobService.stopById(id);
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 停止所有任务
     *
     * @return
     */
    @RequestMapping(value = "stopAll", method = RequestMethod.GET)
    public String stopAll() {
        try {
            jobService.stopAll();
            return success("停止成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /**
     * 启动所有任务
     *
     * @return
     */
    @RequestMapping(value = "startAll", method = RequestMethod.GET)
    public String startAll() {
        try {
            jobService.startAll();
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 115 - 0
svr/svr-cloud-job/src/main/resources/application.yml

@ -0,0 +1,115 @@
#通用的配置不用区分环境变量
server:
  port: 10032
spring:
  application:
      name:  svr-cloud-job
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50
    max-idle: 50 #最大空闲连接
    min-idle: 10 #最小空闲连接
    validation-query-timeout: 20
    log-validation-errors: true
    validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
    validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
    test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
    test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
    idle-timeout: 30000
    connection-test-query: SELECT 1
    num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
    test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
  connect-timeout: 2 #链接超时时间
  network-timeout: 30
  charset: ISO8859-1 #编码
  http:
    tracker-http-port: 80
    anti-steal-token: no
    secret-key: FastDFS1234567890
  pool: #连接池大小
    init-size: 5
    max-size: 20
    wait-time: 500
configDefault: # 默认配置
  saasId: xmjkzl_saasId
express:
  sf_url: http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService
  sf_code: JKZL
  sf_check_word: QkeIfIvQdheqIv2cVSgAUnBU29lfNbVk
quartz:
  name: schedulerFactoryBean
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
---
spring:
  profiles: jwtest
  datasource:
    url: jdbc:mysql://172.26.0.104/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
hlwyyEntrance:
  url: http://localhost:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
hospital:
  url: ht
  mqUser: 1
  mqPwd: 1
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段
---
spring:
  profiles: jwprod
  datasource:
    url: jdbc:mysql://192.0.33.27:3306/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true
    username: im
    password: 2oEq3Kf7
hlwyyEntrance:
  url: http://172.16.1.42:10023
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
hospital:
  url: https://172.16.1.34
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.16.1.42:3000/
  data_base_name: im
fastDFS:
  fastdfs_file_url: http://192.0.33.26:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: d24d1367-7f4f-43af-910e-a0a43799e040  # base库中,wx_wechat 的id字段

+ 5 - 0
svr/svr-cloud-job/src/main/resources/banner.txt

@ -0,0 +1,5 @@
 ____  _     ____                _  ____  ____
/ ___\/ \ |\/  __\              / |/  _ \/  _ \
|    \| | //|  \/|_____ ____    | || / \|| | //
\___ || \// |    /\____ ____\/\_| || \_/|| |_\\
\____/\__/  \_/\_\           \____/\____/\____/

+ 44 - 0
svr/svr-cloud-job/src/main/resources/quartz.properties

@ -0,0 +1,44 @@
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
 
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
 
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 5
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
 
org.quartz.jobStore.misfireThreshold: 60000
#是否集群
org.quartz.jobStore.isClustered=false
 
#============================================================================
# Configure JobStore
#============================================================================
 
# RAM
# org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
# Configure JobStore Cluster
org.quartz.jobStore.useProperties = true
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#datasource׺
org.quartz.jobStore.tablePrefix:QRTZ_
#org.quartz.jobStore.dataSource:qzDS
#
##============================================================================
## Configure Datasources
##============================================================================
##datasource
#org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
#org.quartz.dataSource.qzDS.URL: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#org.quartz.dataSource.qzDS.user: root
#org.quartz.dataSource.qzDS.password: 123456
org.quartz.jobGroupName = RS_JOBGROUP_NAME
org.quartz.triggerGroupName = RS_TRIGGERGROUP_NAME

+ 25 - 0
svr/svr-cloud-job/src/main/resources/system.properties

@ -0,0 +1,25 @@
#-------------------------中山医院-----------------------------#
# 健康频道状态
prescriptionStatus_update_job=0 */2 * * * ?
# 门诊记录过期job,每天1 点触发
prescription_overdue_job=0 0 1 * * ?
#每天13 点触发
data_upload_job=0 0 2 * * ?
#-------------------------中山医院end-----------------------------#
#-------------------------眼科医院-----------------------------#
data_ykupload_job=0 0 0 * * ?
#每间隔1分钟触发
unsettled_prescription_notice_job=0 */1 * * * ?
#-------------------------眼科医院end-----------------------------#
#-------------------------监管平台通用医院-----------------------------#
data_common_upload_job=0 0 0 * * ?
#------------------------物联网后台系统---------------------------#
#设备质检时间 每天24 点触发
data_device_quality_plan_job=0 0 0 * * ?
#SIM卡每月套餐扣费  每月1号凌晨0点0分0秒扣费
data_sim_set_meal_job=0 0 0 1 * ?
#设备库存预警提醒时间
device_inventory_warning_job = 0 0 7 * * ?