Browse Source

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

trick9191 7 years ago
parent
commit
e1d5e1ec26
44 changed files with 4809 additions and 948 deletions
  1. 2 2
      common/common-entity/src/main/java/com/yihu/wlyy/entity/device/PatientDevice.java
  2. 1 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/config/SpringSecurityConfig.java
  3. 1 1
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/IotDeviceController.java
  4. 25 3
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/WlyyDeviceController.java
  5. 153 63
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/WlyyDevice.java
  6. 3 7
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/repository/DeviceManufacturerDao.java
  7. 2 3
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/repository/WlyyDeviceDao.java
  8. 108 108
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/DmDevice.java
  9. 415 322
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Patient.java
  10. 75 0
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/SignPatientLabelInfo.java
  11. 13 12
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/DmDeviceDao.java
  12. 1 1
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/DeviceManufacturerService.java
  13. 253 8
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/device/WlyyDeviceService.java
  14. 2 2
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_create_js.jsp
  15. 8 0
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_list.jsp
  16. 27 1
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_list_js.jsp
  17. 3 3
      patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_modify_js.jsp
  18. 62 0
      patient-co-service/wlyy_service/pom.xml
  19. 104 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticFactory.java
  20. 1374 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticsearchUtil.java
  21. 32 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ZysoftServiceController.java
  22. 316 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/vo/SaveModel.java
  23. 168 3
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java
  24. 1 1
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/guahao/GuahaoService.java
  25. 68 0
      patient-co-service/wlyy_service/src/main/resources/application.yml
  26. 6 11
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/BaseService.java
  27. 17 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/DeviceDetailService.java
  28. 1 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceLogService.java
  29. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java
  30. 550 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/CreditLogService.java
  31. 78 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/TaskRuleService.java
  32. 167 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/TaskService.java
  33. 84 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/message/MessageService.java
  34. 36 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java
  35. 0 330
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/health/bank/CreditLogService.java
  36. 4 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/HttpClientUtil.java
  37. 5 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/data/DataHandlingController.java
  38. 17 9
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java
  39. 272 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/bank/ActivityController.java
  40. 26 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/message/DoctorMessageController.java
  41. 4 4
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java
  42. 90 46
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/CreditsLogController.java
  43. 131 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/bank/TaskController.java
  44. 103 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/AccountController.java

+ 2 - 2
common/common-entity/src/main/java/com/yihu/wlyy/entity/device/PatientDevice.java

@ -15,7 +15,7 @@ public class PatientDevice extends IdEntity {
    // 设备ID
    private Long deviceId;
    // 设备标识 1血糖仪,2.血压计
    // 设备标识
    private String deviceSn;
    //sim卡号
    private String sim;
@ -23,7 +23,7 @@ public class PatientDevice extends IdEntity {
    private String deviceName;
    // 用户code
    private String user;
    // 设备类型标识
    // 设备类型标识 1血糖仪,2.血压计
    private String categoryCode;
    // 用户类型标准 -1代表单用户
    private String userType;

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

@ -38,6 +38,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
                "/admin/hos/importData",
                "/admin/hos/doctor/toExcel",
                "/admin/device/toExcel",
                "/admin/device/importData",
                "/admin/patientDevice/toExcel",
                "/admin/healthIndex/toExcel",
                "/admin/healthIndex/getExcelByFilter",

+ 1 - 1
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/IotDeviceController.java

@ -54,7 +54,7 @@ public class IotDeviceController extends BaseController {
    @RequestMapping(value = "findDeviceById",method = RequestMethod.GET)
    @ApiOperation("根据设备id查找设备管理")
    public String getDevice(@RequestParam(value = "id") Integer id){
    public String getDevice(@RequestParam(value = "id") Long id){
        try {
            WlyyDevice device = deviceService.findById(id);
            return  write(200,"操作成功","data",device);

+ 25 - 3
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/controller/manager/device/WlyyDeviceController.java

@ -5,6 +5,7 @@ import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.device.entity.WlyyDevice;
import com.yihu.wlyy.service.manager.device.WlyyDeviceService;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
@ -14,8 +15,10 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
@ -71,7 +74,7 @@ public class WlyyDeviceController extends BaseController {
    @RequestMapping(value = "device")
    @ResponseBody
    public String getDevice(@RequestParam(value = "id") Integer id){
    public String getDevice(@RequestParam(value = "id") Long id){
        try {
            WlyyDevice device = deviceService.findById(id);
            return  write(200,"操作成功","data",device);
@ -122,7 +125,7 @@ public class WlyyDeviceController extends BaseController {
    @RequestMapping(value = "delete")
    @ResponseBody
    public String deleteDevice(Integer id){
    public String deleteDevice(Long id){
        try{
            deviceService.deleteDevice(id);
            return write(200,"操作成功");
@ -158,7 +161,26 @@ public class WlyyDeviceController extends BaseController {
            error(ex);
        }
    }
    
    //导入设备报表
    @RequestMapping(value = "importData", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String importData(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = request.getInputStream();
            Workbook workbook = Workbook.getWorkbook(inputStream);
            deviceService.importData(workbook);
            return write(200, "操作成功");
        } catch (IOException | BiffException e) {
            e.printStackTrace();
            error(e);
            return error(-1, "操作失败!");
        }
    }
    public void addHeader(WritableSheet ws) throws WriteException {
        
        String[] header = {"ID","设备名称","型号","SN码", "SIM卡号","机构名称", "联系人", "联系电话", "厂家名称"};

+ 153 - 63
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/entity/WlyyDevice.java

@ -1,48 +1,109 @@
package com.yihu.wlyy.device.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Administrator on 2016/12/1.
 * Created by Administrator on 2018/6/14.
 * 设备表
 */
@Entity
@Table(name = "wlyy_devices",catalog = "device",schema = "")
public class WlyyDevice {
    private Integer id;
    private Date applyDate; //申请日期
    private String orgName;//机构名称
    private String linkman;//联系人
    private String tel;//联系电话
    private String serverIp;//服务IP地址
@Table(name = "wlyy_devices")
public class WlyyDevice extends IdEntity{
    private String deviceName;//设备名称
    private String deviceModel;//设备型号
    private String deviceModel;//型号
    private String deviceCode;//设备唯一标识
    private String manufacturerCode;//厂家代码
    private String manufacturer;//厂家名称
    private Date applyDate;//申请日期
    private String orgName;//(居民)机构名称
    private String linkman;//联系人(居民)
    private String tel;//联系人(居民)电话
    private String serverIp;//服务IP地址
    private String manufacturerCode;//厂商代码threeNod:三诺 urion:优瑞恩 bioland:爱奥乐 comvee:康为
    private String address;//厂家地址
    private String representative;//法人代表
    private String applicantName;//申请注册人
    private String applicantIdentity;//申请人身份证号
    private String applicantTel;//申请人手机
    private String applicantMail;//申请人邮箱
    private String sim;//sim卡号
    private String applicantName;//申请注册人(发放人/医生)
    private String applicantIdentity;//申请人(发放人/医生)身份证号
    private String applicantTel;//申请人(发放人/医生)手机
    private String applicantMail;//申请人(发放人/医生)邮箱
    //1.4.8版本新增字段
    private String sim;//SIM卡
    private String manufacturerId;//厂商表的业务关联code
    private Integer isGrant;//是否发放(0否1是)
    private String grantAdminTeam;//发放的患者所在团队
    private String grantOrgCode;//发放所在机构
    private Integer isBinding;//是否绑定(0否 1 绑定单端口 2 绑定双端口)
    private String bindingCount;//绑定次数({"1":"0", "2":"0"})
    private Date grantTime;//发放时间
    /** default constructor */
    public WlyyDevice() {
    }
    /** full constructor */
    public WlyyDevice(String deviceName, String deviceModel, String deviceCode, String manufacturer, Date applyDate
            , String orgName, String linkman, String tel, String serverIp, String manufacturerCode, String address
            , String representative, String applicantName, String applicantIdentity, String applicantTel, String applicantMail) {
        this.deviceName = deviceName;
        this.deviceModel = deviceModel;
        this.deviceCode = deviceCode;
        this.manufacturer = manufacturer;
        this.applyDate = applyDate;
        this.orgName = orgName;
        this.linkman = linkman;
        this.tel = tel;
        this.serverIp = serverIp;
        this.manufacturerCode = manufacturerCode;
        this.address = address;
        this.representative = representative;
        this.applicantName = applicantName;
        this.applicantIdentity = applicantIdentity;
        this.applicantTel = applicantTel;
        this.applicantMail = applicantMail;
    }
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "device_model")
    public String getDeviceModel() {
        return deviceModel;
    }
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }
    public void setId(Integer id) {
        this.id = id;
    @Column(name = "device_code")
    public String getDeviceCode() {
        return deviceCode;
    }
    public void setDeviceCode(String deviceCode) {
        this.deviceCode = deviceCode;
    }
    @Column(name = "manufacturer")
    public String getManufacturer() {
        return manufacturer;
    }
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    @Column(name = "apply_date")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getApplyDate() {
        return applyDate;
    }
@ -60,6 +121,7 @@ public class WlyyDevice {
        this.orgName = orgName;
    }
    @Column(name = "linkman")
    public String getLinkman() {
        return linkman;
    }
@ -68,6 +130,7 @@ public class WlyyDevice {
        this.linkman = linkman;
    }
    @Column(name = "tel")
    public String getTel() {
        return tel;
    }
@ -85,35 +148,7 @@ public class WlyyDevice {
        this.serverIp = serverIp;
    }
    @Basic
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "device_model")
    public String getDeviceModel() {
        return deviceModel;
    }
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }
    @Column(name = "device_code")
    public String getDeviceCode() {
        return deviceCode;
    }
    public void setDeviceCode(String deviceCode) {
        this.deviceCode = deviceCode;
    }
    @Column(name = "manufacturer_code")
    @Column(name = "manufacturerCode")
    public String getManufacturerCode() {
        return manufacturerCode;
    }
@ -122,15 +157,7 @@ public class WlyyDevice {
        this.manufacturerCode = manufacturerCode;
    }
    @Column(name = "manufacturer")
    public String getManufacturer() {
        return manufacturer;
    }
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    @Column(name = "address")
    public String getAddress() {
        return address;
    }
@ -184,6 +211,15 @@ public class WlyyDevice {
        this.applicantMail = applicantMail;
    }
    @Column(name = "manufacturer_id")
    public String getManufacturerId() {
        return manufacturerId;
    }
    public void setManufacturerId(String manufacturerId) {
        this.manufacturerId = manufacturerId;
    }
    @Column(name = "sim")
    public String getSim() {
        return sim;
@ -192,4 +228,58 @@ public class WlyyDevice {
    public void setSim(String sim) {
        this.sim = sim;
    }
    @Column(name = "is_grant")
    public Integer getIsGrant() {
        return isGrant;
    }
    public void setIsGrant(Integer grant) {
        isGrant = grant;
    }
    @Column(name = "grant_admin_team")
    public String getGrantAdminTeam() {
        return grantAdminTeam;
    }
    public void setGrantAdminTeam(String grantAdminTeam) {
        this.grantAdminTeam = grantAdminTeam;
    }
    @Column(name = "grant_org_code")
    public String getGrantOrgCode() {
        return grantOrgCode;
    }
    public void setGrantOrgCode(String grantOrgCode) {
        this.grantOrgCode = grantOrgCode;
    }
    @Column(name = "is_binding")
    public Integer getIsBinding() {
        return isBinding;
    }
    public void setIsBinding(Integer isBinding) {
        this.isBinding = isBinding;
    }
    @Column(name = "binding_count")
    public String getBindingCount() {
        return bindingCount;
    }
    public void setBindingCount(String bindingCount) {
        this.bindingCount = bindingCount;
    }
    @Column(name = "grant_time")
    public Date getGrantTime() {
        return grantTime;
    }
    public void setGrantTime(Date grantTime) {
        this.grantTime = grantTime;
    }
}

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

@ -10,9 +10,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
 * Created by humingfen on 2018/6/6.
 */
public interface DeviceManufacturerDao extends PagingAndSortingRepository<DeviceManufacturer, Integer>, JpaSpecificationExecutor<DeviceManufacturer> {
    @Query("select dm from DeviceManufacturer dm where dm.id = ?1")
    DeviceManufacturer findById(Long id);
public interface DeviceManufacturerDao extends PagingAndSortingRepository<DeviceManufacturer, Long>, JpaSpecificationExecutor<DeviceManufacturer> {
    @Transactional
    @Modifying
@ -21,8 +19,6 @@ public interface DeviceManufacturerDao extends PagingAndSortingRepository<Device
    DeviceManufacturer findByCode(String code);
    @Transactional
    @Modifying
    @Query("delete from DeviceManufacturer dm where dm.id = ?1")
    void delete(Long id);
    @Query("select dm.manufacturerCode from DeviceManufacturer dm where dm.code = ?1")
    String getManufacturerCodeByCode(String code);
}

+ 2 - 3
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/device/repository/WlyyDeviceDao.java

@ -4,11 +4,10 @@ import com.yihu.wlyy.device.entity.WlyyDevice;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yww on 2016/12/1.
 */
public interface WlyyDeviceDao extends PagingAndSortingRepository<WlyyDevice, Integer>, JpaSpecificationExecutor<WlyyDevice> {
public interface WlyyDeviceDao extends PagingAndSortingRepository<WlyyDevice, Long>, JpaSpecificationExecutor<WlyyDevice> {
    WlyyDevice findByDeviceCode(String deviceCode);
}

+ 108 - 108
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/DmDevice.java

@ -1,108 +1,108 @@
//package com.yihu.wlyy.entity;
//
//import com.fasterxml.jackson.annotation.JsonFormat;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.Table;
//import java.util.Date;
//
///**
// * 设备列表(设备厂家、设备信息)
// */
//@Entity
//@Table(name = "dm_device")
//public class DmDevice extends IdEntity {
//
//	private String categoryCode;
//	private String photo;
//	private String brands;
//	private String model;
//	private String isMultiUser;
//	private String multiUser;
//	private String name;
//	private Date czrq;
//	private String del;
//
//	@Column(name="category_code")
//	public String getCategoryCode() {
//		return categoryCode;
//	}
//
//	public void setCategoryCode(String categoryCode) {
//		this.categoryCode = categoryCode;
//	}
//
//	@Column(name="photo")
//	public String getPhoto() {
//		return photo;
//	}
//
//	public void setPhoto(String photo) {
//		this.photo = photo;
//	}
//
//	@Column(name="brands")
//	public String getBrands() {
//		return brands;
//	}
//
//	public void setBrands(String brands) {
//		this.brands = brands;
//	}
//
//	@Column(name="model")
//	public String getModel() {
//		return model;
//	}
//
//	public void setModel(String model) {
//		this.model = model;
//	}
//
//	@Column(name="is_multi_user")
//	public String getIsMultiUser() {
//		return isMultiUser;
//	}
//
//	public void setIsMultiUser(String isMultiUser) {
//		this.isMultiUser = isMultiUser;
//	}
//
//	@Column(name="multi_user")
//	public String getMultiUser() {
//		return multiUser;
//	}
//
//	public void setMultiUser(String multiUser) {
//		this.multiUser = multiUser;
//	}
//
//	@Column(name="name")
//	public String getName() {
//		return name;
//	}
//
//	public void setName(String name) {
//		this.name = name;
//	}
//
//	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
//	@Column(name="czrq")
//	public Date getCzrq() {
//		return czrq;
//	}
//
//	public void setCzrq(Date czrq) {
//		this.czrq = czrq;
//	}
//
//	@Column(name="del")
//	public String getDel() {
//		return del;
//	}
//
//	public void setDel(String del) {
//		this.del = del;
//	}
//}
package com.yihu.wlyy.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 设备列表(设备厂家、设备信息)
 */
@Entity
@Table(name = "dm_device")
public class DmDevice extends IdEntity {
	private String categoryCode;
	private String photo;
	private String brands;
	private String model;
	private String isMultiUser;
	private String multiUser;
	private String name;
	private Date czrq;
	private String del;
	@Column(name="category_code")
	public String getCategoryCode() {
		return categoryCode;
	}
	public void setCategoryCode(String categoryCode) {
		this.categoryCode = categoryCode;
	}
	@Column(name="photo")
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	@Column(name="brands")
	public String getBrands() {
		return brands;
	}
	public void setBrands(String brands) {
		this.brands = brands;
	}
	@Column(name="model")
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	@Column(name="is_multi_user")
	public String getIsMultiUser() {
		return isMultiUser;
	}
	public void setIsMultiUser(String isMultiUser) {
		this.isMultiUser = isMultiUser;
	}
	@Column(name="multi_user")
	public String getMultiUser() {
		return multiUser;
	}
	public void setMultiUser(String multiUser) {
		this.multiUser = multiUser;
	}
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	@Column(name="czrq")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	@Column(name="del")
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
}

+ 415 - 322
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/Patient.java

@ -7,7 +7,9 @@ import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 患者信息
@ -23,302 +25,356 @@ public class Patient extends IdEntity implements Serializable {
	 */
	private static final long serialVersionUID = 8358924836164389434L;
	// 业务主键
	private String code;
	// 身份证号
	private String idcard;
	// 登录密码
	private String password;
	private String salt;
	// 姓名
	private String name;
	// 生日
	private Date birthday;
	// 性別,1男,2女
	private Integer sex;
	// 手機號
	private String mobile;
	// 聯繫電話
	private String phone;
	// 社保卡號
	private String ssc;
	// 頭像HTTP地址
	private String photo;
	// 省代碼
	private String province;
	// 城市代碼
	private String city;
	// 區縣代碼
	private String town;
	// 街道代码
	private String street;
	// 省名
	private String provinceName;
	// 市名
	private String cityName;
	// 區縣名
	private String townName;
	// 街道名称
	private String streetName;
	// 地址
	private String address;
	// 疾病类型,0健康,1高血压,2糖尿病,3高血压+糖尿病
	private Integer disease;
	private String diseaseName;
	// 病情:0绿标,1黄标,2红标
	private Integer diseaseCondition;
	private String diseaseConditionName;
	// 病历记录总数
	private Integer recordAmount;
	// 總積分
	private Integer points;
	// 更新時間
	private Date czrq;
	// 微信编号
	private String openid;
	// 用户状态:1正常,0禁用,-1恶意注册,2审核中
	private Integer status;
    //联系方式备注【基卫】mobile_remarks
    // 业务主键
    private String code;
    // 身份证号
    private String idcard;
    // 登录密码
    private String password;
    private String salt;
    // 姓名
    private String name;
    // 生日
    private Date birthday;
    // 性別,1男,2女
    private Integer sex;
    // 手機號
    private String mobile;
    // (基卫)手機號
    private String mobileRemarks;
	//微信开放平台主键
	private String unionId;
    // 聯繫電話
    private String phone;
    // 社保卡號
    private String ssc;
    // 頭像HTTP地址
    private String photo;
    // 省代碼
    private String province;
    // 城市代碼
    private String city;
    // 區縣代碼
    private String town;
    // 街道代码
    private String street;
    // 省名
    private String provinceName;
    // 市名
    private String cityName;
    // 區縣名
    private String townName;
    // 街道名称
    private String streetName;
    // 地址
    private String address;
    // 疾病类型,0健康,1高血压,2糖尿病,3高血压+糖尿病
    private Integer disease;
    // 病情:0绿标,1黄标,2红标
    private Integer diseaseCondition;
    // 病历记录总数
    private Integer recordAmount;
    // 總積分
    private Integer points;
    // 更新時間
    private Date czrq;
    // 微信编号
    private String openid;
    //微信时间
    private Date openidTime;
    // 用户状态:1正常,0禁用,-1恶意注册,2审核中
    private Integer status;
    // 居委会字段id
    private String sickVillage;
    // 居委会字段名称
    private String sickVillageName;
    //	绑定电子社保卡主体(本人为本人code,共济为操作人code)
    private String principalCode;
    //	是否绑定电子社保卡
    private Integer sicardStatus;
    //	绑定电子社保卡时间
    private Date sicardTime;
    //是否分配过微信标签  1分配过 0或者空没有
    private Integer isWxtag;
    //微信iagId
    private Integer wxtagid;
    //居民预警状态:0为标准,1为预警状态
    private Integer standardStatus;
    //医疗保险号
    private String medicareNumber;
    //微信开发平台唯一标识
    private String unionid;
    public String getPrincipalCode() {
        return principalCode;
    }
    public void setPrincipalCode(String principalCode) {
        this.principalCode = principalCode;
    }
    public Integer getSicardStatus() {
        return sicardStatus;
    }
    public void setSicardStatus(Integer sicardStatus) {
        this.sicardStatus = sicardStatus;
    }
    public Date getSicardTime() {
        return sicardTime;
    }
    public void setSicardTime(Date sicardTime) {
        this.sicardTime = sicardTime;
    }
    private List<SignPatientLabelInfo> labelInfos = new ArrayList<>();//患者的疾病标签list
    public Patient() {
    }
    public Patient(Long id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSalt() {
        return salt;
    }
    public void setSalt(String salt) {
        this.salt = salt;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getBirthday() {
        return birthday;
    }
	public Patient() {
	}
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
	public Patient(Long id) {
		this.id = id;
	}
    public Integer getSex() {
        return sex;
    }
	public String getCode() {
		return code;
	}
    public void setSex(Integer sex) {
        this.sex = sex;
    }
	public void setCode(String code) {
		this.code = code;
	}
    public String getMobile() {
        return mobile;
    }
	public String getIdcard() {
		return idcard;
	}
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
    public String getPhone() {
        return phone;
    }
	public String getPassword() {
		return password;
	}
    public void setPhone(String phone) {
        this.phone = phone;
    }
	public void setPassword(String password) {
		this.password = password;
	}
    public String getSsc() {
        return ssc;
    }
	public String getSalt() {
		return salt;
	}
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
	public void setSalt(String salt) {
		this.salt = salt;
	}
    @Column(name = "photo", insertable = false)
    public String getPhoto() {
        return photo;
    }
	public String getName() {
		return name;
	}
    public void setPhoto(String photo) {
        this.photo = photo;
    }
	public void setName(String name) {
		this.name = name;
	}
    public String getProvince() {
        return province;
    }
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
    public void setProvince(String province) {
        this.province = province;
    }
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
    public String getCity() {
        return city;
    }
	public Integer getSex() {
		return sex;
	}
    public void setCity(String city) {
        this.city = city;
    }
	public void setSex(Integer sex) {
		this.sex = sex;
	}
    public String getTown() {
        return town;
    }
	public String getMobile() {
		return mobile;
	}
    public void setTown(String town) {
        this.town = town;
    }
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
    public String getStreet() {
        return street;
    }
	public String getPhone() {
		return phone;
	}
    public void setStreet(String street) {
        this.street = street;
    }
    @Column(name = "province_name")
    public String getProvinceName() {
        return provinceName;
    }
    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }
    @Column(name = "city_name")
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
	public void setPhone(String phone) {
		this.phone = phone;
	}
    @Column(name = "town_name")
    public String getTownName() {
        return townName;
    }
	public String getSsc() {
		return ssc;
	}
    public void setTownName(String townName) {
        this.townName = townName;
    }
    @Column(name = "street_name")
    public String getStreetName() {
        return streetName;
    }
    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getDisease() {
        return disease;
    }
    public void setDisease(Integer disease) {
        this.disease = disease;
    }
    @Column(name = "disease_condition")
    public Integer getDiseaseCondition() {
        return diseaseCondition;
    }
    public void setDiseaseCondition(Integer diseaseCondition) {
        this.diseaseCondition = diseaseCondition;
    }
    @Column(name = "record_amount")
    public Integer getRecordAmount() {
        return recordAmount;
    }
    public void setRecordAmount(Integer recordAmount) {
        this.recordAmount = recordAmount;
    }
    public Integer getPoints() {
        return points;
    }
    public void setPoints(Integer points) {
        this.points = points;
    }
    @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 getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getTown() {
		return town;
	}
	public void setTown(String town) {
		this.town = town;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	@Column(name = "province_name")
	public String getProvinceName() {
		return provinceName;
	}
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	@Column(name = "city_name")
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	@Column(name = "town_name")
	public String getTownName() {
		return townName;
	}
	public void setTownName(String townName) {
		this.townName = townName;
	}
	@Column(name = "street_name")
	public String getStreetName() {
		return streetName;
	}
	public void setStreetName(String streetName) {
		this.streetName = streetName;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getDisease() {
		return disease;
	}
	public void setDisease(Integer disease) {
		this.disease = disease;
	}
	@Column(name = "disease_condition")
	public Integer getDiseaseCondition() {
		return diseaseCondition;
	}
	public void setDiseaseCondition(Integer diseaseCondition) {
		this.diseaseCondition = diseaseCondition;
	}
	@Column(name = "record_amount")
	public Integer getRecordAmount() {
		return recordAmount;
	}
	public void setRecordAmount(Integer recordAmount) {
		this.recordAmount = recordAmount;
	}
	public Integer getPoints() {
		return points;
	}
	public void setPoints(Integer points) {
		this.points = points;
	}
	@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 getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
    public Integer getStatus() {
		return status;
	}
        return status;
    }
	public void setStatus(Integer status) {
		this.status = status;
	}
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Transient
    public List<SignPatientLabelInfo> getLabelInfos() {
        return labelInfos;
    }
    public void setLabelInfos(List<SignPatientLabelInfo> labelInfos) {
        this.labelInfos = labelInfos;
    }
    @Column(name = "mobile_remarks")
    public String getMobileRemarks() {
        return mobileRemarks;
    }
@ -327,57 +383,94 @@ public class Patient extends IdEntity implements Serializable {
        this.mobileRemarks = mobileRemarks;
    }
	public void setUnionId(String unionId) {
		this.unionId = unionId;
	}
	public String getUnionId() {
		return unionId;
	}
	@Transient
	public String getDiseaseName() {//0健康,1高血压,2糖尿病,3高血压+糖尿病
		if(disease==null){
			this.diseaseName = "";
			return diseaseName;
		}
		if(0==disease) {
			this.diseaseName = "健康";
		}else if(1==disease) {
			this.diseaseName = "高血压";
		}else if(2==disease) {
			this.diseaseName = "糖尿病";
		}else if(3==disease) {
			this.diseaseName = "高血压+糖尿病";
		}else{
			this.diseaseName = "";
		}
		return diseaseName;
	}
	public void setDiseaseName(String diseaseName) {
		this.diseaseName = diseaseName;
	}
	@Transient
	public String getDiseaseConditionName() {
		if(null==diseaseCondition){
			this.diseaseConditionName = "";
			return diseaseConditionName;
		}
		if(0==diseaseCondition) {
			this.diseaseConditionName = "绿标";
		}else if(1==diseaseCondition) {
			this.diseaseConditionName = "黄标";
		}else if(2==diseaseCondition) {
			this.diseaseConditionName = "红标";
		}else{
			this.diseaseConditionName = "";
		}
		return diseaseConditionName;
	}
	public void setDiseaseConditionName(String diseaseConditionName) {
		this.diseaseConditionName = diseaseConditionName;
	}
    public Date getOpenidTime() {
        return openidTime;
    }
    public void setOpenidTime(Date openidTime) {
        this.openidTime = openidTime;
    }
    public String getSickVillage() {
        return sickVillage;
    }
    public void setSickVillage(String sickVillage) {
        this.sickVillage = sickVillage;
    }
    public String getSickVillageName() {
        return sickVillageName;
    }
    public void setSickVillageName(String sickVillageName) {
        this.sickVillageName = sickVillageName;
    }
    public Integer getIsWxtag() {
        return isWxtag;
    }
    public void setIsWxtag(Integer isWxtag) {
        this.isWxtag = isWxtag;
    }
    public Integer getWxtagid() {
        return wxtagid;
    }
    public void setWxtagid(Integer wxtagid) {
        this.wxtagid = wxtagid;
    }
    //---------------------------常量----------------------------
    public enum isWchatTage {
        yes(1), no(0);
        isWchatTage(Integer value) {
            this.value = value;
        }
        private Integer value;
        public Integer getValue() {
            return value;
        }
        public void setValue(Integer value) {
            this.value = value;
        }
    }
    public Integer getStandardStatus() {
        return standardStatus;
    }
    public void setStandardStatus(Integer standardStatus) {
        this.standardStatus = standardStatus;
    }
    public Patient(String code, String name) {
        this.code = code;
        this.name = name;
    }
    public Patient(String code) {
        this.code = code;
    }
    public String getMedicareNumber() {
        return medicareNumber;
    }
    public void setMedicareNumber(String medicareNumber) {
        this.medicareNumber = medicareNumber;
    }
    public String getUnionid() {
        return unionid;
    }
    public void setUnionid(String unionid) {
        this.unionid = unionid;
    }
}

+ 75 - 0
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/entity/SignPatientLabelInfo.java

@ -0,0 +1,75 @@
package com.yihu.wlyy.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "wlyy_sign_patient_label_info")
public class SignPatientLabelInfo extends IdEntity {
    // 患者code
    private String patient;
    // 患者姓名
    private String pname;
    // 标签code
    private String label;
    // 标签名称
    private String labelName;
    // 标签类型
    private String labelType;
    // 状态 0:无效 1:有效
    private Integer status;
    // 操作日期
    private Date czrq;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 13 - 12
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/repository/DmDeviceDao.java

@ -1,12 +1,13 @@
//package com.yihu.wlyy.repository;
//
//
//import com.yihu.wlyy.entity.DmDevice;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Administrator on 2017/1/18.
// */
//public interface DmDeviceDao extends PagingAndSortingRepository<DmDevice,Long> {
//
//}
package com.yihu.wlyy.repository;
import com.yihu.wlyy.entity.DmDevice;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2018/6/14.
 */
public interface DmDeviceDao extends PagingAndSortingRepository<DmDevice,Long> {
    DmDevice findByModel(String deviceModel);
}

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

@ -50,7 +50,7 @@ public class DeviceManufacturerService  {
    public DeviceManufacturer findById(Long id) {
        return deviceManufacturerDao.findById(id);
        return deviceManufacturerDao.findOne(id);
    }
    public void  updateManufacturer(DeviceManufacturer manufacturer) {

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

@ -1,7 +1,15 @@
package com.yihu.wlyy.service.manager.device;
        import com.yihu.wlyy.device.entity.WlyyDevice;
import com.yihu.wlyy.device.entity.DeviceManufacturer;
import com.yihu.wlyy.device.entity.WlyyDevice;
import com.yihu.wlyy.device.repository.DeviceManufacturerDao;
import com.yihu.wlyy.device.repository.WlyyDeviceDao;
import com.yihu.wlyy.entity.DmDevice;
import com.yihu.wlyy.repository.DmDeviceDao;
import com.yihu.wlyy.service.common.excel.ExcelData;
import com.yihu.wlyy.util.ReadExcelUtil;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
@ -12,10 +20,9 @@ import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by yww on 2016/12/1.
@ -25,8 +32,12 @@ import java.util.Map;
public class WlyyDeviceService {
    @Autowired
    private WlyyDeviceDao deviceDao;
    @Autowired
    private DeviceManufacturerDao deviceManufacturerDao;
    @Autowired
    private DmDeviceDao dmDeviceDao;
    public WlyyDevice findById(Integer id){
    public WlyyDevice findById(Long id){
        return deviceDao.findOne(id);
    }
@ -60,6 +71,27 @@ public class WlyyDeviceService {
    @Transactional
    public WlyyDevice createDevice(WlyyDevice device){
        device.setApplyDate(new Date());
        String manufacturerCode = deviceManufacturerDao.getManufacturerCodeByCode(device.getManufacturerId());
        device.setManufacturerCode(manufacturerCode);
        //根据型号设置绑定次数形式
        if(device.getDeviceModel() != null) {
            DmDevice dmDevice = dmDeviceDao.findByModel(device.getDeviceModel());
            if(dmDevice == null) {
                if(device.getDeviceName().contains("血糖")) {
                    device.setBindingCount("{\"1\":\"0\"}");
                }else if(device.getDeviceName().contains("血压")) {
                    device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
                }
            }else {
                if(dmDevice.getIsMultiUser().equals("1")) {
                    device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
                }else if(dmDevice.getIsMultiUser().equals("0")) {
                    device.setBindingCount("{\"1\":\"0\"}");
                }
            }
        }
        device.setIsGrant(0);
        device.setIsBinding(0);
        WlyyDevice deviceNew = deviceDao.save(device);
        return deviceNew;
    }
@ -70,6 +102,8 @@ public class WlyyDeviceService {
        if(deviceNew == null){
            return null;
        }
        String manufacturerCode = deviceManufacturerDao.getManufacturerCodeByCode(device.getManufacturerId());
        deviceNew.setManufacturerCode(manufacturerCode);
        deviceNew.setOrgName(device.getOrgName());
        deviceNew.setLinkman(device.getLinkman());
        deviceNew.setTel(device.getTel());
@ -77,7 +111,7 @@ public class WlyyDeviceService {
        deviceNew.setDeviceName(device.getDeviceName());
        deviceNew.setDeviceModel(device.getDeviceModel());
        deviceNew.setDeviceCode(device.getDeviceCode());
        deviceNew.setManufacturerCode(device.getManufacturerCode());
        deviceNew.setManufacturerId(device.getManufacturerId());
        deviceNew.setManufacturer(device.getManufacturer());
        deviceNew.setAddress(device.getAddress());
        deviceNew.setRepresentative(device.getRepresentative());
@ -90,7 +124,7 @@ public class WlyyDeviceService {
    }
    @Transactional
    public boolean deleteDevice(Integer id){
    public boolean deleteDevice(Long id){
        deviceDao.delete(id);
        return true;
    }
@ -121,4 +155,215 @@ public class WlyyDeviceService {
        Specification<WlyyDevice> spec = DynamicSpecifications.bySearchFilter(filter.values(), WlyyDevice.class);
        return deviceDao.findAll(spec);
    }
    public boolean importData(Workbook workbook) {
        Sheet[] sheets = workbook.getSheets();
        Sheet sheet = sheets[0];
        int rows = ReadExcelUtil.getRightRows(sheet);
        List<WlyyDevice> deviceList = new ArrayList<>();
        for (int row = 1; row < rows; row++) {  //索引从0开始,第一行为标题
            WlyyDevice device = new WlyyDevice();
            Map<Integer, ExcelData> mapping = mappingDevice(device);
            int finalRow = row;
            mapping.forEach((index, excelData) -> {
                String value = sheet.getCell(index, finalRow).getContents().trim();
                excelData.transform(value);
            });
            //判断设备厂商是否存在,不存在则存入
            if(StringUtils.isNotBlank(device.getManufacturerId())) {
                DeviceManufacturer manufacturer = deviceManufacturerDao.findByCode(device.getManufacturerId());
                if (manufacturer == null) {
                    manufacturer.setCode(device.getManufacturerId());
                    manufacturer.setManufacturerCode(device.getManufacturerCode());
                    manufacturer.setManufacturerName(device.getManufacturer());
                    manufacturer.setCzrq(new Date());
                    deviceManufacturerDao.save(manufacturer);
                }
            }
            device.setIsGrant(0);
            device.setIsBinding(0);
            deviceList.add(device);
        }
        deviceDao.save(deviceList);
        return true;
    }
    private Map<Integer, ExcelData> mappingDevice(WlyyDevice device) {
        Map<Integer, ExcelData> dataMap = new HashMap<>();
        //申请日期
        dataMap.put(1, new ExcelData() {
            @Override
            public void transform(String data) {
                if(StringUtils.isNotBlank(data)) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        device.setApplyDate(simpleDateFormat.parse(data));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //机构名称
        dataMap.put(2, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setOrgName(data);
            }
        });
        //联系人
        dataMap.put(3, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setLinkman(data);
            }
        });
        //联系电话
        dataMap.put(4, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setTel(data);
            }
        });
        //服务IP地址
        dataMap.put(5, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setServerIp(data);
            }
        });
        //设备名称
        dataMap.put(6, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setDeviceName(data);
            }
        });
        //设备型号
        dataMap.put(7, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setDeviceModel(data);
            }
        });
        //设备唯一标识
        dataMap.put(8, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setDeviceCode(data);
            }
        });
        //厂商代码
        dataMap.put(9, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setManufacturerCode(data);
            }
        });
        //厂商名称
        dataMap.put(10, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setManufacturer(data);
            }
        });
        //厂商地址
        dataMap.put(11, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setAddress(data);
            }
        });
        //法人代表
        dataMap.put(12, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setRepresentative(data);
            }
        });
        //申请注册人
        dataMap.put(13, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setApplicantName(data);
            }
        });
        //申请人身份证号
        dataMap.put(14, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setApplicantIdentity(data);
            }
        });
        //申请人手机
        dataMap.put(15, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setApplicantTel(data);
            }
        });
        //申请人邮箱
        dataMap.put(16, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setApplicantMail(data);
            }
        });
        //SIM卡号
        dataMap.put(17, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setSim(data);
            }
        });
        //厂商表关联id
        dataMap.put(18, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setManufacturerId(data);
            }
        });
        //发放的患者所在团队
        dataMap.put(19, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setGrantAdminTeam(data);
            }
        });
        //发放所在机构
        dataMap.put(20, new ExcelData() {
            @Override
            public void transform(String data) {
                device.setGrantOrgCode(data);
            }
        });
        //根据仪器名称设定绑定次数
        dataMap.put(21, new ExcelData() {
            @Override
            public void transform(String data) {
                if(data.contains("血压")) {
                    device.setBindingCount("{\"1\":\"0\", \"2\":\"0\"}");
                } else if(data.contains("血糖")){
                    device.setBindingCount("{\"1\":\"0\"}");
                }
            }
        });
        //发放时间
        dataMap.put(22, new ExcelData() {
            @Override
            public void transform(String data) {
                if(StringUtils.isNotBlank(data)) {
                    try {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        device.setGrantTime(simpleDateFormat.parse(data));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        return dataMap;
    }
}

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

@ -52,7 +52,7 @@
                        for (var i = 0; i < data.data.length; i++) {
                            d.push({
                                text: data.data[i].manufacturerName,
                                id: data.data[i].manufacturerCode
                                id: data.data[i].code
                            });
                        }
                        that.initInpCat( d, that);
@ -99,7 +99,7 @@
						var values = self.$form.Fields.getValues();
						//厂家代码
						values.manufacturerCode = $("#sel_manufacturer").ligerComboBox("getValue");
						values.manufacturerId = $("#sel_manufacturer").ligerComboBox("getValue");
						if (!validator.validate()) {
							return;

+ 8 - 0
patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_list.jsp

@ -51,6 +51,14 @@
			</div>
			</sec:authorize>
			<sec:authorize url="/admin/device/importData">
				<div class="m-form-control m-form-control-fr">
					<div id="btn_import" class="l-button u-btn u-btn-primary u-btn-small f-ib f-vam f-mr20">
						<div id="div_file_picker" class="f-mt10" style="margin-top:-10px;">导入</div>
					</div>
				</div>
			</sec:authorize>
			<sec:authorize url="/admin/device/create">
			<div class="m-form-control m-form-control-fr">

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

@ -202,7 +202,33 @@
								self.delRecord(id, code);
							}
						});
					})
					});
                    var uploader = $("#btn_import").webupload({
                        server: ctx + "/admin/device/importData",
                        pick: {id: '#div_file_picker'},
                        accept: {
                            title: 'Excel',
                            extensions: 'xls',
                            mimeTypes: '.xls'
                        },
                        auto: true
                    });
                    uploader.on('beforeSend', function (file, data, headers) {
                    });
                    uploader.on('uploadProgress', function (file, percentage) {
                        $.ligerDialog.waitting('正在保存中,请稍候...');
                    });
                    uploader.on('uploadError', function (file) {
                        $.ligerDialog.closeWaitting();
                        $.Notice.error("上传失败!");
                    });
                    uploader.on('uploadSuccess', function (file, resp) {
                        $.ligerDialog.closeWaitting();
                        $.Notice.success("上传成功。");
                    });
				}
			};

+ 3 - 3
patient-co-manage/wlyy-manage/src/main/webapp/WEB-INF/views/device/device_modify_js.jsp

@ -46,7 +46,7 @@
                        parms: {},
                        dataParmName: "data",
                        textField: "manufacturerName",
                        valueField: "manufacturerCode",
                        valueField: "code",
                        isMultiSelect: false,
                        ajaxBeforeSend: function (xhr) {
                            if (ajaxHeaderName) {
@ -93,7 +93,7 @@
									applicantMail: data.applicantMail,
								});
								//填值
								_this.manufacturerBox.selectValue(data.manufacturerCode);
								_this.manufacturerBox.selectValue(data.manufacturerId);
							} else {
								$.Notice.error(result.msg);
							}
@ -158,7 +158,7 @@
						var values = self.$form.Fields.getValues();
						//厂家名称
						values.manufacturerCode = self.manufacturerBox.getValue();
						values.manufacturerId = self.manufacturerBox.getValue();
                        values.manufacturer = self.manufacturerBox.getText();
						if (!validator.validate()) {
							return;

+ 62 - 0
patient-co-service/wlyy_service/pom.xml

@ -195,6 +195,68 @@
            <version>2.5.0</version>
        </dependency>
        <!-- 智业接口引用 END -->
        <!--elasticsearch start-->
        <!--      <dependency>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch</artifactId>
                  <version>2.4.4</version>
              </dependency>
              <dependency>
                  <groupId>io.searchbox</groupId>
                  <artifactId>jest</artifactId>
                  <version>2.4.0</version>
              </dependency>-->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.ylz</groupId>
            <artifactId>onpay-java-sdk-all</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.1.0</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest-common</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--elasticsearch end-->
    </dependencies>
    <build>

+ 104 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticFactory.java

@ -0,0 +1,104 @@
package com.yihu.wlyy.service.common.util;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
 * Created by chenweida on 2017/6/5.
 */
@Component
public class ElasticFactory {
    private static JestClientFactory factory = null;
    @Value("${es.host}")
    private String esHost;//http://59.61.92.90:9065,http://59.61.92.90:9067
    @Value("${es.tHost}")
    private String tHost;// 59.61.92.90:9066,59.61.92.90:9068
    @Value("${es.clusterName}")
    private String clusterName;
//-----------------------------------jestClient----------------------------------------
    /**
     * @param "http://localhost:9200"
     * @return
     */
    public JestClient getJestClient() {
        if (factory == null) {
            //初始化链接
            init();
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     * 9200
     */
    public synchronized void init() {
        String[] hostArray = esHost.split(",");
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        HttpClientConfig httpClientConfig = new HttpClientConfig
                .Builder(Arrays.asList(hostArray))
                .multiThreaded(true)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(10, TimeUnit.MINUTES)//链接等待时间
                .connTimeout(60 * 1000*10)
                // .discoveryEnabled(true)
                .readTimeout(60 * 1000*10)//60秒
                .build();
        factory.setHttpClientConfig(httpClientConfig);//得到链接
    }
    //-----------------------------------TransportClient----------------------------------------
    private TransportClient transportClient;
    public Client getTransportClient() {
        try {
            initTranClient();
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 9300
     *
     * @throws UnknownHostException
     */
    private synchronized void initTranClient() throws UnknownHostException {
        if (transportClient == null) {
            String[] hosts = tHost.split(",");
            Settings settings = Settings.settingsBuilder()
                    // .put("client.transport.sniff", true)//开启嗅探功能
                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
                    .build();
            transportClient = TransportClient.builder().settings(settings).build();
            for (String oneHost : hosts) {
                String[] hostAndport = oneHost.split(":");
                transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAndport[0]), Integer.valueOf(hostAndport[1])));
            }
        }
    }
}

+ 1374 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticsearchUtil.java

@ -0,0 +1,1374 @@
package com.yihu.wlyy.service.common.util;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.SQLExprParser;
import com.yihu.wlyy.service.entity.vo.SaveModel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.jdbc.ObjectResult;
import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
import org.nlpcn.es4sql.parse.SqlParser;
import org.nlpcn.es4sql.query.AggregationQueryAction;
import org.nlpcn.es4sql.query.DefaultQueryAction;
import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by chenweida on 2017/7/17.
 * SELECT town,townName,sum(result1) result1 FROM wlyy_quota_test
 * where quotaCode='1'
 * group by town,townName , date_histogram(field='quotaDate','interval'='week')
 */
@Component
public class ElasticsearchUtil {
    private Logger logger = LoggerFactory.getLogger(ElasticsearchUtil.class);
    private final String commonParams = "xmijk_quota";
    
    
    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;
    public List excute(String sql, Class clazz, String esType, String esIndex) {
        List saveModels = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //解决 group by之后默认是200的问题
            if (sql.toLowerCase().contains("group by")) {
                sql = sql + " limit 0,2000";
            }
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || select.isAgg) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().forEach(one -> {
                Object saveModel = null;
                try {
                    saveModel = clazz.newInstance();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                for (int i = 0; i < one.size(); i++) {
                    try {
                        String key = null;
                        Object value = one.get(i);
                        if (heads.get(i).startsWith("_")) {
                            if(heads.get(i).contains("_id")){
                                clazz.getMethod("setId", String.class).invoke(saveModel, value);
                            }
                            continue;
                        }
                        key = "set" + UpFirstStr(heads.get(i));
                        if (heads.get(i).contains("quotaDate") || heads.get(i).contains("createTime") || heads.get(i).contains("date_histogram")) {
                            if (heads.get(i).contains("date_histogram")) {
                                key = "setQuotaDate";
                            }
                            
                            try {
                                //yyyy-MM-dd'T'HH:mm:ssXX
                                value = dateFormat.parse(String.valueOf(one.get(i)));
                            } catch (Exception e) {
                                //yyyy-MM-dd HH:mm:ss
                                try {
                                    value = dateFormat1.parse(String.valueOf(one.get(i)));
                                }catch (Exception e1){
                                    Timestamp ts = new Timestamp(Long.parseLong(String.valueOf(one.get(i))));
                                    try {
                                        Date date = new Date();
                                        date = ts;
                                        value =date;
                                    
                                    } catch (Exception e2) {
                                        value = String.valueOf(one.get(i));
                                    }
                                }
                                
                            }
//                            value = DateUtil.strToDate(String.valueOf(value).replace("T00:00:00+0800", " 00:00:00"), "yyyy-MM-dd HH:mm:ss");
                        }
                        if (value instanceof String) {
                            clazz.getMethod(key, String.class).invoke(saveModel, value);
                        } else if (value instanceof Integer) {
                            clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                        } else if (value instanceof Double) {
                            clazz.getMethod(key, Double.class).invoke(saveModel, value);
                        } else if (value instanceof Date) {
                            clazz.getMethod(key, Date.class).invoke(saveModel, value);
                        } else if (value instanceof List) {
                            clazz.getMethod(key, List.class).invoke(saveModel, value);
                        }
                    } catch (Exception e) {
                        logger.warn(e.getMessage());
                    }
                }
                saveModels.add(saveModel);
            });
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return saveModels;
    }
    public Long excuteForLong(String sql, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
            Long Longvalue = ((Double) temp.getLines().get(0).get(0)).longValue();
            return Longvalue;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return 0L;
    }
    /**
     * 首字母大写
     *
     * @param str
     * @return
     */
    private String UpFirstStr(String str) {
        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase());
    }
    public Object excuteOneObject(String sql, Class clazz, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getHits(), true);
            List<String> heads = temp.getHeaders();
            Object saveModel = clazz.newInstance();
            try {
                for (int i = 0; i < temp.getLines().get(0).size(); i++) {
                    String key = null;
                    Object value = temp.getLines().get(0).get(i);
                    if (heads.get(i).contains("createTime")) {
                        key = "setCreateTime";
                        value = DateUtil.strToDate(String.valueOf(value).replace("+0800", "").replace("T", " "), "yyyy-MM-dd HH:mm:ss");
                    } else {
                        key = "set" + UpFirstStr(heads.get(i));
                    }
                    if (value instanceof String) {
                        clazz.getMethod(key, String.class).invoke(saveModel, value);
                    } else if (value instanceof Integer) {
                        clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                    } else if (value instanceof Double) {
                        clazz.getMethod(key, Double.class).invoke(saveModel, value);
                    } else if (value instanceof Date) {
                        clazz.getMethod(key, Date.class).invoke(saveModel, value);
                    }
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
            }
            return saveModel;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
    /**
     * 0级指标查询列表
     * 获取所有指标的增量、到达量
     * 备注:原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,sum(result1) result1, sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 一级指标查询列表
     * 获取一级指标的增量、到达量
     * 备注:原接口的二级指标对应现在的一级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度
     * @param interval  1日 2周 3月
     * @param lowLevel  下个等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotEmpty(slaveKey1) && !commonParams.equals(slaveKey1)) {
            sql.append(" and slaveKey1='" + slaveKey1 + "'  ");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 二级指标查询列表
     * 获取二级指标的增量、到达量
     * 备注:原接口的三级指标对应现在的二级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度code
     * @param slaveKey2 二级维度code
     * @param interval  1日 2周 3月
     * @param lowLevel  下一等级
     * @return
     */
    public List findDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            sql.append(" and slaveKey1='" + slaveKey1 + "'");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            sql.append(" and slaveKey2='" + slaveKey2 + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     *
     * @param quotaDate
     */
    private String changeDate(String quotaDate) {
        try {
            quotaDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(quotaDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return quotaDate;
    }
    public String changeTime(String time) {
        try {
            if (time.length() == 10) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(time));
            } else if (time.length() == 19) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }
    //获取最新更新的时间
    public String getQuotaTime() {
        String date = redisTemplate.opsForValue().get("quota:date");
//        date = date.replace(" ","T")+"+0800";
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     * 获取一个指标下所有一级维度按维度分组的数据
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public List findDateAllQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 0级维度
     * 查询某一天某一个0级维度的指标
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 0级维度
     * 查询某个时间区间某一个0级维度的指标
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null);
        if (list.size() > 0) {
            return (SaveModel) list.get(0);
        } else {
            return null;
        }
    }
    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timelevel
     * @return
     * @throws Exception
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }
    /**
     * 2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return list;
    }
    /**
     * 根据2级维度的2级指标去聚合 没有一级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 根据2级维度的1级指标去聚合 没有2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 2级维度
     * 查询某个时间区间某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 2级维度
     * 查询某一天某个1级维度下所有2级维度的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, commonParams, null, null);
        return list;
    }
    /**
     * 折线图
     * 0级维度
     * 查询某个0级维度的指标折线图
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     * @throws Exception
     */
    public List<SaveModel> findLineChartDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, interval, null);
        return list;
    }
    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, interval, null);
        return list;
    }
    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, interval, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, interval, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第二个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey2) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, slaveKey2);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, slaveKey1, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, null);
        return list;
    }
    /**
     * 列表
     * 0级维度
     * 查询某一天某个0级维度的指标列表
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 0级维度
     * 查询某个区间某个0级维度的指标列表
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队.
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个区间某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, null, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 2级维度
     * 查询某个区间某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }
    /**
     * 将参数转换成需要的SaveModel里的标识
     *
     * @param level 等级  4 市  3区  2社区 1团队
     *              转换后的level  等级  2 市  3区  4社区 5团队
     * @return
     * @author zhangdan
     * @time 2017-10-18
     */
    public int changeLevel(int level) {
        int resultLevel = 0;
        if (level == 1) {
            //团队转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.teamLevel);
        } else if (level == 2) {
            //社区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.OrgLevel);
        } else if (level == 3) {
            //区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.townLevel);
        } else if (level == 4) {
            //市转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.cityLevel);
        }
        if (resultLevel == 0) {
            resultLevel = level;
        }
        return resultLevel;
    }
    public List<Map<String, Object>> excuteDataModel(String sql) {
        List<Map<String, Object>> returnModels = new ArrayList<>();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//            if (parser.getLexer().token() != Token.EOF) {
//                throw new ParserException("illegal sql expr : " + sql);
//            }
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                Client client = elasticFactory.getTransportClient();
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                try {
                    Map<String, Object> oneMap = new HashMap<String, Object>();
                    for (int i = 0; i < one.size(); i++) {
                        String key = null;
                        Object value = one.get(i);
                        key = heads.get(i);
                        oneMap.put(key, value);
                    }
                    returnModels.add(oneMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnModels;
    }
}

+ 32 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ZysoftServiceController.java

@ -266,6 +266,38 @@ public class ZysoftServiceController {
			}
		}
	}
	
	@RequestMapping(value = "getstatictag",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("查询服务记录指标")
	/**
	 *  查询服务记录指标
	 *  data={
	        "type":1,//1咨询量,2健康教育量,3代预约量,4长处方续方两,5体征测量总数,6体征异常量
		    "idcard":"350681111111111111",//身份证
	        "data_type":"1",//1血糖,2血压
		    "start_time":"2017-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
		    "end_time":"2018-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
	     
		 }
	 */
	public Result getStaticTag(@ApiParam(name="data",value="json串",defaultValue = "{}")
	                               @RequestParam(value = "data",required = true) String data){
		try {
			com.alibaba.fastjson.JSONObject result = zysoftService.getStaticTag(data);
			return Result.success("请求成功!",result);
		} catch (Exception ex) {
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	
	}
}

+ 316 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/vo/SaveModel.java

@ -0,0 +1,316 @@
package com.yihu.wlyy.service.entity.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.searchbox.annotations.JestId;
import org.springframework.data.annotation.CreatedDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/1.
 */
public class SaveModel {
    private final static String teamKey = "team";
    private final static String OrgKey = "hospital";
    private final static String townKey = "town";
    private final static String cityKey = "city";
    public final static String interval_day="1";
    public final static String interval_week="2";
    public final static String interval_month="3";
    public final static String teamLevel = "5";
    public final static String OrgLevel = "4";
    public final static String townLevel = "3";
    public final static String cityLevel = "2";
    private static final Map<String, String> fieldsSithch = new HashMap<>();
    public final static String timeLevel_ZL="1";//增量
    public final static String timeLevel_DDL="2";//到达量
    @JestId
    private String id;
    private String saasId;//saasId
    private String quotaCode;//指标code
    private Date quotaDate;//统计时间
    private String city;//城市代码 350200
    private String cityName;//
    private String town;//区代码 350206
    private String townName;//
    private String hospital;//机构code
    private String hospitalName;//
    private String team;//团队的code
    private String teamName;//
    private String slaveKey1;//从维度  1级维度
    private String slaveKey1Name;
    private String slaveKey2;//从维度  2级维度
    private String slaveKey2Name;
    private String slaveKey3;//从维度  3级维度
    private String slaveKey3Name;
    private String slaveKey4;//从维度  4级维度
    private String slaveKey4Name;
    private Double result1 = 0.0;//统计结果(如:评分总合)
    private Double result2 = 0.0;//统计结果
    private String areaLevel;// 1 省 2 市 3 区县 4 机构 5团队
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
    @CreatedDate
    private Date createTime;//创建时间
    private String timeLevel;// 1日 2年
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd ")
    public Date getQuotaDate() {
        return quotaDate;
    }
    public void setQuotaDate(Date quotaDate) {
        this.quotaDate = quotaDate;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    //@Field(type = FieldType.String, analyzer="ngram_analyzer")//使用ngram进行单字分词
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getTeam() {
        return team;
    }
    public void setTeam(String team) {
        this.team = team;
    }
    public String getSlaveKey1() {
        return slaveKey1;
    }
    public void setSlaveKey1(String slaveKey1) {
        this.slaveKey1 = slaveKey1;
    }
    public String getSlaveKey2() {
        return slaveKey2;
    }
    public void setSlaveKey2(String slaveKey2) {
        this.slaveKey2 = slaveKey2;
    }
    public String getSlaveKey3() {
        return slaveKey3;
    }
    public void setSlaveKey3(String slaveKey3) {
        this.slaveKey3 = slaveKey3;
    }
    public String getSlaveKey4() {
        return slaveKey4;
    }
    public void setSlaveKey4(String slaveKey4) {
        this.slaveKey4 = slaveKey4;
    }
    public Double getResult1() {
        return result1;
    }
    public void setResult1(Double result1) {
        this.result1 = result1;
    }
    public Double getResult2() {
        return result2;
    }
    public void setResult2(Double result2) {
        this.result2 = result2;
    }
    public String getSlaveKey1Name() {
        return slaveKey1Name;
    }
    public void setSlaveKey1Name(String slaveKey1Name) {
        this.slaveKey1Name = slaveKey1Name;
    }
    public String getSlaveKey2Name() {
        return slaveKey2Name;
    }
    public void setSlaveKey2Name(String slaveKey2Name) {
        this.slaveKey2Name = slaveKey2Name;
    }
    public String getSlaveKey3Name() {
        return slaveKey3Name;
    }
    public void setSlaveKey3Name(String slaveKey3Name) {
        this.slaveKey3Name = slaveKey3Name;
    }
    public String getSlaveKey4Name() {
        return slaveKey4Name;
    }
    public void setSlaveKey4Name(String slaveKey4Name) {
        this.slaveKey4Name = slaveKey4Name;
    }
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getTeamName() {
        return teamName;
    }
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    public String getAreaLevel() {
        return areaLevel;
    }
    public void setAreaLevel(String areaLevel) {
        this.areaLevel = areaLevel;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
    /**
     * 根据级别得到key
     * 1 省 2 市 3 区县 4 机构 5团队
     *
     * @param level
     * @return
     */
    public static String getAreaLevelKey(String level) {
        switch (level) {
            case teamLevel: {
                return teamKey;
            }
            case OrgLevel: {
                return OrgKey;
            }
            case townLevel: {
                return townKey;
            }
            case cityLevel: {
                return cityKey;
            }
            default: {
                return teamKey;
            }
        }
    }
}

+ 168 - 3
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java

@ -1,22 +1,33 @@
package com.yihu.wlyy.service.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.service.common.http.HttpApiException;
import com.yihu.wlyy.service.common.model.Result;
import com.yihu.wlyy.service.common.util.ElasticFactory;
import com.yihu.wlyy.service.common.util.ElasticsearchUtil;
import com.yihu.wlyy.service.common.util.StringUtil;
import com.yihu.wlyy.service.dao.PatientDao;
import com.yihu.wlyy.service.entity.DoctorMapping;
import com.yihu.wlyy.service.entity.Message;
import com.yihu.wlyy.service.entity.Patient;
import com.yihu.wlyy.service.entity.prescription.Prescription;
import com.yihu.wlyy.service.entity.prescription.PrescriptionExpressage;
import com.yihu.wlyy.service.entity.prescription.PrescriptionLog;
import com.zoe.phip.ssp.sdk.ApiException;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * Created by hzp on 2016/9/9.
@ -24,6 +35,11 @@ import java.util.Map;
 */
@Service
public class ZysoftService {
    
    @Value("${es.type.HealthEduArticlePatient}")
    private String esType;
    @Value("${es.index.HealthEduArticlePatient}")
    private String esIndex;
    @Autowired
    private LogService logService;
@ -34,6 +50,17 @@ public class ZysoftService {
    private Boolean openCrypto;
    //默认重复次数
    private int retryTimes = 3;
    
    @Autowired
    PatientDao patientDao;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    /**
     * 基卫二次封装Get接口
@ -875,4 +902,142 @@ public class ZysoftService {
        
        return response;
	}
    
    /**
     *  查询服务记录指标
     *  data={
         "type":1,//1咨询量,2健康教育量,3代预约量,4长处方续方两,5体征测量总数,6体征异常量
         "idcard":"350681111111111111",//身份证
         "start_time":"2017-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
         "end_time":"2018-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
     }
     */
    public com.alibaba.fastjson.JSONObject getStaticTag(String data) {
        String error = null;
        String status = "1";
        String errMsg = null;
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        
        try{
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(data);
            String type = json.getString("type");//
            String idcard = json.getString("idcard");//身份证
            String start_time = json.getString("start_time");//开始时间
            String end_time = json.getString("end_time");//结束时间
            String data_type = json.getString("data_type");//1血糖,2血压
            
            String name = "";//居民姓名
            String datatype = "";//1血糖,2血压
            Long total = new Long("0");
            String sql = "";//待执行的SQL语句
            Map<String, Object> totalCountMap = new HashMap<>();
            
            
            if(StringUtils.isBlank(idcard)){
                throw new Exception("身份证号不允许为空");
            }
            
            if(StringUtils.isBlank(start_time) || StringUtils.isBlank(end_time)){
                throw new Exception("开始时间和结束时间不能为空");
            }
            
            Patient patient = patientDao.findByIdcard(idcard);
            System.out.println(patient.getCode());
            if(StringUtils.isNotBlank(patient.getCode())){
                name = patient.getName();
                result.put("name",name);
                result.put("idcard",patient.getIdcard());
            }else{
                throw new Exception(idcard+"-该身份证号找不到居民");
            }
            
            //1咨询量
            if("1".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_consult where patient ='"+patient.getCode()+"' and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
                
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
    
            //2健康教育量
            if("2".equals(type)){
                //查询总数sql
                String countSql = "SELECT COUNT(*) AS count FROM " + esType + "  where patientCode= '" + patient.getCode() + "' and userType = 1";
                Long totalES = elasticsearchUtil.excuteForLong(countSql,esIndex, esType);
                JSONArray re = new JSONArray();
                result.put("total",totalES);
                result.put("type","0");
            
            }
    
            //3代预约量
            if("3".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_patient_reservation where patient='"+patient.getCode()+"' and doctor is not null and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
    
            //4长处方续方量
            if("4".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_prescription where patient ='"+patient.getCode()+"' and create_time BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
            
            //5体征测量总数
            if("5".equals(type)){
                sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type='"+data_type+"'and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type",data_type);
            }
            
            //6体征异常量
            if("6".equals(type)){
                sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type='"+data_type+"' and status = 1 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type",data_type);
            }
        
        }catch (JSONException ex){
            ex.printStackTrace();
            error = ex.getMessage();
            errMsg = ex.getMessage();
            status = "0";
        }catch (Exception e){
            e.printStackTrace();
            error = e.getMessage();
            status = "0";
        }
    
        return result;
    }
}

+ 1 - 1
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/guahao/GuahaoService.java

@ -1562,7 +1562,7 @@ public class GuahaoService {
        Map<String,String> params = new HashMap<>();
        params.put("act", "findWzymBymykh");
        params.put("accId", "q9Bt3TE00KaigEW5EJVIMA==");
        params.put("_token", "525870222");
        params.put("_token", "118328844");
        params.put("etmykh", "0052182708");
        return ylzImmGetSecond(apiString,"计免预约-获取计划免疫接种记录",params);
    }

+ 68 - 0
patient-co-service/wlyy_service/src/main/resources/application.yml

@ -84,6 +84,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://192.168.131.113:8081
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: devtest
@ -112,6 +129,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://192.168.131.113:8081
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: test
@ -139,6 +173,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://172.19.103.88:9092/wlyy
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: production
@ -166,3 +217,20 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://www.xmtyw.cn/wlyy
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    Statistics: wlyy_quota_prod
    FollowUp: wlyy_followup
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    Statistics: wlyy_quota_prod
    FollowUpContent: wlyy_followup_content
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://59.61.92.90:9065,http://59.61.92.90:9067
  tHost: 59.61.92.90:9066,59.61.92.90:9068
  clusterName: jkzl

+ 6 - 11
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/BaseService.java

@ -1,21 +1,16 @@
package com.yihu.wlyy.service;
import java.security.KeyPair;
import java.util.Iterator;
import java.util.UUID;
import com.yihu.wlyy.entity.security.AccessToken;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.util.HttpUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import com.yihu.wlyy.entity.security.RSA;
import com.yihu.wlyy.repository.security.RSADao;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.util.CommonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.KeyPair;
import java.util.Iterator;
import java.util.UUID;
@Service
public class BaseService {

+ 17 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/DeviceDetailService.java

@ -18,6 +18,7 @@ import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@ -44,6 +45,8 @@ public class DeviceDetailService extends BaseService {
	private DoctorDao doctorDao;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
@ -53,6 +56,7 @@ public class DeviceDetailService extends BaseService {
	 * @param isFirst
	 * @throws Exception
	 */
	@Transactional
	public void updateAfterBinding(PatientDevice patientDevice, Date grantTime,boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		List<SignFamily> signFamilyList = signFamilyDao.findSSandJTByIdcard(patientDevice.getUserIdcard());
@ -84,11 +88,15 @@ public class DeviceDetailService extends BaseService {
		}
		if (isFirst){
			deviceDetailDao.updateAfterBindingFirst(String.valueOf(adminTeam),hospital,isFirstBind,grantTime,patientDevice.getDeviceSn());
			String updateFirstSql ="update device.wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.grant_time = ?,dd.is_binding=1 where dd.device_code=?";
			jdbcTemplate.update(updateFirstSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,grantTime,patientDevice.getDeviceSn()});
			//deviceDetailDao.updateAfterBindingFirst(String.valueOf(adminTeam),hospital,isFirstBind,grantTime,patientDevice.getDeviceSn());
		}else {
			List<PatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(patientDevice.getDeviceSn());
			int patientDeviceSize = patientDeviceList.size();
			deviceDetailDao.updateAfterBinding(String.valueOf(adminTeam),hospital,isFirstBind,patientDevice.getDeviceSn(),patientDeviceSize);
			String updateSql ="update device.wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.is_binding=? where dd.device_code=?";
			jdbcTemplate.update(updateSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,patientDeviceSize,patientDevice.getDeviceSn()});
			//deviceDetailDao.updateAfterBinding(String.valueOf(adminTeam),hospital,isFirstBind,patientDevice.getDeviceSn(),patientDeviceSize);
		}
	}
@ -147,14 +155,18 @@ public class DeviceDetailService extends BaseService {
	 */
	public void unBindUpdateIsBinding(String deviceSn)throws Exception{
		List<PatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(deviceSn);
		String sql = "update device.wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
		if (patientDeviceList.size()==0){
			deviceDetailDao.updateUnbindAll(0,deviceSn);
			jdbcTemplate.update(sql,new Object[]{0,deviceSn});
			//deviceDetailDao.updateUnbindAll(0,deviceSn);
		}
		if (patientDeviceList.size()==1){
			deviceDetailDao.updateUnbindAll(1,deviceSn);
			jdbcTemplate.update(sql,new Object[]{1,deviceSn});
			//deviceDetailDao.updateUnbindAll(1,deviceSn);
		}
		if (patientDeviceList.size()>1){
			deviceDetailDao.updateUnbindAll(2,deviceSn);
			jdbcTemplate.update(sql,new Object[]{2,deviceSn});
			//deviceDetailDao.updateUnbindAll(2,deviceSn);
		}
	}
}

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

@ -40,6 +40,7 @@ public class PatientDeviceLogService extends BaseService {
     * @param operateCode
     * @throws Exception
     */
    @Transactional
    public void savePatientDeviceLog(PatientDevice patientDevice,String deviceSn,int role,int operateCode)throws Exception{
       if (patientDevice==null){
           patientDevice = patientDeviceDao.findByDeviceSn(deviceSn).get(0);

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

@ -155,7 +155,7 @@ public class PatientDeviceService extends BaseService {
            }
        }
        /*DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
        //if(deviceDetail != null){
        if(deviceDetail != null){
            flag = true;
        }*/
        return flag;

+ 550 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/CreditLogService.java

@ -0,0 +1,550 @@
package com.yihu.wlyy.service.app.health.bank;/**
 * Created by nature of king on 2018/5/7.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author wangzhinan
 * @create 2018-05-07 9:24
 * @desc wlyy health bank service
 **/
@Service
@Transactional
public class CreditLogService {
    private Logger logger = LoggerFactory.getLogger(CreditLogService.class);
    private static String URL = "health:blank:url";
    //    private String baseUrl = "http://192.168.131.24:8088/svr-iot/";
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    /**
     * 获取url
     *
     * @return
     */
    public  String getBaseUrl(){
        String url = redisTemplate.opsForValue().get(URL);
        String url1 = systemDictDao.findByDictNameAndCode("HEALTH_BANK_URL","HEALTH_BANK_URL");
        if (url != null && url1.equalsIgnoreCase(url)){
            return url;
        }else {
            redisTemplate.opsForValue().set(URL,url1);
            return url1;
        }
    }
    /**
     * 调用第三方积分排名接口
     *
     * @param doctorId
     * @param page
     * @param name
     * @param size
     * @return
     */
    public JSONObject selectByRanking(String doctorId,String name, Integer page, Integer size){
        String sql = null;
        if (name == null || name == ""){
            sql  = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"')";
        } else if (name != null) {
            sql  = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"') AND name = '"+name+"'";
        }
        List<SignFamily> signFamilyList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamily.class));
        List<String>  patientIds = new ArrayList<>();
        if (signFamilyList != null && signFamilyList.size() != 0){
            for (SignFamily signFamily:signFamilyList){
                patientIds.add(signFamily.getPatient());
            }
        }
        JSONObject object = new JSONObject();
        object.put("filter",patientIds.toArray());
        object.put("page",page);
        object.put("size",size);
        String url = getBaseUrl() + "selectByRanking";
        String response = null;
        JSONArray data =null;
        JSONObject object1 = null;
        try {
            response = httpClientUtil.iotPostBody(url,object.toString());
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject object2 = array.getJSONObject(i);
                String patientId = object2.getString("patientId");
                Patient patient = patientDao.findByCode(patientId);
                object2.put("patient",patient);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 调用添加积分接口
     *
     * @param object
     * @return
     */
    public JSONObject insert(JSONObject object) throws Exception {
        String response = null;
        String patientId = object.getString("patientId");
        Patient patient = patientDao.findByCode(patientId);
        if (patient == null){
            throw new Exception("该居民不存在");
        }
        object.put("name",patient.getName());
        object.put("idCard",patient.getIdcard());
        object.put("openId",patient.getOpenid());
        object.put("unionId",patient.getUnionid());
        String url =getBaseUrl() + "createCreditsDetail";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 按条件查询积分
     *
     * @param object
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByCondition(JSONObject object,Integer page,Integer size){
        String response = null;
        String url =getBaseUrl() + "findCreditsLogInfo";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 查询账户积分详情
     *
     * @param object
     * @return
     */
    public JSONObject selectAccount(JSONObject object) throws Exception {
        String patientId = object.getString("patientId");
        Patient patient = patientDao.findByCode(patientId);
        if (patient == null){
            throw new Exception("该居民不存在");
        }
        object.put("name",patient.getName());
        String response = null;
        String url =getBaseUrl() + "selectAccount";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 查询任务完成情况
     *
     * @param object
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByTask(JSONObject object,Integer page,Integer size){
        JSONObject object1 = new JSONObject();
        String response = null;
        String url =getBaseUrl() + "findTask";
        Map<String,String> params = new HashMap<>();
        params.put("task",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        String patientId = object.getString("patientId");
        try {
            response = httpClientUtil.httpPost(url,params);
            Map<String,Object> taskInfo = patientDeviceService.getPatientDeviceTaskInfo(patientId);
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            JSONArray array1 = new JSONArray();
            for (int i =0 ;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String taskCode = jsonObject.getString("taskCode");
                if (taskCode.equalsIgnoreCase("BIND")){
                    jsonObject.put("deviceCount",taskInfo.get("deviceCount"));
                }else if (taskCode.equalsIgnoreCase("MEASURE")){
                    jsonObject.put("resultHealty",taskInfo.get("resultHealty"));
                }
                array1.add(jsonObject);
            }
            object1.put("detailModelList",array1);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 查询银行账户信息
     *
     * @param object 账户对象
     * @param page 页码
     * @param size 每页大小
     * @return
     */
    public JSONObject selectByAccount(JSONObject object,Integer page,Integer size){
        String signSql = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND patient = '"+object.getString("patientId") +"'";
        List<SignFamily> signFamilyList1 = jdbcTemplate.query(signSql,new BeanPropertyRowMapper(SignFamily.class));
        String sql = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +signFamilyList1.get(0).getDoctor() + "' OR doctor_health = '" + signFamilyList1.get(0).getDoctor() +"')";
        List<SignFamily> signFamilyList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamily.class));
        List<String>  patientIds = new ArrayList<>();
        if (signFamilyList != null && signFamilyList.size() != 0){
            for (SignFamily signFamily:signFamilyList){
                patientIds.add(signFamily.getPatient());
            }
        }
        String response = null;
        String url =getBaseUrl() + "findAccount";
        object.put("patientIds",patientIds.toArray());
        Map<String,String> params = new HashMap<>();
        params.put("account",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        JSONObject object1 = null;
        try {
            response = httpClientUtil.httpPost(url,params);
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject object2 = array.getJSONObject(i);
                String patientId = object2.getString("patientId");
                Patient patient = patientDao.findByCode(patientId);
                object2.put("patient",patient);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 获取活动所有排名
     *
     * @param activityId 活动对象
     * @param page 页码
     * @param size
     * @return
     */
    public JSONObject selectByActivityRanking1(String activityId,Integer page,Integer size){
        String response = null;
        String url =getBaseUrl() + "selectByActivityRanking1";
        Map<String,String> params = new HashMap<>();
        params.put("activityId",activityId);
        params.put("page",page.toString());
        params.put("size",size.toString());
        JSONObject object1 = null;
        try {
            response = httpClientUtil.httpPost(url,params);
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject object2 = array.getJSONObject(i);
                String patientId = object2.getString("patientId");
                Patient patient = patientDao.findByCode(patientId);
                object2.put("patient",patient);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 查询参与活动
     *
     * @param object
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByPatient(JSONObject object,Integer page,Integer size){
        Patient patient = new Patient();
        if (object.getString("openId") != null){
            patient = patientDao.findByOpenid(object.getString("openId"));
        }else if (object.getString("patientId") != null){
            patient = patientDao.findByCode(object.getString("patientId"));
        }
        object.put("openId",patient.getOpenid());
        object.put("unionId",patient.getUnionid());
        object.put("patientIdcard",patient.getIdcard());
        String response = null;
        String url =getBaseUrl() + "selectByPatient";
        Map<String,String> params = new HashMap<>();
        params.put("activity",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 根据活动查找积分
     *
     * @param patientId 居民id
     *
     * @param activityId 活动id
     * @param page 页码
     *
     * @param size  分页大小
     * @return
     */
    public JSONObject selectByActivity(String patientId,String activityId,Integer page,Integer size){
        String response = null;
        String url =getBaseUrl() + "selectByActivity";
        Map<String,String> params = new HashMap<>();
        params.put("patientId",patientId);
        params.put("activityId",activityId);
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 按照活动排名
     *
     * @param activityId 活动id
     * @param doctorId 医生id
     * @param name 居民名称
     * @param page 页码
     * @param size 分页大小
     * @return
     */
    public JSONObject selectByActivityRanking(String activityId,String doctorId,String name, Integer page, Integer size){
        String sql = null;
        if (name == null || name ==""){
            sql  = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"')";
        } else if (name != null) {
            sql  = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"') AND name = '"+name+"'";
        }
        List<SignFamily> signFamilyList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamily.class));
        List<String>  patientOpenIds = new ArrayList<>();
        if (signFamilyList != null && signFamilyList.size() != 0){
            for (SignFamily signFamily:signFamilyList){
                patientOpenIds.add(signFamily.getOpenid());
            }
        }
        JSONObject object = new JSONObject();
        object.put("filter",patientOpenIds.toArray());
        object.put("activityId",activityId);
        object.put("page",page);
        object.put("size",size);
        String url = getBaseUrl() + "selectByActivityRanking";
        String response = null;
        JSONArray data =null;
        JSONObject object1 = null;
        try {
            response = httpClientUtil.iotPostBody(url,object.toString());
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            for (int i = 0;i<array.size();i++){
                JSONObject object2 = array.getJSONObject(i);
                String patientId = object2.getString("patientId");
                Patient patient = patientDao.findByCode(patientId);
                object2.put("patient",patient);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 根据条件获取信息
     *
     * @param object 对象
     * @param page 页码
     * @param size 分页大小
     * @return
     */
    public JSONObject selectAccountByCondition(JSONObject object,Integer page,Integer size){
        String doctorId = object.getString("doctorId");
        String sql = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"')";
        List<SignFamily> signFamilyList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamily.class));
        List<String>  patientIds = new ArrayList<>();
        if (signFamilyList != null && signFamilyList.size() != 0){
            for (SignFamily signFamily:signFamilyList){
                patientIds.add(signFamily.getPatient());
            }
        }
        JSONObject object1 = new JSONObject();
        JSONArray array = object.getJSONArray("deviceTypes");
        object1.put("patientIds",patientIds.toArray());
        object1.put("bindStatus",object.getInteger("bindStatus"));
        object1.put("deviceTypes",array);
        object1.put("page",page);
        object1.put("size",size);
        String response = null;
        String url =getBaseUrl() + "findAccounByCondition";
        JSONObject object2 = null;
        try {
            response = httpClientUtil.iotPostBody(url,object1.toString());
            object2 = JSONObject.parseObject(response);
            JSONArray array1 = object2.getJSONArray("detailModelList");
            for (int i = 0;i<array1.size();i++){
                JSONObject object3 = array1.getJSONObject(i);
                String patientId = object3.getString("patientId");
                Patient patient = patientDao.findByCode(patientId);
                object3.put("patient",patient);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object2;
    }
    /**
     * 医生添加积分
     *
     * @param object {patientIds:[],ruleId:"",description:""}
     * @return
     */
    public JSONObject doctorAddIntegrate(JSONObject object){
        String response = null;
        String url =getBaseUrl() + "doctorAddIntegrate";
        JSONArray array = object.getJSONArray("patientIds");
        JSONArray jsonArray  = new JSONArray();
        for (int i =0 ;i<array.size();i++){
            Patient patient = patientDao.findByCode(array.getString(i));
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(patient);
            jsonArray.add(jsonObject);
        }
        JSONObject object1 = new JSONObject();
        object1.put("patient",jsonArray);
        object1.put("ruleId",object.getString("ruleId"));
        object1.put("description",object.getString("description"));
        JSONObject object2 = null;
        try {
            response = httpClientUtil.iotPostBody(url,object1.toString());
            object2 = JSONObject.parseObject(response);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object2;
    }
    /**
     * 步数获取积分
     *
     * @param object
     * @return
     * @throws Exception
     */
    public JSONObject stepAddIntegrate(JSONObject object) throws Exception {
        String response = null;
        String patientId = object.getString("patientId");
        Patient patient = patientDao.findByCode(patientId);
        if (patient == null){
            throw new Exception("该居民不存在");
        }
        object.put("name",patient.getName());
        object.put("idCard",patient.getIdcard());
        object.put("openId",patient.getOpenid());
        object.put("unionId",patient.getUnionid());
        String url =getBaseUrl() + "addStepIntegrate";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
}

+ 78 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/TaskRuleService.java

@ -0,0 +1,78 @@
package com.yihu.wlyy.service.app.health.bank;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by wangzhinan on 2018/6/14.
 */
@Service
@Transactional
public class TaskRuleService {
    private Logger logger = LoggerFactory.getLogger(TaskRuleService.class);
    private static String URL = "health:blank:url";
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 获取url
     *
     * @return
     */
    public  String getBaseUrl(){
        String url = redisTemplate.opsForValue().get(URL);
        String url1 = systemDictDao.findByDictNameAndCode("HEALTH_BANK_URL","HEALTH_BANK_URL");
        if (url != null && url1.equalsIgnoreCase(url)){
            return url;
        }else {
            redisTemplate.opsForValue().set(URL,url1);
            return url1;
        }
    }
    /**
     * 查找规则
     *
     * @param object 规则对象
     *
     * @param page 页码
     *
     * @param size 分页大小
     *
     * @return
     */
    public JSONObject selectTaskRule(JSONObject object, Integer page, Integer size){
        String response = null;
        String url =getBaseUrl() + "findTaskRule";
        Map<String,String> params = new HashMap<>();
        params.put("taskRule",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
}

+ 167 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/TaskService.java

@ -0,0 +1,167 @@
package com.yihu.wlyy.service.app.health.bank;/**
 * Created by nature of king on 2018/6/11.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author wangzhinan
 * @create 2018-06-11 8:54
 * @desc 健康银行活动
 **/
@Service
@Transactional
public class TaskService {
    private Logger logger = LoggerFactory.getLogger(TaskService.class);
    private static String URL = "health:blank:url";
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDao patientDao;
    /**
     * 获取url
     *
     * @return
     */
    public  String getBaseUrl(){
        String url = redisTemplate.opsForValue().get(URL);
        String url1 = systemDictDao.findByDictNameAndCode("HEALTH_BANK_URL","HEALTH_BANK_URL");
        if (url != null && url1.equalsIgnoreCase(url)){
            return url;
        }else {
            redisTemplate.opsForValue().set(URL,url1);
            return url1;
        }
    }
    /**
     * 查看活动列表
     *
     * @param object
     * @return
     */
    public JSONObject selectActivity(JSONObject object,Integer page,Integer size){
        String response = null;
        String url =getBaseUrl() + "findActivity";
        Map<String,String> params = new HashMap<>();
        params.put("activity",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 查询任务获取积分
     *
     * @param taskCodeIds taskCode集合
     * @param patientId 居民id
     * @param page 页码
     * @param size 分页大小
     * @return
     */
    public JSONObject selectTask(JSONArray taskCodeIds,String patientId, Integer page, Integer size){
        String response = null;
        String url =getBaseUrl() + "selectByCode";
        JSONObject object = new JSONObject();
        object.put("taskCode",taskCodeIds.toJSONString());
        object.put("patientId",patientId);
        object.put("page",page.toString());
        object.put("size",size.toString());
        try {
            response = httpClientUtil.iotPostBody(url,object.toString());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 参加任务
     *
     * @param object 参加任务JSON
     * @return
     */
    public JSONObject attendTask(JSONObject object){
        String response = null;
        Patient patient = patientDao.findByCode(object.getString("patientId"));
        String unionId = "1";
        patient.setUnionid(unionId);
        patientDao.save(patient);
        object.put("unionId",unionId);
        object.put("patientIdcard",patient.getIdcard());
        String url =getBaseUrl() + "attendTask";
        Map<String,String> params = new HashMap<>();
        params.put("taskPatientDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 根据openId获取用户数据
     *
     * @param openId 微信id
     *
     * @param page 页码
     *
     * @param size 分页大小
     *
     * @return
     */
    public JSONObject selectByOpenId(String openId, Integer page,Integer size){
        String sql = "select * from wlyy_patient where openid = '"+ openId +"' LIMIT "+(page-1)*size+","+size;
        List<Patient> patientList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(Patient.class));
        String sqlcount = "select * from wlyy_patient where openid = '"+ openId +"'";
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlcount);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        JSONObject object = new JSONObject();
        object.put("patientList",patientList);
        object.put("total",count);
        object.put("page",page);
        object.put("size",size);
        return object;
    }
}

+ 84 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/message/MessageService.java

@ -15,6 +15,7 @@ import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.IdCardUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@ -704,4 +705,87 @@ public class MessageService extends BaseService {
        List<Map<String,Object>> messagelist = jdbcTemplate.queryForList(sql,new Object[]{start,pageSize});
        return messagelist;
    }
    public JSONObject getPatientInfo(String patientCode){
        JSONObject jsonObject = new JSONObject();
        Patient patient = patientDao.findByCode(patientCode);
        // 患者code
        jsonObject.put("code",patient.getCode());
        // 社保号
        jsonObject.put("ssc",patient.getSsc());
        // openid
        jsonObject.put("openid",StringUtils.isNotEmpty(patient.getOpenid()) ? patient.getOpenid() : "");
        // 性别
        jsonObject.put("sex",patient.getSex());
        // 患者手机号码
        jsonObject.put("mobile",patient.getMobile());
        // 头像
        jsonObject.put("photo",patient.getPhoto());
        // 身份证号码
        jsonObject.put("idcard",patient.getIdcard());
        // 患者名字
        jsonObject.put("name",patient.getName());
        // 患者年纪
        jsonObject.put("age",IdCardUtil.getAgeForIdcard(patient.getIdcard()));
        String sql = "SELECT sf.* FROM wlyy_sign_family sf LEFT JOIN wlyy_patient p ON sf.patient = p.`code` WHERE sf.`status`>0 and sf.patient='"+patientCode+"'";
        List<SignFamily> signFamilys = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(SignFamily.class));
        if (signFamilys!=null && signFamilys.size()>0){
            SignFamily signFamily = signFamilys.get(0);
            // 签约类型
            jsonObject.put("signType",signFamily.getType()== null ? "" : signFamily.getType());
            // 签约时间
            jsonObject.put("qyrq",signFamily.getApplyDate() != null ? DateUtil.dateToStr((signFamily.getApplyDate()),DateUtil.YYYY_MM_DD) : "");
            //紧急联系人
            jsonObject.put("emerMobile",signFamily.getEmerMobile() == null ? "" : signFamily.getEmerMobile());
            if (String.valueOf(signFamily.getType()).equals("2")) {
                // 缴费情况
                jsonObject.put("expensesStatus", signFamily.getExpensesStatus() != null ? String.valueOf(signFamily.getExpensesStatus()) : "0");
                // 缴费时间
                jsonObject.put("expensesTime", signFamily.getExpensesTime() != null ? DateUtil.dateToStr((signFamily.getExpensesTime()), DateUtil.YYYY_MM_DD_HH_MM) : "");
                // 缴费类型
                jsonObject.put("expensesType", signFamily.getExpensesType() != null ? String.valueOf(signFamily.getExpensesType()) : "");
                if (StringUtils.isEmpty(String.valueOf(signFamily.getExpensesStatus())) || String.valueOf(signFamily.getExpensesStatus()).equals("0")) {
                    boolean epTime = false;
                    try {
                        epTime = redisTemplate.opsForSet().isMember("expenses:remind:set", patient.getCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!epTime) {
                        jsonObject.put("expensesRemindStatus", 0);
                    } else {
                        jsonObject.put("expensesRemindStatus", 1);
                    }
                }
            } else {
                // 缴费情况
                jsonObject.put("expensesStatus", "1");
            }
            boolean epTime = false;
            try {
                epTime = redisTemplate.opsForSet().isMember("wechat:focus:remind:set", patient.getCode());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!epTime) {
                jsonObject.put("wechatFocusRemind", 0);
            } else {
                jsonObject.put("wechatFocusRemind", 1);
            }
        }
        String devcieSql = "select group_concat(category_code) deviceType FROM wlyy_patient_device where user = '"+patientCode+"'";
        Map<String,Object> deviceMap = null;
        try {
            deviceMap = jdbcTemplate.queryForMap(devcieSql);
        }catch (Exception e){
            System.out.println(e.getMessage());
            deviceMap.put("devicrType",0);
        }
        /// 设备状态:0未绑定,1血糖仪,2血压仪,3血糖仪+血压仪
        jsonObject.put("deviceType",String.valueOf(deviceMap.get("deviceType")));
        return  jsonObject;
    }
}

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

@ -5,6 +5,7 @@ import com.yihu.wlyy.entity.address.Street;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
@ -27,6 +28,7 @@ import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.statistics.ServiceStatisticsService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
@ -132,6 +134,8 @@ public class SignWebService extends BaseService {
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    /**
     * 厦门市
     */
@ -636,6 +640,7 @@ public class SignWebService extends BaseService {
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataType","sign");//家庭医生签约服务包
            jsonObject.put("hospitalName", renew.getHospitalName());
            jsonObject.put("hospital", renew.getHospital());
            jsonObject.put("code", renewCode);
@ -707,6 +712,7 @@ public class SignWebService extends BaseService {
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataType","sign");//家庭医生签约服务包
            jsonObject.put("hospitalName", signFamily.getHospitalName());
            jsonObject.put("hospital", signFamily.getHospital());
            jsonObject.put("code", signCode);
@ -767,6 +773,36 @@ public class SignWebService extends BaseService {
            jsonObject.put("statusName", statusName);
            jsonArray.add(jsonObject);
        }
        
        List<PatientDevice> patientDevices = patientDeviceDao.findByPatient(patient);
        for (PatientDevice patientDevice: patientDevices) {
            JSONObject jsonObject = new JSONObject();
            SignFamily signFamily = signFamilyDao.findByPatient(patient);//签约社区
            if(StringUtils.isNotBlank(patientDevice.getDoctor())){
                Doctor deviceDoctor = doctorService.findDoctorByCode(patientDevice.getDoctor());
                jsonObject.put("doctor",patientDevice.getDoctor());//操作医生代码
                jsonObject.put("doctorName",deviceDoctor.getName());//操作医生姓名
            }
            jsonObject.put("dataType","device");//家庭医生签约服务包
            jsonObject.put("deviceId",patientDevice.getDeviceId());//设备ID
            jsonObject.put("deviceSn",patientDevice.getDeviceSn());//设备SN码
            jsonObject.put("sim",patientDevice.getSim());//设备SIM卡号
            jsonObject.put("deviceName",patientDevice.getDeviceName());//设备名称
            jsonObject.put("user",patientDevice.getUser());//居民CODE
            jsonObject.put("categoryCode",patientDevice.getCategoryCode());//1血糖仪,2.血压计
            jsonObject.put("userType",patientDevice.getUserType());//-1代表单用户
            jsonObject.put("userIdcard",patientDevice.getUserIdcard());//用户身份证号
            jsonObject.put("agent",patientDevice.getAgent());//代绑人代码(家人)
            jsonObject.put("agentName",patientDevice.getAgentName());//代绑人姓名
            jsonObject.put("createTime",patientDevice.getCzrq());//操作时间
            jsonObject.put("agreementPhoto",patientDevice.getAgreementPhoto());//上传的协议图片地址
            jsonObject.put("hospitalName",signFamily.getHospitalName());//社区名称
            jsonArray.add(jsonObject);
        }
        
        
        
        Collections.sort(jsonArray, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {

+ 0 - 330
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/health/bank/CreditLogService.java

@ -1,330 +0,0 @@
package com.yihu.wlyy.service.third.health.bank;/**
 * Created by nature of king on 2018/5/7.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author wangzhinan
 * @create 2018-05-07 9:24
 * @desc wlyy health bank service
 **/
@Service
@Transactional
public class CreditLogService {
    private Logger logger = LoggerFactory.getLogger(CreditLogService.class);
    @Value("${healthBank.url}")
    private String baseUrl;
    //    private String baseUrl = "http://192.168.131.24:8088/svr-iot/";
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PatientDeviceService patientDeviceService;
    
    @Autowired
    private PatientService patientService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private PatientDao patientDao;
    /**
     * 调用第三方积分排名接口
     *
     * @param doctorId
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByRanking(String doctorId, Integer page, Integer size){
        String sql = "SELECT * FROM wlyy_sign_family WHERE status = 1 AND ( doctor = '" +doctorId + "' OR doctor_health = '" + doctorId +"')";
        List<SignFamily> signFamilyList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamily.class));
        List<String>  patientIds = new ArrayList<>();
        if (signFamilyList != null && signFamilyList.size() != 0){
            for (SignFamily signFamily:signFamilyList){
                patientIds.add(signFamily.getPatient());
            }
        }
        JSONObject object = new JSONObject();
        object.put("filter",patientIds.toArray());
        object.put("page",page);
        object.put("size",size);
        String url = baseUrl + "selectByRanking";
        String response = null;
        JSONArray data =null;
        JSONObject object1 = null;
        try {
            response = httpClientUtil.iotPostBody(url,object.toString());
            object1 = JSONObject.parseObject(response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 调用添加积分接口
     *
     * @param object
     * @return
     */
    public JSONObject insert(JSONObject object) throws Exception {
    
        JSONObject result = new JSONObject();
        
        init();
        String response = null;
        String integrate = getIntegrate("health:blank:integrate:"+object.getString("flag"));
        String patientId = object.getString("patientId");
        Patient patient = patientDao.findByCode(patientId);
        if (patient == null){
            throw new Exception("该居民不存在");
        }
        object.put("name",patient.getName());
        object.put("integrate",integrate);
        String url =baseUrl + "createCreditsDetail";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    
        result = JSONObject.parseObject(response);
    
    
        String status = result.getString("status");
    
        logger.info("健康银行居民新增积分:"+result.toString());
        if ("200".equals(status)){
            List<Map<String,Object>> list = (List<Map<String,Object>>)result.get("detailModelList");
            if (list!=null && list.size()>0){
                //积分
                String integrateresult = String.valueOf(list.get(0).get("integrate"));
                String patientid = String.valueOf(list.get(0).get("patientId"));
                String total = String.valueOf(list.get(0).get("total"));
            
            
                try {
                    //@TODO 获取积分调用发送微信模板接口
                    Patient people = patientDao.findByCode(patientid);
                    String openId = people.getOpenid();
                    String name = people.getName();
                
                    org.json.JSONObject sendJson = new org.json.JSONObject();
                    String first = "";
                    String remark = "";
                    String urlresult = "";
                
                    WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_healthbank_credit","jfdztz");
                    first = templateConfig.getFirst();
                    remark = templateConfig.getRemark();
//                    String keyword1 = templateConfig.getKeyword1();
                
                    sendJson.put("keyword1", integrateresult);
                    sendJson.put("keyword2", DateUtil.getStringDate());
                    sendJson.put("keyword3", total);
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
                    urlresult = templateConfig.getUrl();
                    urlresult = urlresult.replace("key1",(integrate==null?"":integrate));
                    sendJson.put("url", urlresult);//带参数的模板跳转链接
                    System.out.println(sendJson.toString());
                    pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 23, openId, name, sendJson);
//	                    //发送代理人
//	                    jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openId);
//	                    if (jsonArray != null && jsonArray.length() > 0) {
//		                    for (int i = 0; i < jsonArray.length(); i++) {
//			                    org.json.JSONObject j = jsonArray.getJSONObject(i);
//			                    Patient member = (Patient) j.get("member");
//			                    int start = url.indexOf("&toUser=");
//			                    int end = url.indexOf("&", start + 1);
//			                    String touser = url.substring(start, end);
//			                    url = url.replace(touser, "&toUser=" + member.getCode());
//			                    //name患者姓名
//			                    sendJson.put("first", weiXinOpenIdUtils.getTitleMes(people, (int) j.get("relation"), name) + first);
//			                    sendJson.put("url", url);
//			                    pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 19, member.getOpenid(), name, sendJson);
//		                    }
//	                    }
                }catch (Exception e){
                    logger.info("健康银行居民新增积分,微信模板消息发送失败:"+e.getMessage());
//	                        e.printStackTrace();
                }
            
            }
        }
        return result;
    }
    /**
     * 按条件查询积分
     *
     * @param object
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByCondition(JSONObject object,Integer page,Integer size){
        String response = null;
        String url =baseUrl + "findCreditsLogInfo";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 查询账户积分详情
     *
     * @param object
     * @return
     */
    public JSONObject selectAccount(JSONObject object) throws Exception {
        String patientId = object.getString("patientId");
        Patient patient = patientDao.findByCode(patientId);
        if (patient == null){
            throw new Exception("该居民不存在");
        }
        object.put("name",patient.getName());
        String response = null;
        String url =baseUrl + "selectAccount";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 查询任务完成情况
     *
     * @param object
     * @param page
     * @param size
     * @return
     */
    public JSONObject selectByTask(JSONObject object,Integer page,Integer size){
        JSONObject object1 = new JSONObject();
        String response = null;
        String url =baseUrl + "findTask";
        Map<String,String> params = new HashMap<>();
        params.put("task",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        String patientId = object.getString("patientId");
        try {
            response = httpClientUtil.httpPost(url,params);
            Map<String,Object> taskInfo = patientDeviceService.getPatientDeviceTaskInfo(patientId);
            object1 = JSONObject.parseObject(response);
            JSONArray array = object1.getJSONArray("detailModelList");
            JSONArray array1 = new JSONArray();
            for (int i =0 ;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String taskCode = jsonObject.getString("taskCode");
                if (taskCode.equalsIgnoreCase("BIND")){
                    jsonObject.put("deviceCount",taskInfo.get("deviceCount"));
                }else if (taskCode.equalsIgnoreCase("MEASURE")){
                    jsonObject.put("resultHealty",taskInfo.get("resultHealty"));
                }
                array1.add(jsonObject);
            }
            object1.put("detailModelList",array1);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object1;
    }
    /**
     * 查询银行账户信息
     *
     * @param object 账户对象
     * @param page 页码
     * @param size 每页大小
     * @return
     */
    public JSONObject selectByAccount(JSONObject object,Integer page,Integer size){
        String response = null;
        String url =baseUrl + "findAccount";
        Map<String,String> params = new HashMap<>();
        params.put("account",object.toJSONString());
        params.put("page",page.toString());
        params.put("size",size.toString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    public void init(){
        redisTemplate.opsForValue().set("health:blank:integrate:BIND","1");
        redisTemplate.opsForValue().set("health:blank:integrate:MEASURE","1");
    }
    public String getIntegrate(String key){
        return redisTemplate.opsForValue().get(key);
    }
}

+ 4 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/HttpClientUtil.java

@ -4,6 +4,7 @@ import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
@ -121,8 +122,11 @@ public class HttpClientUtil {
     */
    public  String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(10000).build();//设置请求和传输超时时间
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if (params != null && params.size() > 0) {
                List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {

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

@ -276,4 +276,9 @@ public class DataHandlingController extends BaseController {
            return write(0, "清洗数据失败!");
        }
    }
    //将wlyy_patient_device的数据清洗至wlyy_patietn_devcie_log
    //将devcie库中wlyy_device新增的字段补充完整
}

+ 17 - 9
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java

@ -3,7 +3,6 @@ package com.yihu.wlyy.web.doctor.device;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.device.DeviceWxMessage;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.device.vo.DeviceWxMessageDTO;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
@ -11,15 +10,15 @@ import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.device.DeviceDetailService;
import com.yihu.wlyy.service.app.device.DeviceWxMessageService;
import com.yihu.wlyy.service.app.device.PatientDeviceLogService;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.third.health.bank.CreditLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
@ -35,11 +34,13 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
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 javax.jms.JMSException;
import javax.jms.Message;
@ -84,6 +85,8 @@ public class DoctorDeviceController extends BaseController {
	private CommonUtil commonUtil;
	@Autowired
	private DeviceWxMessageService deviceWxMessageService;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JmsTemplate jmsTemplate;
@ -142,7 +145,7 @@ public class DoctorDeviceController extends BaseController {
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			Patient patient = patientDao.findByCode(device.getUser());
			//调用增加积分接口  海沧区的居民才能添加积分
			if (flag && "350205".equals(patient.getTown())){
			if (flag){
				String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"BIND\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
				JSONObject jsonObject = JSONObject.parseObject(creditDetail);
				JSONObject response = creditLogService.insert(jsonObject);
@ -236,8 +239,8 @@ public class DoctorDeviceController extends BaseController {
				if(StringUtils.isNotBlank(pd.getDoctor())&&StringUtils.equals(pd.getDoctor(), getUID())){
					List<com.alibaba.fastjson.JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
					//全部解绑后去判断就更新设备表中是否绑定字段
					deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
					patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),1,2);
					deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
					return write(200,"","data",objects);
				}
				else if(StringUtils.isNotBlank(pd.getDoctor())&&!StringUtils.equals(pd.getDoctor(), getUID())){
@ -249,8 +252,8 @@ public class DoctorDeviceController extends BaseController {
					}
					if(bo){//同行政团队
						List<com.alibaba.fastjson.JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
						deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
						patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),1,2);
						deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
						return write(200,"","data",objects);
					}else{
						return error(-1, "只允许删除自己及自己行政团队绑定的设备!");
@ -280,10 +283,15 @@ public class DoctorDeviceController extends BaseController {
						@ApiParam(name="type",value="设备类型")
						@RequestParam(value="type",required = true) String type) {
		try{
			List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
			PatientDevice patientDevice = new PatientDevice();
			if (patientDevices!=null && patientDevices.size()>0){
				patientDevice = patientDevices.get(0);
			}
			patientDeviceService.deleteDevices(deviceSn,type,getUID());
			//全部解绑后去判断就更新设备表中是否绑定字段
			patientDeviceLogService.savePatientDeviceLog(patientDevice,deviceSn,1,2);
			deviceDetailService.unBindUpdateIsBinding(deviceSn);
			patientDeviceLogService.savePatientDeviceLog(null,deviceSn,1,2);
			return write(200,"解绑成功!");
		}catch (Exception e){
			error(e);

+ 272 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/bank/ActivityController.java

@ -0,0 +1,272 @@
package com.yihu.wlyy.web.doctor.health.bank;/**
 * Created by nature of king on 2018/6/13.
 */
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.service.app.health.bank.TaskRuleService;
import com.yihu.wlyy.service.app.health.bank.TaskService;
import com.yihu.wlyy.web.BaseController;
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;
/**
 * @authorwangzhinan
 * @create 2018-06-13 15:04
 * @desc 活动广场
 **/
@RestController
@RequestMapping(value = "/doctor/healthBank", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-健康广场")
public class ActivityController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(ActivityController.class);
    @Autowired
    private CreditLogService service;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskRuleService taskRuleService;
    /**
     * 查询活动排名
     * @param doctorId 医生id
     *
     * @param activityId 活动id
     * @param page 页码
     *
     * @param size 分页大小
     * @return
     */
    @RequestMapping(value = "/findActivityRanking",method = RequestMethod.POST)
    @ApiOperation("查询活动排名")
    public String getById(@ApiParam(name = "doctorId",value = "医生Id")
                          @RequestParam(name = "doctorId")String doctorId,
                          @ApiParam(name = "activityId",value = "活动id")
                          @RequestParam(name = "activityId") String activityId,
                          @ApiParam(name = "name",value = "居民名称")
                          @RequestParam(name = "name",required = false)String name,
                          @ApiParam(name = "page", value = "第几页,从1开始")
                          @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                          @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                          @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"查询成功","data",service.selectByActivityRanking(activityId,doctorId,name,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 查询积分排名
     *
     * @param doctorId
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/findCreditRanking",method = RequestMethod.POST)
    @ApiOperation("查询积分排名")
    public String getById(@ApiParam(name = "doctorId",value = "医生Id")
                          @RequestParam(name = "doctorId")String doctorId,
                          @ApiParam(name = "name",value = "居民名称")
                          @RequestParam(name = "name",required = false)String name,
                          @ApiParam(name = "page", value = "第几页,从1开始")
                          @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                          @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                          @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"查询成功","data",service.selectByRanking(doctorId,name,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 活动广场
     *
     * @param task
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/selectTask",method = RequestMethod.POST)
    @ApiOperation("活动列表")
    public String selectByCondition(@ApiParam(name = "task",value = "任务JSON")
                                    @RequestParam(name = "task") String task,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(task);
            object.put("openId",getOpenid());
            return write(200,"查询成功","data",taskService.selectActivity(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 查看任务规则
     *
     * @param taskRule 任务规则对象
     * @param page 页码
     * @param size 分页大小
     * @return
     */
    @RequestMapping(value = "/selectTaskRule",method = RequestMethod.POST)
    @ApiOperation("查看任务规则")
    public String selectByTaskRule(@ApiParam(name = "taskRule",value = "规则JSON")
                                    @RequestParam(name = "taskRule") String taskRule,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(taskRule);
            return write(200,"查询成功","data",taskRuleService.selectTaskRule(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 根据条件查找用户信息
     *
     * @param condition {"doctorId":,"bindStatus":"","deviceTypes":[]}
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/selectAccountByCondition",method = RequestMethod.POST)
    @ApiOperation("根据条件查找用户信息")
    public String selectAccountByCondition(@ApiParam(name = "condition",value = "条件JSON")
                                   @RequestParam(name = "condition") String condition,
                                   @ApiParam(name = "page", value = "第几页,从1开始")
                                   @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                   @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                   @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(condition);
            return write(200,"查询成功","data",service.selectAccountByCondition(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 医生添加积分
     *
     * @param object {"patientIds":["915cc456-5b1d-11e6-8344-fa163e8aee56"],"ruleId":"4028037363fc550f0163fc633a1a0007","description":"321321"}
     * @return
     */
    @RequestMapping(value = "/doctorAddInteger",method = RequestMethod.POST)
    @ApiOperation("医生添加积分")
    public String doctorAddInteger(@ApiParam(name = "object",value = "object")
                                   @RequestParam(name = "object") String object){
        try {
            JSONObject object1 = JSONObject.parseObject(object);
            return write(200,"查询成功","data",service.doctorAddIntegrate(object1));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * find credits log details
     *
     * @param creditsLogDo
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/selectDetails",method = RequestMethod.POST)
    @ApiOperation("积分详情")
    public String selectByCondition1(@ApiParam(name = "creditsLogDo",value = "积分JSON")
                                    @RequestParam(name = "creditsLogDo") String creditsLogDo,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(creditsLogDo);
            return write(200,"查询成功","data",service.selectByCondition(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     *  根据条件查看银行账户信息
     *
     * @param account 银行账户
     * @param page 页码
     * @param size 每页大小
     * @return
     */
    @RequestMapping(value = "/findAccount",method = RequestMethod.POST)
    @ApiOperation("银行账户信息")
    public String selectByAccount(@ApiParam(name = "account",value = "任务JSON")
                                  @RequestParam(name = "account") String account,
                                  @ApiParam(name = "page", value = "第几页,从1开始")
                                  @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(account);
            return write(200,"查询成功","data",service.selectByAccount(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 医生端查询居民参与活动
     *
     * @param patientId 居民id
     * @param page 页码
     * @param size 分页大小
     * @return
     */
    @RequestMapping(value = "/selectByPatient",method = RequestMethod.POST)
    @ApiOperation("参与活动列表")
    public String selectByPatient(@ApiParam(name = "patientId",value = "居民id")
                                      @RequestParam(value = "patientId") String patientId,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                  @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = new JSONObject();
            object.put("patientId",patientId);
            return write(200,"查询成功","data",service.selectByPatient(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}

+ 26 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/message/DoctorMessageController.java

@ -266,8 +266,18 @@ public class DoctorMessageController extends BaseController {
                                                 @RequestParam(value = "pagesize", required = true) Integer pagesize) throws Exception {
        try {
            List<Map<String, String>> list = messageService.getHealthIndexMessageByPatient(getUID(), patient, type, page, pagesize);
            return write(200, "获取超标指标消息成功", "data", list);
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", 200);
            map.put("msg", "获取超标指标消息成功");
            map.put("data", list);
            String tzCode ="";
            for (Map<String, String> one:list){
                tzCode+=","+one.get("tzCode");
            }
            map.put("tzCode",StringUtils.isNotEmpty(tzCode)?tzCode.substring(1):"");
            return mapper.writeValueAsString(map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return invalidUserException(ex, -1, "查询失败");
@ -476,4 +486,18 @@ public class DoctorMessageController extends BaseController {
    }
    @RequestMapping(value = "getDevcieMessageDetailToInfo",method = RequestMethod.POST)
    @ApiOperation("点击具体的设备解绑的消息跳转至具名详情页")
    @ResponseBody
    public String getDeviceMessageDetailToInfo(@ApiParam(name = "msgid",value = "消息主键id")@RequestParam(value = "msgid",required = true)long msgid,
                                               @ApiParam(name = "patientCode",value = "居民code")@RequestParam(value = "patientCode",required = true)String patientCode){
        try {
            messageService.readHealth(msgid);
            return write(200,"获取成功!","data",messageService.getPatientInfo(patientCode));
        }catch (Exception e){
            error(e);
            return error( -1, "操作失败!");
        }
    }
}

+ 4 - 4
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java

@ -1,7 +1,6 @@
package com.yihu.wlyy.web.patient.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.device.DeviceDetail;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.device.PatientHealthTime;
import com.yihu.wlyy.entity.message.Message;
@ -13,12 +12,12 @@ import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.app.device.DeviceDetailService;
import com.yihu.wlyy.service.app.device.PatientDeviceLogService;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.device.DeviceDetailService;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.third.health.bank.CreditLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
@ -235,7 +234,7 @@ public class PatientDeviceController extends BaseController {
                patientDeviceService.saveDevice(device);
                patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),2,1);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息,
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            if (flag && "350205".equals(patient.getTown())){
                String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"BIND\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
@ -409,6 +408,7 @@ public class PatientDeviceController extends BaseController {
                message.setType(301);//解绑设备消息
                message.setReadonly(1);//是否只读消息
                message.setSex(1);
                message.setRelationCode(patient.getCode());
                message.setOver("1");//未处理
                message.setData("");
                message.setDel("1");

+ 90 - 46
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/CreditsLogController.java

@ -1,20 +1,11 @@
/**
 * Created by nature of king on 2018/5/7.
 */
package com.yihu.wlyy.web.third.health.bank;
import com.alibaba.fastjson.JSONArray;
package com.yihu.wlyy.web.patient.health.bank;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.wechat.WechatTemplateConfig;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.third.health.bank.CreditLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.web.doctor.device.DoctorDeviceController;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -22,10 +13,10 @@ 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.*;
import java.util.List;
import java.util.Map;
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;
/**
 * @author wangzhinan
@ -33,7 +24,7 @@ import java.util.Map;
 * @desc credit log controller
 **/
@RestController
@RequestMapping(value = "/healthBank",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "/patient/healthBank",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "积分处理机制")
public class CreditsLogController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(CreditsLogController.class);
@ -50,7 +41,7 @@ public class CreditsLogController extends BaseController {
     * @param size
     * @return
     */
    @RequestMapping(value = "/findCreditRanking",method = RequestMethod.POST)
    /*@RequestMapping(value = "/findCreditRanking",method = RequestMethod.POST)
    @ApiOperation("查询积分排名")
    public String getById(@ApiParam(name = "doctorId",value = "医生Id")
                              @RequestParam(name = "doctorId")String doctorId,
@ -64,7 +55,7 @@ public class CreditsLogController extends BaseController {
            error(e);
            return error(-1,e.getMessage());
        }
    }
    }*/
    /**
@ -75,7 +66,7 @@ public class CreditsLogController extends BaseController {
     */
    @RequestMapping(value = "/insertCredits",method = RequestMethod.POST)
    @ApiOperation("添加积分")
    public String insert(@ApiParam(name = "creditsDetail",value = "居民id集合")
    public String insert(@ApiParam(name = "creditsDetail",value = "居民对象JSON")
                          @RequestParam(name = "creditsDetail") String creditsDetail){
        try {
            JSONObject object = JSONObject.parseObject(creditsDetail);
@ -87,6 +78,8 @@ public class CreditsLogController extends BaseController {
        }
    }
    /**
     * find credits log details
     *
@ -131,32 +124,6 @@ public class CreditsLogController extends BaseController {
        }
    }
    /**
     * 查询任务完成情况
     *
     * @param task
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/selectTasks",method = RequestMethod.POST)
    @ApiOperation("任务完成情况")
    public String selectByTask(@ApiParam(name = "task",value = "任务JSON")
                                    @RequestParam(name = "task") String task,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(task);
            return write(200,"查询成功","data",service.selectByTask(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     *  根据条件查看银行账户信息
     *
@ -182,4 +149,81 @@ public class CreditsLogController extends BaseController {
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "/selectByActivityRanking1",method = RequestMethod.POST)
    @ApiOperation("获取活动所有排名")
    public String selectByActivityRanking1(@ApiParam(name = "activityId",value = "活动id")
                                  @RequestParam(name = "activityId") String activityId,
                                  @ApiParam(name = "page", value = "第几页,从1开始")
                                  @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"查询成功","data",service.selectByActivityRanking1(activityId,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     *  参与活动列表
     *
     * @param page 页码
     *
     * @param size 分页大小
     *
     * @return
     */
    @RequestMapping(value = "/selectByPatient",method = RequestMethod.POST)
    @ApiOperation("参与活动列表")
    public String selectByPatient(@ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = new JSONObject();
            object.put("openId",getOpenid());
            return write(200,"查询成功","data",service.selectByPatient(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 根据活动查积分
     *
     * @param activityId 活动id
     *
     * @param patientId 居民id
     *
     * @param page 页码
     *
     * @param size 分页大小
     *
     * @return
     */
    @RequestMapping(value = "/selectByActivity",method = RequestMethod.POST)
    @ApiOperation("根据活动查积分")
    public String selectByActivity(@ApiParam(name = "activityId",value = "活动id")
                                  @RequestParam(name = "activityId") String activityId,
                                   @ApiParam(name = "patientId",value = "居民id")
                                   @RequestParam(name = "patientId") String patientId,
                                  @ApiParam(name = "page", value = "第几页,从1开始")
                                  @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"查询成功","data",service.selectByActivity(patientId,activityId,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}

+ 131 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/bank/TaskController.java

@ -0,0 +1,131 @@
package com.yihu.wlyy.web.patient.health.bank;/**
 * Created by nature of king on 2018/6/11.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.service.app.health.bank.TaskService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * @author wangzhinan
 * @create 2018-06-11 10:49
 * @desc 健康任务
 **/
@RestController
@RequestMapping(value = "/patient/healthBank",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "健康活动")
public class TaskController extends BaseController{
    @Autowired
    private TaskService service;
    /**
     * 活动广场
     *
     * @param task
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/selectTask",method = RequestMethod.POST)
    @ApiOperation("活动列表")
    public String selectByCondition(@ApiParam(name = "task",value = "任务JSON")
                                    @RequestParam(name = "task") String task,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(task);
            object.put("openId",getOpenid());
            return write(200,"查询成功","data",service.selectActivity(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 查看任务列表
     *
     * @param task (taskCode:[],patientId:")
     *
     * @param page 页码
     *
     * @param size 分页大小
     *
     * @return
     */
    @RequestMapping(value = "/selectTasks",method = RequestMethod.POST)
    @ApiOperation("任务列表")
    public String selectByTask(@ApiParam(name = "task", value = "任务JSON")
                                    @RequestParam(name ="task" )String task,
                                    @ApiParam(name = "page", value = "第几页,从1开始")
                                    @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                    @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                    @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(task);
            JSONArray array = object.getJSONArray("taskCode");
            String patientId = object.getString("patientId");
            return write(200,"查询成功","data",service.selectTask(array,patientId,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 参加任务
     *
     * @param taskPatientDetail
     * @return
     */
    @RequestMapping(value = "/attendTask",method = RequestMethod.POST)
    @ApiOperation("参加任务")
    public String attendTask(@ApiParam(name = "taskPatientDetail",value = "参与活动JSON")
                             @RequestParam(name = "taskPatientDetail")String taskPatientDetail){
        try {
            JSONObject object = JSONObject.parseObject(taskPatientDetail);
            object.put("patientOpenid",getOpenid());
            return write(200,"报名成功","data",service.attendTask(object));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 获取用户信息
     *
     * @param page 页码
     *
     * @param size  分页大小
     *
     * @return
     */
    @RequestMapping(value = "/selectByOpenId",method = RequestMethod.POST)
    @ApiOperation("获取用户信息")
    public String selectByOpenId( @ApiParam(name = "page", value = "第几页,从1开始")
                                      @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                      @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"添加成功","data",service.selectByOpenId(getOpenid(),page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}

+ 103 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/AccountController.java

@ -0,0 +1,103 @@
/**
 * Created by nature of king on 2018/5/7.
 */
package com.yihu.wlyy.web.third.health.bank;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.web.BaseController;
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;
/**
 * @author wangzhinan
 * @create 2018-05-07 8:50
 * @desc credit log controller
 **/
@RestController
@RequestMapping(value = "/healthBank",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "小程序")
public class AccountController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AccountController.class);
    @Autowired
    private CreditLogService service;
    /**
     *  根据条件查看银行账户信息
     *
     * @param account 银行账户
     * @param page 页码
     * @param size 每页大小
     * @return
     */
    @RequestMapping(value = "/findAccount",method = RequestMethod.POST)
    @ApiOperation("银行账户信息")
    public String selectByAccount(@ApiParam(name = "account",value = "任务JSON")
                               @RequestParam(name = "account") String account,
                               @ApiParam(name = "page", value = "第几页,从1开始")
                               @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                               @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                               @RequestParam(value = "size", required = false)Integer size){
        try {
            JSONObject object = JSONObject.parseObject(account);
            return write(200,"查询成功","data",service.selectByAccount(object,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "/selectByActivityRanking1",method = RequestMethod.POST)
    @ApiOperation("获取活动所有排名")
    public String selectByActivityRanking1(@ApiParam(name = "activityId",value = "活动id")
                                  @RequestParam(name = "activityId") String activityId,
                                  @ApiParam(name = "page", value = "第几页,从1开始")
                                  @RequestParam(value = "page", defaultValue = "1",required = false)Integer page,
                                  @ApiParam(name = "size",defaultValue = "10",value = ",每页分页大小")
                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            return write(200,"查询成功","data",service.selectByActivityRanking1(activityId,page,size));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    /**
     * 步数获取积分
     *
     * @param creditsDetail {"patientId":"","transactionId":"","stepNumber":""}
     * @return
     */
    @RequestMapping(value = "/stepAddIntegrate",method = RequestMethod.POST)
    @ApiOperation("步数获取积分")
    public String stepAddIntegrate(@ApiParam(name = "creditsDetail",value = "对象JSON")
                                   @RequestParam(name = "creditsDetail") String creditsDetail){
        try {
            JSONObject object = JSONObject.parseObject(creditsDetail);
            JSONObject result = service.stepAddIntegrate(object);
            return write(200,"获取成功","data",result);
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}