浏览代码

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

wujunjie 7 年之前
父节点
当前提交
34db1c922c
共有 42 个文件被更改,包括 2894 次插入84 次删除
  1. 97 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLJobConfig.java
  2. 43 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDict.java
  3. 52 0
      common/common-entity/src/main/java/com/yihu/figure_label/entity/FLlabelDictJob.java
  4. 24 10
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/DeviceHealthIndexController.java
  5. 9 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndex.java
  6. 199 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/DeviceHealthIndexVO.java
  7. 23 2
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/WlyyPatientDeviceVO.java
  8. 111 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/device/PatientHealthStandard.java
  9. 4 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/WlyyPatientDeviceDao.java
  10. 85 7
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/DeviceHealthIndexService.java
  11. 3 1
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/WlyyPatientDeviceService.java
  12. 24 5
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list.jsp
  13. 144 5
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/deviceHealthIndex_list_js.jsp
  14. 2 1
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/patientDevice_list_js.jsp
  15. 9 0
      patient-co/patient-co-figure-label/pom.xml
  16. 8 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/FigureLabelApplication.java
  17. 2 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/config/db/WlyyJpa.java
  18. 445 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/BaseController.java
  19. 231 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/controller/JobController.java
  20. 65 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/AgeConvert.java
  21. 43 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/BirthConvert.java
  22. 4 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/Convert.java
  23. 98 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/ConvertHelper.java
  24. 14 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/HealthConditionConvert.java
  25. 36 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/convert/SexConvert.java
  26. 66 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLJobConfigDao.java
  27. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictDao.java
  28. 29 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/dao/FLLabelDictJobDao.java
  29. 7 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/Extracter.java
  30. 22 2
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/extract/MysqlExtracter.java
  31. 143 7
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/job/Mysql2ESJob.java
  32. 80 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/DataModel.java
  33. 0 31
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/ExtractModel.java
  34. 30 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/model/SaveModel.java
  35. 5 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/ExtractService.java
  36. 390 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/service/JobService.java
  37. 37 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2ES.java
  38. 12 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/storage/Store2Hbase.java
  39. 7 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/ConstantUtil.java
  40. 124 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/IdCardUtil.java
  41. 121 0
      patient-co/patient-co-figure-label/src/main/java/com/yihu/wlyy/figure/label/util/QuartzHelpers.java
  42. 17 5
      patient-co/patient-co-figure-label/src/main/resources/application-dev.yml

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

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

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

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

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

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

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

@ -1,23 +1,24 @@
package com.yihu.wlyy.controller.manager.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.device.entity.DeviceHealthIndex;
import com.yihu.wlyy.device.entity.DeviceHealthIndexExportVO;
import com.yihu.wlyy.device.entity.DeviceHealthIndexVO;
import com.yihu.wlyy.service.manager.device.DeviceHealthIndexService;
import jxl.Workbook;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2016/12/5.
@ -38,10 +39,11 @@ public class DeviceHealthIndexController extends BaseController{
            @RequestParam(value = "date",required = false) String date,
            @RequestParam(value = "idcard",required = false) String idcard,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "indexType",required = false) String indexType,
            @RequestParam(value = "page",required = false) Integer page,
            @RequestParam(value = "rows",required = false) Integer pageSize){
        try{
            Page<DeviceHealthIndex> deviceHealthIndexes = healthIndexService.searchList(deviceSn,date, idcard, userName, page, pageSize);
            Page<DeviceHealthIndexVO> deviceHealthIndexes = healthIndexService.searchList(deviceSn,date, idcard, userName, indexType,page, pageSize);
            return write(200,"操作成功",page,pageSize,deviceHealthIndexes);
        }catch (Exception ex){
            error(ex);
@ -50,19 +52,31 @@ public class DeviceHealthIndexController extends BaseController{
    }
    
    //导出报表
    @ResponseBody
    @RequestMapping(value="toExcel",method = RequestMethod.POST,produces = "application/json;charset=UTF-8" )
    public void exportList(
            @RequestParam(value = "town",required = false)String town,
            @RequestParam(value = "hospital",required = false)String hospital,
    public  String exportList(
            @RequestParam(value = "deviceSn",required = false) String deviceSn,
            @RequestParam(value = "date",required = false) String date,
            @RequestParam(value = "idcard",required = false) String idcard,
            @RequestParam(value = "userName",required = false) String userName,
            @RequestParam(value = "indexType",required = false) String indexType,
            @RequestParam(value = "indexTypeMin",required = false) String indexTypeMin,
            @RequestParam(value = "indexTypeMax",required = false) String indexTypeMax,
            HttpServletResponse response){
        try {
            List<DeviceHealthIndexExportVO> wlyyDevices = healthIndexService.exportDeviceHealthIndexList(town,hospital);
//            List<DeviceHealthIndexExportVO> wlyyDevices = healthIndexService.exportDeviceHealthIndexList(town,hospital);
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename="+ new String( "deviceHealthIndexDataList.xls"));
            OutputStream os = response.getOutputStream();
            this.write(os,wlyyDevices);
//            this.write(os,wlyyDevices);
//            write(200, "操作成功!");
//            Map<Object, Object> map = new HashMap<Object, Object>();
//            map.put("status", 200);
//            map.put("msg", "操作成功!");
            return write(200, "操作成功");
        }catch (Exception ex){
            error(ex);
            return null;
        }
    }
    

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

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

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

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

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

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

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

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

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

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

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

@ -2,12 +2,18 @@ package com.yihu.wlyy.service.manager.device;
import com.yihu.wlyy.device.entity.DeviceHealthIndex;
import com.yihu.wlyy.device.entity.DeviceHealthIndexExportVO;
import com.yihu.wlyy.device.entity.DeviceHealthIndexVO;
import com.yihu.wlyy.device.repository.DeviceHealthIndexDao;
import com.yihu.wlyy.entity.Patient;
import com.yihu.wlyy.entity.device.PatientHealthStandard;
import com.yihu.wlyy.repository.PatientDao;
import com.yihu.wlyy.repository.WlyyPatientDeviceDao;
import com.yihu.wlyy.util.DateTimeUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.query.BaseDeviceJpaService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
@ -30,10 +36,12 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
    private PatientDao patientDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyPatientDeviceDao wlyyPatientDeviceDao;
    public Page<DeviceHealthIndex> searchList(String deviceSn,String date,String idcard,String userName,Integer page,Integer pageSize)throws Exception{
    public Page<DeviceHealthIndexVO> searchList(String deviceSn,String date,String idcard,String userName,String indexType,Integer page,Integer pageSize)throws Exception{
        if (page == null){
            page = 1;
        }
@ -66,23 +74,32 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
            if(codes != null && codes.length >0){
                filter.append("user="+StringUtils.join(codes, ","));
            }else {
                return new PageImpl<DeviceHealthIndex>(new ArrayList<>(), pageRequest, 0);
                return new PageImpl<DeviceHealthIndexVO>(new ArrayList<>(), pageRequest, 0);
            }
        }
        if(!StringUtils.isEmpty(indexType)){
            filter.append("type="+indexType+";");
        }
        List<DeviceHealthIndex> list = (List<DeviceHealthIndex>)search("", filter.toString(), "-czrq", page, pageSize);
        long count = 0;
        String regex = "(\\w{3})(\\w+)(\\w{3})";
        List<DeviceHealthIndexVO> listTemp = new ArrayList<>();
        if(list !=null && list.size()>0){
            count = getCount(filter.toString());
            for (DeviceHealthIndex info : list){
                Patient patient = findPatient(info.getUser());
                info.setUserName(patient== null?"":patient.getName());
                if(StringUtils.isNotBlank(info.getIdcard())){
                    info.setIdcard(info.getIdcard().replaceAll(regex, "$1****$3"));
                DeviceHealthIndexVO bean = new DeviceHealthIndexVO();
                BeanUtils.copyProperties(info, bean);
//                BeanUtils.copyProperties(bean, info);
                Patient patient = findPatient(bean.getUser());
                bean.setUserName(patient== null?"":patient.getName());
                if(StringUtils.isNotBlank(bean.getIdcard())){
                    bean.setIdcard(bean.getIdcard().replaceAll(regex, "$1****$3"));
                }
                bean.setHealthStandard(gethealthStandard(info.getType(),info.getUser()).toString());
                listTemp.add(bean);
            }
        }
        return new PageImpl<DeviceHealthIndex>(list,pageRequest,count);
        return new PageImpl<DeviceHealthIndexVO>(listTemp,pageRequest,count);
    }
    //查询居民姓名
@ -109,4 +126,65 @@ public class DeviceHealthIndexService extends BaseDeviceJpaService<DeviceHealthI
        list =  jdbcTemplate.query(sql,new BeanPropertyRowMapper(DeviceHealthIndexExportVO.class));
        return list ;
	}
    public JSONObject gethealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = SystemConf.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = wlyyPatientDeviceDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = SystemConf.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = SystemConf.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            json.put("minValueSZY", minValueSZY);
            json.put("maxValueSZY", maxValueSZY);
            json.put("minValueSSY", minValueSSY);
            json.put("maxValueSSY", maxValueSSY);
        }
        return json;
    }
}

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

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

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

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

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

@ -22,12 +22,35 @@
				this.grid.setOptions({parms: params});
				this.grid.loadData(true);
			}
            function reloadExcel(params) {
//                $.ajax({
//                    url: ctx + "/admin/healthIndex/toExcel",
//                    type: "post",
//                    dataType: "json",
//                    async: "true",
//                    data: params,
//                    success: function (result) {
//                        debugger;
//                        if (result.status == '200') {
//                            $.Notice.success(result.msg);
//                        } else {
//                            $.Notice.error(result.msg);
//                        }
//                    },
//                    error: function (data) {
//                        $.Notice.error("系统异常,请联系管理员!");
//                    }
//
//                })
            }
			/* *************************** 模块初始化 ***************************** */
			retrieve = {
				$element: $('.m-retrieve-area'),
				$searchBtn: $('#btn_search'),
                $btnExport: $('#btn_excel'),
				$addBtn: $('#btn_add'),
@ -35,11 +58,16 @@
				$czrd: $("#inp_czrq"),
				$idcard: $("#inp_idcard"),
				$userName: $("#inp_user_name"),//人员姓名
                $indexType: $("#inp_index_type"),//指标类型
                $searchMin:$("#search-min"),
                $searchMax:$("#search-max"),
				init: function () {
					this.$element.show();
					this.$element.attrScan();
					window.form = this.$element;
					this.$deviceCode.ligerTextBox({width: 200});
                    this.$searchMax.ligerTextBox({width: 150});
                    this.$searchMin.ligerTextBox({width: 150});
					this.$czrd.ligerDateEditor({
						format: "yyyy-MM-dd",
						showTime: false,
@ -50,13 +78,80 @@
					this.$idcard.ligerTextBox({width: 150});
					this.$userName.ligerTextBox({width: 150});
					this.bindEvents();
                    this.typeBox = this.$indexType.ligerComboBox({
                        width: 150,
                        data: [
                            {text: '血糖', typeId: '1'},
                            {text: '血压', typeId: '2'},
                            {text: '体重', typeId: '3'},
                            {text: '腰围', typeId: '4'}
                        ],
//                        initIsTriggerEvent: false,
                        valueField: 'typeId',
                        onSelected: function (value,name) {
                            if(value){
                                $("#search-max").attr('placeholder',name+"最大值");
                                $("#search-min").attr('placeholder',name+'最小值');
                                $("#search-max").val('');
                                $("#search-min").val('');
                                $("#select-list").show();
                            }
                        }
                    });
				},
				bindEvents: function () {
					var self = this;
					self.$searchBtn.click(function () {
						master.grid.options.newPage = 1;
						master.reloadGrid();
					});
                        master.grid.options.newPage = 1;
                        master.reloadGrid();
                    });
                    self.$btnExport.click(function () {
//                        master.toExcel();
                        var myform = $("<form></form>");
                        myform.attr('method','post')
                        myform.attr('action',ctx + '/admin/healthIndex/toExcel');
                        self.$element.attrScan();
                        var values = self.$element.Fields.getValues();
                        //设备SN码
                        var deviceSn = $("<input type='hidden' name='deviceSn' />")
                        deviceSn.attr('value',$("#inp_device_code").val());
                        //查询日期
                        var date = $("<input type='hidden' name='date' />")
                        date.attr('value',$("#inp_czrq").val());
                        //身份证号
                        var idcard = $("<input type='hidden' name='idcard' />")
                        idcard.attr('value',$("#inp_idcard").val());
                        //居民姓名
                        var userName = $("<input type='hidden' name='userName' />")
                        userName.attr('value',$("#inp_user_name").val());
                        //血糖/血压/体重/腰围
                        var indexType = $("<input type='hidden' name='indexType' />")
                        indexType.attr('value',$("#inp_index_type_val").val());
                        //指标最小值
                        var indexTypeMin = $("<input type='hidden' name='indexTypeMin' />")
                        indexTypeMin.attr('value',$("#search-min").val());
                        //指标最大值
                        var indexTypeMax = $("<input type='hidden' name='indexTypeMax' />")
                        indexTypeMax.attr('value',$("#search-max").val());
                        myform.append(deviceSn);
                        myform.append(date);
                        myform.append(idcard);
                        myform.append(userName);
                        myform.append(indexType);
                        myform.append(indexTypeMin);
                        myform.append(indexTypeMax);
                        myform.appendTo('body').submit(); //must add this line for higher html spec
                    });
					//隐藏操作
                    self.$indexType.change(function(obj){
                        if(!obj.target.value){
                            $("#search-max").val('');
                            $("#search-min").val('');
                            $("#select-list").hide();
                        }
                    });
				}
			};
			master = {
@ -91,8 +186,45 @@
									}
								}
							},
							{display: 'value1', name: 'value1', width: '5%', align: "center"},
							{display: 'value2', name: 'value2', width: '5%', align: "center"},
							{display: 'value1', name: 'value1', width: '5%', align: "center",
                                render: function (row) {
                                    var standard = typeof(row.healthStandard)=='object'?row.healthStandard:JSON.parse(row.healthStandard)
                                    if(row.type==1){
                                        if(row.value1>standard.minValueBefore&&row.value1<standard.maxValueBefore){
                                            return row.value1;
                                        }else {
                                            return "<span style='color:red;'>"+row.value1+"</span>";
                                        }
                                    }else if(row.type==2){
                                        if(row.value1>standard.minValueSSY&&row.value1<standard.maxValueSSY){
                                            return row.value1;
                                        }else {
                                            return "<span style='color:red;'>"+row.value1+"</span>";
                                        }
                                    }
                                }
                            },
							{display: 'value2', name: 'value2', width: '5%', align: "center",
                                render: function (row) {
                                    var standard = typeof(row.healthStandard)=='object'?row.healthStandard:JSON.parse(row.healthStandard)
                                    if(row.type==1){
                                        if(row.value2>standard.minValueAfter&&row.value2<standard.maxValueAfter){
                                            return row.value2;
                                        }else {
                                            return "<span style='color:red;'>"+row.value2+"</span>";
                                        }
                                    }else if(row.type==2){
                                        if(row.value2>standard.minValueSZY&&row.value2<standard.maxValueSZY){
                                            return row.value2;
                                        }else {
                                            return "<span style='color:red;'>"+row.value2+"</span>";
                                        }
                                    }
                                }
                            },
							{display: 'value3', name: 'value3', width: '5%', align: "center"},
							{display: 'value4', name: 'value4', width: '5%', align: "center"},
							{display: 'value5', name: 'value5', width: '5%', align: "center"},
@ -106,8 +238,15 @@
				reloadGrid: function (msg) {
					retrieve.$element.attrScan();
					var values = retrieve.$element.Fields.getValues();
                    values.indexType = retrieve.typeBox.getValue();
					reloadGrid.call(this, values);
				},
                toExcel: function (msg) {
                    retrieve.$element.attrScan();
                    var values = retrieve.$element.Fields.getValues();
                    values.indexType = retrieve.typeBox.getValue();
                    reloadExcel(values);
                }
			};
			pageInit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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