Bladeren bron

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

Conflicts:
	svr/svr-wlyy-health-bank/src/main/java/com/yihu/jw/service/CreditsDetailService.java
yeshijie 4 jaren geleden
bovenliggende
commit
066e2b67cc
100 gewijzigde bestanden met toevoegingen van 20846 en 6 verwijderingen
  1. 11 2
      business/base-service/src/main/java/com/yihu/jw/area/dao/BaseTownDao.java
  2. 9 0
      business/base-service/src/main/java/com/yihu/jw/hospital/family/dao/WlyyPatientFamilyMemberDao.java
  3. 1 1
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultDao.java
  4. 2 0
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultTeamDao.java
  5. 20 1
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  6. 82 0
      common/common-entity/src/main/java/com/yihu/jw/entity/BaseIdentityEntity.java
  7. 35 0
      common/common-entity/src/main/java/com/yihu/jw/entity/IdentityEntityListener.java
  8. 57 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/DoctorRegistration.java
  9. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/DoctorRegistrationTemp.java
  10. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCancelLogDO.java
  11. 141 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCommentDO.java
  12. 154 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCommentDoctorDO.java
  13. 516 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorConclusionDO.java
  14. 116 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorDO.java
  15. 64 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorFeeDictDO.java
  16. 79 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorStatusDO.java
  17. 182 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorFeeDetailDO.java
  18. 57 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorOrderItemDO.java
  19. 89 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPatientConfirmLogDO.java
  20. 413 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDO.java
  21. 101 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDetailDO.java
  22. 327 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDrugDO.java
  23. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorProcessLogDO.java
  24. 231 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceApplicationDo.java
  25. 65 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceConfigureDo.java
  26. 1184 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java
  27. 98 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceVoucherDo.java
  28. 102 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorTransRecordDO.java
  29. 106 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyFeldsherCADO.java
  30. 23 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/ResponseContant.java
  31. 1 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/PageEnvelop.java
  32. 54 2
      common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java
  33. 20 0
      common/common-util/src/main/java/com/yihu/jw/util/entity/EntityUtils.java
  34. 34 0
      common/common-util/src/main/java/com/yihu/jw/util/entity/ServiceException.java
  35. 169 0
      svr/svr-door-serivce/pom.xml
  36. 1 0
      svr/svr-door-serivce/readme.MD
  37. 24 0
      svr/svr-door-serivce/src/main/java/com/yihu/SvrDoorServiceApplication.java
  38. 57 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/config/jpa/DoorServiceJpa.java
  39. 35 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/config/jpa/HibernateProperties.java
  40. 781 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/BaseController.java
  41. 170 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoctorDoorServiceAuditController.java
  42. 1298 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoorOrderController.java
  43. 783 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoorStatisticAnalyzeController.java
  44. 117 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/PatientDoorServiceApplicationController.java
  45. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorCommentController.java
  46. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorCommentDoctorController.java
  47. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorConclusionController.java
  48. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorDoctorController.java
  49. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorDoctorFeeController.java
  50. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorFeeDetailController.java
  51. 92 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorPatientConfirmLogController.java
  52. 315 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorServiceOrderController.java
  53. 16 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoctorRegistrationDao.java
  54. 27 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoctorRegistrationTempDao.java
  55. 24 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceApplicationDao.java
  56. 14 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceConfigureDao.java
  57. 29 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceOrderDao.java
  58. 28 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceVoucherDao.java
  59. 25 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCancelLogDao.java
  60. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCommentDao.java
  61. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCommentDoctorDao.java
  62. 29 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorConclusionDao.java
  63. 36 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorDao.java
  64. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorFeeDictDao.java
  65. 33 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorStatusDao.java
  66. 34 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorFeeDetailDao.java
  67. 15 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorOrderItemDao.java
  68. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPatientConfirmLogDao.java
  69. 29 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDao.java
  70. 18 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDetailDao.java
  71. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDrugDao.java
  72. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorProcessLogDao.java
  73. 50 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorServiceOrderDao.java
  74. 20 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorTransRecordDao.java
  75. 169 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoctorRegistrationTempService.java
  76. 1750 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorOrderService.java
  77. 639 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorServiceApplicationService.java
  78. 14 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorServiceVoucherService.java
  79. 163 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCancelLogService.java
  80. 163 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCommentDoctorService.java
  81. 163 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCommentService.java
  82. 163 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorConclusionService.java
  83. 163 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorFeeDictService.java
  84. 195 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorService.java
  85. 24 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorStatusService.java
  86. 184 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorFeeDetailService.java
  87. 161 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorPatientConfirmLogService.java
  88. 631 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorPrescriptionService.java
  89. 161 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorProcessLogService.java
  90. 2912 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorServiceOrderService.java
  91. 165 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorTransRecordService.java
  92. 121 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/common/HospitalService.java
  93. 130 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/common/ServerPackageService.java
  94. 146 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/consult/ConsultTeamService.java
  95. 281 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/prescription/JwDoorPrescriptionService.java
  96. 272 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/prescription/PresModeAdapter.java
  97. 1563 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/statics/DoorStatisticAnalyzeService.java
  98. 662 0
      svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/statics/StatisticsUtilService.java
  99. 268 0
      svr/svr-door-serivce/src/main/resource/application.yml
  100. 0 0
      svr/svr-door-serivce/src/main/resource/banner.txt

+ 11 - 2
business/base-service/src/main/java/com/yihu/jw/area/dao/BaseTownDao.java

@ -1,12 +1,13 @@
package com.yihu.jw.area.dao;
import com.yihu.jw.entity.base.area.BaseTownDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.jw.entity.base.area.BaseTownDO;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * 区县字典 数据库访问层
 *
@ -21,4 +22,12 @@ public interface BaseTownDao extends PagingAndSortingRepository<BaseTownDO, Inte
    @Query("select name from BaseTownDO where code =:code")
    String getNameByCode(@Param("code") String code);
    @Query("select p from BaseTownDO p where p.code = ?1")
    BaseTownDO findByCode(String code);
    @Query("select a from BaseTownDO a where a.city = ?1 order by id")
    List<BaseTownDO> findByCityCode(String city);
}

+ 9 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/family/dao/WlyyPatientFamilyMemberDao.java

@ -18,4 +18,13 @@ public interface WlyyPatientFamilyMemberDao extends PagingAndSortingRepository<W
    WlyyPatientFamilyMemberDO findbyCardNoAndPatient(String idCard,String patient);
    @Query("from WlyyPatientFamilyMemberDO t where t.patient=?1  and t.isDel =1")
    List<WlyyPatientFamilyMemberDO> findbyPatient(String patient);
    /**
     * 查询居民的某个成员
     *
     * @param patient 居民
     * @param member 成员
     * @return
     */
    WlyyPatientFamilyMemberDO findByPatientAndFamilyMember(String patient,String member);
}

+ 1 - 1
business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultDao.java

@ -29,5 +29,5 @@ public interface ConsultDao extends PagingAndSortingRepository<ConsultDo, String
//	@Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate,a.signCode  from ConsultDo a,ConsultTeamDo b where a.code = b.consult and a.patient = ?1 and a.del = '1' and a.type<>8 order by a.czrq desc")
//	Page<Object> findByPatient(String patient, Pageable pageRequest);
	ConsultDo queryByRelationCode(String relationCode);
}

+ 2 - 0
business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultTeamDao.java

@ -27,4 +27,6 @@ public interface ConsultTeamDao  extends PagingAndSortingRepository<ConsultTeamD
	@Query("select count(id) from  ConsultTeamDo a where a.type = ?1 and a.doctor = ?2 and a.czrq >=?3 and a.czrq <=?4")
	Integer  countByTime(int type, String doctor, Date startTime, Date endTime);
	ConsultTeamDo queryByRelationCode(String relationCode);
}

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

@ -294,7 +294,26 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent) {
		String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("sender_name", fromName);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("topic_id", topicId);
		params.put("agent", agent);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	/**
	 * 发送消息给IM

+ 82 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/BaseIdentityEntity.java

@ -0,0 +1,82 @@
package com.yihu.jw.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
 * Entity - 基类(自动递增)
 */
@MappedSuperclass
@EntityListeners(IdentityEntityListener.class)
public abstract class BaseIdentityEntity implements Serializable {
    private static final long serialVersionUID = -67188388306700736L;
    /** 创建日期 */
    private Date createTime;
    /**
     * 最后修改时间
     */
    private Date  lastUpdateTime;
    // 非业务主键
    protected Long id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_time", nullable = false, updatable = false)
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "last_update_time", nullable = false)
    public Date getLastUpdateTime() {
        return lastUpdateTime;
    }
    public void setLastUpdateTime(Date lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!BaseIdentityEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        BaseIdentityEntity other = (BaseIdentityEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 35 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/IdentityEntityListener.java

@ -0,0 +1,35 @@
package com.yihu.jw.entity;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.util.Date;
/**
 * Listener - 创建日期、修改日期处理
 */
public class IdentityEntityListener {
    /**
     * 保存前处理
     *
     * @param entity
     *            基类
     */
    @PrePersist
    public void prePersist(BaseIdentityEntity entity) {
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
    }
    /**
     * 更新前处理
     *
     * @param entity
     *            基类
     */
    @PreUpdate
    public void preUpdate(BaseIdentityEntity entity) {
        entity.setLastUpdateTime(new Date());
    }
}

+ 57 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/DoctorRegistration.java

@ -0,0 +1,57 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by wangpeiqiang on 2019/3/12.
 */
@Entity
@Table(name = "wlyy_doctor_registration")
public class DoctorRegistration extends IdEntity {
    //登记服务一级模板编码
    private String code;
    //模板名称
    private String modelName;
    // 创建时间
    private Date createTime;
    // 是否隐藏
    private Integer isHide;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getModelName() {
        return modelName;
    }
    public void setModelName(String modelName) {
        this.modelName = modelName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getIsHide() {
        return isHide;
    }
    public void setIsHide(Integer isHide) {
        this.isHide = isHide;
    }
}

+ 86 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/DoctorRegistrationTemp.java

@ -0,0 +1,86 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by wangpeiqiang on 2019/3/12.
 */
@Entity
@Table(name = "wlyy_doctor_registration_temp")
public class DoctorRegistrationTemp extends IdEntity {
    //二级模板标识
    private String code;
    // 医生标识
    private String doctor;
    // 一级模板标识
    private String registration;
    //模板内容
    private String content;
    // 发送次数
    private Integer sendTimes;
    // 创建时间
    private Date createTime;
    // 最后一次发送时间
    private Date lastTime;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getRegistration() {
        return registration;
    }
    public void setRegistration(String registration) {
        this.registration = registration;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getSendTimes() {
        return sendTimes;
    }
    public void setSendTimes(Integer sendTimes) {
        this.sendTimes = sendTimes;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getLastTime() {
        return lastTime;
    }
    public void setLastTime(Date lastTime) {
        this.lastTime = lastTime;
    }
}

+ 91 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCancelLogDO.java

@ -0,0 +1,91 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
* 工单取消记录实体
*
* @author Administrator on  2019年03月26日
*
*/
@Entity
@Table(name = "wlyy_door_cancel_log")
public class WlyyDoorCancelLogDO extends UuidIdentityEntity {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 居民code
	 */
	private String patient;
    /**
	 * 取消类型:1-调度员取消,2-居民取消
	 */
	private Integer cancelType;
    /**
	 * 取消理由
	 */
	private String cancelReason;
    /**
	 * 取消时间
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date time;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
	@Column(name = "cancel_type")
    public Integer getCancelType() {
        return cancelType;
    }
    public void setCancelType(Integer cancelType) {
        this.cancelType = cancelType;
    }
	@Column(name = "cancel_reason")
    public String getCancelReason() {
        return cancelReason;
    }
    public void setCancelReason(String cancelReason) {
        this.cancelReason = cancelReason;
    }
	@Column(name = "time")
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
}

+ 141 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCommentDO.java

@ -0,0 +1,141 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.IntegerIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* 服务工单评价实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_comment")
public class WlyyDoorCommentDO extends IntegerIdentityEntityWithOperator {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
     * 评价code
     */
    private String code;
    /**
	 * 专业能力
	 */
	private Integer professionalSkill;
    /**
	 * 服务态度
	 */
	private Integer serveAttitude;
    /**
	 * 服务效率
	 */
	private Integer serveEfficiency;
    /**
     * 平均分
     */
    private BigDecimal evaluateSplit;
    /**
	 * 服务描述和建议
	 */
	private String description;
    /**
	 * 是否匿名:0-否,1-是
	 */
	private Integer isAnonymous;
    /**
	 * 评价的居民id
	 */
	private String patient;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
	@Column(name = "professional_skill")
    public Integer getProfessionalSkill() {
        return professionalSkill;
    }
    public void setProfessionalSkill(Integer professionalSkill) {
        this.professionalSkill = professionalSkill;
    }
	@Column(name = "serve_attitude")
    public Integer getServeAttitude() {
        return serveAttitude;
    }
    public void setServeAttitude(Integer serveAttitude) {
        this.serveAttitude = serveAttitude;
    }
	@Column(name = "serve_efficiency")
    public Integer getServeEfficiency() {
        return serveEfficiency;
    }
    public void setServeEfficiency(Integer serveEfficiency) {
        this.serveEfficiency = serveEfficiency;
    }
	@Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
	@Column(name = "is_anonymous")
    public Integer getIsAnonymous() {
        return isAnonymous;
    }
    public void setIsAnonymous(Integer isAnonymous) {
        this.isAnonymous = isAnonymous;
    }
	@Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "evaluate_split")
    public BigDecimal getEvaluateSplit() {
        return evaluateSplit;
    }
    public void setEvaluateSplit(BigDecimal evaluateSplit) {
        this.evaluateSplit = evaluateSplit;
    }
}

+ 154 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorCommentDoctorDO.java

@ -0,0 +1,154 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.IntegerIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* 服务工单中的医生评价实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_comment_doctor")
public class WlyyDoorCommentDoctorDO extends IntegerIdentityEntityWithOperator {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
     * 评价code
     */
    private String code;
    /**
	 * 医生code
	 */
	private String doctorCode;
    /**
	 * 专业能力
	 */
	private Integer professionalSkill;
    /**
	 * 服务态度
	 */
	private Integer serveAttitude;
    /**
	 * 服务效率
	 */
	private Integer serveEfficiency;
    /**
     * 评价均分
     */
    private BigDecimal evaluateSplit;
    /**
	 * 服务描述和建议
	 */
	private String description;
    /**
	 * 是否匿名:0-否,1-是
	 */
	private Integer isAnonymous;
    /**
	 * 评价的居民id
	 */
	private String patient;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
	@Column(name = "doctor_code")
    public String getDoctorCode() {
        return doctorCode;
    }
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
	@Column(name = "professional_skill")
    public Integer getProfessionalSkill() {
        return professionalSkill;
    }
    public void setProfessionalSkill(Integer professionalSkill) {
        this.professionalSkill = professionalSkill;
    }
	@Column(name = "serve_attitude")
    public Integer getServeAttitude() {
        return serveAttitude;
    }
    public void setServeAttitude(Integer serveAttitude) {
        this.serveAttitude = serveAttitude;
    }
	@Column(name = "serve_efficiency")
    public Integer getServeEfficiency() {
        return serveEfficiency;
    }
    public void setServeEfficiency(Integer serveEfficiency) {
        this.serveEfficiency = serveEfficiency;
    }
	@Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
	@Column(name = "is_anonymous")
    public Integer getIsAnonymous() {
        return isAnonymous;
    }
    public void setIsAnonymous(Integer isAnonymous) {
        this.isAnonymous = isAnonymous;
    }
	@Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "evaluate_split")
    public BigDecimal getEvaluateSplit() {
        return evaluateSplit;
    }
    public void setEvaluateSplit(BigDecimal evaluateSplit) {
        this.evaluateSplit = evaluateSplit;
    }
}

+ 516 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorConclusionDO.java

@ -0,0 +1,516 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 工单服务小结实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_conclusion")
public class WlyyDoorConclusionDO extends UuidIdentityEntityWithOperator {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 工单服务的居民
	 */
	private String patient;
    /**
	 * 居民姓名
	 */
	private String patientName;
    /**
	 * 居民姓名
	 */
	private String idcard;
    /**
	 * 性别
	 */
	private String sex;
    /**
	 * 年龄
	 */
	private Integer age;
    /**
	 * 婚姻
	 */
	private String marriage;
    /**
	 * 职业
	 */
	private String profession;
    /**
	 * 民族
	 */
	private String nationa;
    /**
	 * 籍贯
	 */
	private String birthPlace;
    /**
     * 工作单位
     */
	private String company;
    /**
	 * 家庭地址
	 */
	private String address;
    /**
	 * 联系电话
	 */
	private String patientPhone;
    /**
	 * 供史者,病患代理人
	 */
	private String proxyPatientName;
    /**
	 * 供史者联系电话
	 */
	private String proxyPatientPhone;
    /**
	 * 供史者与患者关系:父女,夫妻,父子等
	 */
	private String proxyPatientRelation;
    /**
	 * 诊前记录
	 */
	private String beforeRecord;
    /**
	 * 现病史
	 */
	private String presenIllness;
    /**
	 * 既往史、个人史、家族史
	 */
	private String familyIllHistory;
    /**
	 * 体格记录
	 */
	private String physicalRecord;
    /**
	 * 既往辅助检查
	 */
	private String assistantExamRecord;
    /**
	 * 诊断记录
	 */
	private String diagnosticRecord;
    /**
	 * 治疗结果情况
	 */
	private String examResult;
    /**
	 * 现场照片,最多9张
	 */
	private String imgs;
    /**
     * 医生服务模板
     */
    private List<Map<String, Object>> Template;
    /**
     * 本年度服务次数
     */
    private Integer serviceCount;
    private Date serviceTime;
    private WlyyDoorConclusionDO patientLastConclusion;//居民上次服务小结
    /**
     * 现病史2
     */
    private String presenIllness2;
    /**
     * '既往史、个人史、家族史2
     */
    private String familyIllHistory2;
    /**
     * 体温
     */
    private String  temperature;
    /**
     * 呼吸频率
     */
    private String  respiratoryRate;
    /**
     * 脉搏
     */
    private String  pulse;
    /**
     * 心率
     */
    private String heartRate;
    /**
     * 收缩压
     */
    private String systolic;
    /**
     * 舒张压
     */
    private String diastolic;
    /**
     * 血糖
     */
    private String bloodSugar;
    /**
     * 血糖类型(1 空腹,2餐后,3随机)
     */
    private String bloodSugarType;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
	@Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
	@Column(name = "idcard")
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
	@Column(name = "sex")
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
	@Column(name = "age")
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
	@Column(name = "marriage")
    public String getMarriage() {
        return marriage;
    }
    public void setMarriage(String marriage) {
        this.marriage = marriage;
    }
	@Column(name = "profession")
    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }
	@Column(name = "nationa")
    public String getNationa() {
        return nationa;
    }
    public void setNationa(String nationa) {
        this.nationa = nationa;
    }
	@Column(name = "birth_place")
    public String getBirthPlace() {
        return birthPlace;
    }
    public void setBirthPlace(String birthPlace) {
        this.birthPlace = birthPlace;
    }
    @Column(name = "company")
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    @Column(name = "address")
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
	@Column(name = "patient_phone")
    public String getPatientPhone() {
        return patientPhone;
    }
    public void setPatientPhone(String patientPhone) {
        this.patientPhone = patientPhone;
    }
	@Column(name = "proxy_patient_name")
    public String getProxyPatientName() {
        return proxyPatientName;
    }
    public void setProxyPatientName(String proxyPatientName) {
        this.proxyPatientName = proxyPatientName;
    }
	@Column(name = "proxy_patient_phone")
    public String getProxyPatientPhone() {
        return proxyPatientPhone;
    }
    public void setProxyPatientPhone(String proxyPatientPhone) {
        this.proxyPatientPhone = proxyPatientPhone;
    }
	@Column(name = "proxy_patient_relation")
    public String getProxyPatientRelation() {
        return proxyPatientRelation;
    }
    public void setProxyPatientRelation(String proxyPatientRelation) {
        this.proxyPatientRelation = proxyPatientRelation;
    }
	@Column(name = "before_record")
    public String getBeforeRecord() {
        return beforeRecord;
    }
    public void setBeforeRecord(String beforeRecord) {
        this.beforeRecord = beforeRecord;
    }
	@Column(name = "presen_illness")
    public String getPresenIllness() {
        return presenIllness;
    }
    public void setPresenIllness(String presenIllness) {
        this.presenIllness = presenIllness;
    }
	@Column(name = "family_ill_history")
    public String getFamilyIllHistory() {
        return familyIllHistory;
    }
    public void setFamilyIllHistory(String familyIllHistory) {
        this.familyIllHistory = familyIllHistory;
    }
	@Column(name = "physical_record")
    public String getPhysicalRecord() {
        return physicalRecord;
    }
    public void setPhysicalRecord(String physicalRecord) {
        this.physicalRecord = physicalRecord;
    }
	@Column(name = "assistant_exam_record")
    public String getAssistantExamRecord() {
        return assistantExamRecord;
    }
    public void setAssistantExamRecord(String assistantExamRecord) {
        this.assistantExamRecord = assistantExamRecord;
    }
	@Column(name = "diagnostic_record")
    public String getDiagnosticRecord() {
        return diagnosticRecord;
    }
    public void setDiagnosticRecord(String diagnosticRecord) {
        this.diagnosticRecord = diagnosticRecord;
    }
	@Column(name = "exam_result")
    public String getExamResult() {
        return examResult;
    }
    public void setExamResult(String examResult) {
        this.examResult = examResult;
    }
	@Column(name = "imgs")
    public String getImgs() {
        return imgs;
    }
    public void setImgs(String imgs) {
        this.imgs = imgs;
    }
    @Transient
    public List<Map<String, Object>> getTemplate() {
        return Template;
    }
    public void setTemplate(List<Map<String, Object>> template) {
        Template = template;
    }
    public Integer getServiceCount() {
        return serviceCount;
    }
    public void setServiceCount(Integer serviceCount) {
        this.serviceCount = serviceCount;
    }
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
    public Date getServiceTime() {
        return serviceTime;
    }
    public void setServiceTime(Date serviceTime) {
        this.serviceTime = serviceTime;
    }
    @Transient
    public WlyyDoorConclusionDO getPatientLastConclusion() {
        return patientLastConclusion;
    }
    public void setPatientLastConclusion(WlyyDoorConclusionDO patientLastConclusion) {
        this.patientLastConclusion = patientLastConclusion;
    }
    @Column(name = "presen_illness2")
    public String getPresenIllness2() {
        return presenIllness2;
    }
    public void setPresenIllness2(String presenIllness2) {
        this.presenIllness2 = presenIllness2;
    }
    @Column(name = "family_ill_history2")
    public String getFamilyIllHistory2() {
        return familyIllHistory2;
    }
    public void setFamilyIllHistory2(String familyIllHistory2) {
        this.familyIllHistory2 = familyIllHistory2;
    }
    @Column(name = "temperature")
    public String getTemperature() {
        return temperature;
    }
    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }
    @Column(name = "respiratory_rate")
    public String getRespiratoryRate() {
        return respiratoryRate;
    }
    public void setRespiratoryRate(String respiratoryRate) {
        this.respiratoryRate = respiratoryRate;
    }
    @Column(name = "pulse")
    public String getPulse() {
        return pulse;
    }
    public void setPulse(String pulse) {
        this.pulse = pulse;
    }
    @Column(name = "heart_rate")
    public String getHeartRate() {
        return heartRate;
    }
    public void setHeartRate(String heartRate) {
        this.heartRate = heartRate;
    }
    @Column(name = "systolic")
    public String getSystolic() {
        return systolic;
    }
    public void setSystolic(String systolic) {
        this.systolic = systolic;
    }
    @Column(name = "diastolic")
    public String getDiastolic() {
        return diastolic;
    }
    public void setDiastolic(String diastolic) {
        this.diastolic = diastolic;
    }
    @Column(name = "blood_sugar")
    public String getBloodSugar() {
        return bloodSugar;
    }
    public void setBloodSugar(String bloodSugar) {
        this.bloodSugar = bloodSugar;
    }
    @Column(name = "blood_sugar_type")
    public String getBloodSugarType() {
        return bloodSugarType;
    }
    public void setBloodSugarType(String bloodSugarType) {
        this.bloodSugarType = bloodSugarType;
    }
}

+ 116 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorDO.java

@ -0,0 +1,116 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 服务工单关联的医护人员实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_doctor")
public class WlyyDoorDoctorDO extends UuidIdentityEntity {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 医生code
	 */
	private String doctor;
    /**
     * 医生名称
     */
    private String doctorName;
    /**
	 * 医生级别类型:医生,健管师,护士等
	 */
	private Integer hospitalLevel;
    /**
     * 医生职称(dm_job的code)
     */
    private String doctorJobCode;
    /**
     * 医生职称名称
     */
    private String doctorJobName;
    /**
     * 出诊费用
     */
    private Double jobFeeCost;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
	@Column(name = "hospital_level")
    public Integer getHospitalLevel() {
        return hospitalLevel;
    }
    public void setHospitalLevel(Integer hospitalLevel) {
        this.hospitalLevel = hospitalLevel;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "doctor_job_code")
    public String getDoctorJobCode() {
        return doctorJobCode;
    }
    public void setDoctorJobCode(String doctorJobCode) {
        this.doctorJobCode = doctorJobCode;
    }
    @Column(name = "doctor_job_name")
    public String getDoctorJobName() {
        return doctorJobName;
    }
    public void setDoctorJobName(String doctorJobName) {
        this.doctorJobName = doctorJobName;
    }
    @Column(name = "job_fee_cost")
    public Double getJobFeeCost() {
        return jobFeeCost;
    }
    public void setJobFeeCost(Double jobFeeCost) {
        this.jobFeeCost = jobFeeCost;
    }
}

+ 64 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorFeeDictDO.java

@ -0,0 +1,64 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* 医生出诊费用字典实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_doctor_fee_dict")
public class WlyyDoorDoctorFeeDictDO extends UuidIdentityEntity {
    /**
	 * 医生code
	 */
	private String doctor;
    /**
	 * 医生单次出诊标准费用
	 */
	private BigDecimal standardFee;
    /**
	 * 单次出诊医保补助津贴
	 */
	private BigDecimal medicalAidFee;
	@Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
	@Column(name = "standard_fee")
    public BigDecimal getStandardFee() {
        return standardFee;
    }
    public void setStandardFee(BigDecimal standardFee) {
        this.standardFee = standardFee;
    }
	@Column(name = "medical_aid_fee")
    public BigDecimal getMedicalAidFee() {
        return medicalAidFee;
    }
    public void setMedicalAidFee(BigDecimal medicalAidFee) {
        this.medicalAidFee = medicalAidFee;
    }
}

+ 79 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorDoctorStatusDO.java

@ -0,0 +1,79 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 上门服务工单实体
*
* @author Administrator on  2019年03月19日
*
*/
@Entity
@Table(name = "wlyy_door_doctor_status")
public class WlyyDoorDoctorStatusDO extends UuidIdentityEntityWithOperator {
    /**
     * 医生派单状态
     */
    public enum Status {
        waitForSend(1, "待派单"),
        waitForAccept(2, "待接单"),
        waitForServe(3, "待服务"),
        serving(4, "服务中"),
        stopped(5, "停止接单");
        private Integer type;
        private String desc;
        Status(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * wlyy_doctor中医生code
     */
    private String doctor;
    /**
     * 医生状态:1-待派单,2-待接单,3-待服务,4-服务中,5-停止接单
     */
    private Integer status;
	@Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
	@Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 182 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorFeeDetailDO.java

@ -0,0 +1,182 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
/**
* 服务工单价格明细(服务项价格,医生出诊费用)实体
*
* @author Administrator on  2019年03月19日
*
*/
@Entity
@Table(name = "wlyy_door_fee_detail")
public class WlyyDoorFeeDetailDO extends UuidIdentityEntityWithOperator {
    /**
     * 支付方式
     */
    public enum Type {
        servicePackageItem(1, "服务包的服务项费用"),
        doctor(2,"医生出诊费用");
        private Integer type;
        private String desc;
        Type(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 状态
     */
    public enum Status {
        patient(1, "居民新增(预约)"),
        doctorAdd(2,"医生新增"),
        doctorDel(3,"医生删除");
        private Integer type;
        private String desc;
        Status(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 费用类型,1-服务项费用,2-医生出诊费用
	 */
	private Integer type;
    /**
	 * 居民请求的服务项code,医生出诊费用code
	 */
	private String code;
    /**
	 * 居民请求的服务项名称,医生出诊费用名称
	 */
	private String name;
    /**
	 * 费用
	 */
	private BigDecimal fee;
    /**
	 * 折扣费用
	 */
	private BigDecimal feeDiscount;
    /**
	 * 数量
	 */
	private Integer number;
    /**
	 * 状态,1-居民新增(预约),2-医生新增,3-医生删除
	 */
	private Integer status;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
	@Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
	@Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
	@Column(name = "fee")
    public BigDecimal getFee() {
        return fee;
    }
    public void setFee(BigDecimal fee) {
        this.fee = fee;
    }
	@Column(name = "fee_discount")
    public BigDecimal getFeeDiscount() {
        return feeDiscount;
    }
    public void setFeeDiscount(BigDecimal feeDiscount) {
        this.feeDiscount = feeDiscount;
    }
	@Column(name = "number")
    public Integer getNumber() {
        return number;
    }
    public void setNumber(Integer number) {
        this.number = number;
    }
	@Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 57 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorOrderItemDO.java

@ -0,0 +1,57 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 上门服务待预约服务项
 * Created by yeshijie on 2020/11/5.
 */
@Entity
@Table(name = "wlyy_door_order_item")
public class WlyyDoorOrderItemDO extends IdEntity {
    private String doctor;
    private String patient;
    /**
     * zy_iv_clinic_dict的clinic_code
     */
    private String code;
    private Date createTime;
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 89 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPatientConfirmLogDO.java

@ -0,0 +1,89 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 服务工单居民确认操作日志记录实体
*
* @author Administrator on  2019年03月20日
*
*/
@Entity
@Table(name = "wlyy_door_patient_confirm_log")
public class WlyyDoorPatientConfirmLogDO extends UuidIdentityEntityWithOperator {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 居民
	 */
	private String patient;
    /**
	 * 居民姓名
	 */
	private String patientName;
    /**
	 * 确认操作类型:1-确认基础信息无误或变更,2-确认上门医生变更上门信息,3-同意工单转接,4-同意取消工单
	 */
	private Integer type;
    /**
	 * 操作描述
	 */
	private String description;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
	@Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
	@Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
	@Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

+ 413 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDO.java

@ -0,0 +1,413 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * 上门服务开方表
 *
 * @author humingfen on  2019年07月24日
 *
 */
@Entity
@Table(name = "wlyy_door_prescription")
public class WlyyDoorPrescriptionDO extends IntegerIdentityEntity {
    private String code ;//业务标识
//    private String number;//线上单号
    private String orderId;//工单id
    private String recipeNo;//基位处方code(开方成功后返回)
    private String visitNo;//挂号号
    private String diagnosisCode;//诊断的病种code
    private String diagnosisName;//诊断名称
    private String diagnosisSubCode;//次诊断的病种code
    private String diagnosisSubName;//次诊断名称
    private String remark;//处方备注
    private Integer status;//-1 审核不通过,30 开方中/药师审核成功,40开方完成/待支付 ,50 支付成功/待配药
    private String hospital;  //基卫-开处方的医院编码
    private String hospitalName; //开方机构名称
    private String doctorCode; //基卫-开方医生的编码
    private String doctorName;//医生名字
    private String jwDeptCode;  //基卫-开处方的科室编码
    private String jwHospital;  //基卫-开处方的医院编码
    private String jwDoctorCode; //基卫-开方医生的编码
    private BigDecimal jwRegisterFee; //基卫-诊金
    private Integer jwPayStatus;//处方结算状态,0为未结算,1为结算成功,默认为0
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date visitTime; //处方建立时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date createTime;               //处方创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date payTime;                   //支付时间
    private Integer dispensaryType;  //取药类型:1 自取 2快递配送 3健管师配送'
    private Integer isAfterDoor;//创建处方状态(1上门前开方 2上门后开方)
    private String reason;//取消处方原因
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date updateTime;               //取消处方时间
    private String patient;//居民code
    private String patientName;//居民名称
    private String ssc;//居民社保卡号
    private Long adminTeamId;//患者签约的行政团队
    private String visitDept; //挂号科室编码
    private String visitDeptName;//挂号科室名称
    private String registerType;//基卫-挂号类型编码
    private String registerTypeName;//挂号类别名称
    private String rateType;//挂号费别编码
    private String rateTypeName;//挂号费别名称
//    private Date validStartTime; //有效起始时间
//    private Date validEndTime;//有效截止时间
    private String digitalSignNo;//CA数字签名唯一流水号
    private String originalDataAbstract;//原文的MD5摘要
    private String strOriginalData; //CA原文数据
    private String caCertData;                  //ca加密信息(签名证书主题数据)
    private String caMessage;                   //ca指纹信息(签名值)
    private List<WlyyDoorPrescriptionDrugDO> recipeDetailList;
    @Transient
    public List<WlyyDoorPrescriptionDrugDO> getRecipeDetailList() {
        return recipeDetailList;
    }
    public void setRecipeDetailList(List<WlyyDoorPrescriptionDrugDO> recipeDetailList) {
        this.recipeDetailList = recipeDetailList;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getDoctorCode() {
        return doctorCode;
    }
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public Integer getDispensaryType() {
        return dispensaryType;
    }
    public void setDispensaryType(Integer dispensaryType) {
        this.dispensaryType = dispensaryType;
    }
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public String getRecipeNo() {
        return recipeNo;
    }
    public void setRecipeNo(String recipeNo) {
        this.recipeNo = recipeNo;
    }
    public String getDiagnosisCode() {
        return diagnosisCode;
    }
    public void setDiagnosisCode(String diagnosisCode) {
        this.diagnosisCode = diagnosisCode;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getJwDeptCode() {
        return jwDeptCode;
    }
    public void setJwDeptCode(String jwDeptCode) {
        this.jwDeptCode = jwDeptCode;
    }
    public String getJwHospital() {
        return jwHospital;
    }
    public void setJwHospital(String jwHospital) {
        this.jwHospital = jwHospital;
    }
    public String getJwDoctorCode() {
        return jwDoctorCode;
    }
    public void setJwDoctorCode(String jwDoctorCode) {
        this.jwDoctorCode = jwDoctorCode;
    }
    public BigDecimal getJwRegisterFee() {
        return jwRegisterFee;
    }
    public void setJwRegisterFee(BigDecimal jwRegisterFee) {
        this.jwRegisterFee = jwRegisterFee;
    }
    public Integer getJwPayStatus() {
        return jwPayStatus;
    }
    public void setJwPayStatus(Integer jwPayStatus) {
        this.jwPayStatus = jwPayStatus;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getPayTime() {
        return payTime;
    }
    public void setPayTime(Date payTime) {
        this.payTime = payTime;
    }
    public String getDiagnosisName() {
        return diagnosisName;
    }
    public void setDiagnosisName(String diagnosisName) {
        this.diagnosisName = diagnosisName;
    }
    public Date getVisitTime() {
        return visitTime;
    }
    public void setVisitTime(Date visitTime) {
        this.visitTime = visitTime;
    }
    public Integer getIsAfterDoor() {
        return isAfterDoor;
    }
    public void setIsAfterDoor(Integer isAfterDoor) {
        this.isAfterDoor = isAfterDoor;
    }
    public String getReason() {
        return reason;
    }
    public void setReason(String reason) {
        this.reason = reason;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getVisitNo() {
        return visitNo;
    }
    public void setVisitNo(String visitNo) {
        this.visitNo = visitNo;
    }
    public String getDiagnosisSubCode() {
        return diagnosisSubCode;
    }
    public void setDiagnosisSubCode(String diagnosisSubCode) {
        this.diagnosisSubCode = diagnosisSubCode;
    }
    public String getDiagnosisSubName() {
        return diagnosisSubName;
    }
    public void setDiagnosisSubName(String diagnosisSubName) {
        this.diagnosisSubName = diagnosisSubName;
    }
    public String getVisitDept() {
        return visitDept;
    }
    public void setVisitDept(String visitDept) {
        this.visitDept = visitDept;
    }
    public String getVisitDeptName() {
        return visitDeptName;
    }
    public void setVisitDeptName(String visitDeptName) {
        this.visitDeptName = visitDeptName;
    }
    public String getRegisterType() {
        return registerType;
    }
    public void setRegisterType(String registerType) {
        this.registerType = registerType;
    }
    public String getRegisterTypeName() {
        return registerTypeName;
    }
    public void setRegisterTypeName(String registerTypeName) {
        this.registerTypeName = registerTypeName;
    }
    public String getRateType() {
        return rateType;
    }
    public void setRateType(String rateType) {
        this.rateType = rateType;
    }
    public String getRateTypeName() {
        return rateTypeName;
    }
    public void setRateTypeName(String rateTypeName) {
        this.rateTypeName = rateTypeName;
    }
    public String getDigitalSignNo() {
        return digitalSignNo;
    }
    public void setDigitalSignNo(String digitalSignNo) {
        this.digitalSignNo = digitalSignNo;
    }
    public String getOriginalDataAbstract() {
        return originalDataAbstract;
    }
    public void setOriginalDataAbstract(String originalDataAbstract) {
        this.originalDataAbstract = originalDataAbstract;
    }
    public String getStrOriginalData() {
        return strOriginalData;
    }
    public void setStrOriginalData(String strOriginalData) {
        this.strOriginalData = strOriginalData;
    }
    public String getCaCertData() {
        return caCertData;
    }
    public void setCaCertData(String caCertData) {
        this.caCertData = caCertData;
    }
    public String getCaMessage() {
        return caMessage;
    }
    public void setCaMessage(String caMessage) {
        this.caMessage = caMessage;
    }
    public Long getAdminTeamId() {
        return adminTeamId;
    }
    public void setAdminTeamId(Long adminTeamId) {
        this.adminTeamId = adminTeamId;
    }
}

+ 101 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDetailDO.java

@ -0,0 +1,101 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
 * 上门服务开方服务工单价格明细
 * @author humingfen on  2019年07月24日
 */
@Entity
@Table(name = "wlyy_door_prescription_detail")
public class WlyyDoorPrescriptionDetailDO extends IntegerIdentityEntity {
    private String code;
    private String prescriptionCode;//关联wlyy_door_prescription code
    private Integer type;//费用类型,1-服务项费用
    private String itemCode;//处方服务项code
    private String itemName;//开方服务项名称
    private BigDecimal fee;//总费用
    private Integer num;//数量
    private Integer status;//状态,1有效 0删除
    private Date createTime;//创建时间
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPrescriptionCode() {
        return prescriptionCode;
    }
    public void setPrescriptionCode(String prescriptionCode) {
        this.prescriptionCode = prescriptionCode;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getItemCode() {
        return itemCode;
    }
    public void setItemCode(String itemCode) {
        this.itemCode = itemCode;
    }
    public String getItemName() {
        return itemName;
    }
    public void setItemName(String itemName) {
        this.itemName = itemName;
    }
    @Column(name = "fee")
    public BigDecimal getFee() {
        return fee;
    }
    public void setFee(BigDecimal fee) {
        this.fee = fee;
    }
    public Integer getNum() {
        return num;
    }
    public void setNum(Integer num) {
        this.num = num;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 327 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorPrescriptionDrugDO.java

@ -0,0 +1,327 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
 * 上门服务药品开方表
 *
 * @author humingfen on  2019年08月20日
 *
 */
@Entity
@Table(name = "wlyy_door_prescription_drug")
public class WlyyDoorPrescriptionDrugDO extends IntegerIdentityEntity {
    private String code;                    //业务主键
    private String prescriptionCode;      //处方code 关联表wlyy_door_prescription code
    private String drugCode;               //药品code
    private String drugName;               //药品名称
    private String subjectClass;               //科目类别(0101西成药 0103中草药 0201检验 0202检查 0204治疗 0205材料),02开头为诊疗,详情见zy_iv_subject_class_dict字典表
    private String drugRate;               //吃药频率
    private String drugRateName;          //用药频次名称
    private String drugFormat;             //药品规格/诊项规格
    private Integer num;                    //药品数目
    private Integer isRefrigerate;         //是否冷藏 1是 0否
    private String direction;               //药品用法
    private BigDecimal price;                    //药品单价
    private Integer del;               //1可用 0删除 不填数据库默认是1
    private String jwSubCode;//智业子处方号
    private String drugNumUnit;//数量单位编码
    private String drugNumUnitName;//数量单位名称
    private String physicDose;//用药剂量
    private String physicDoseUnit;//剂量单位编码
    private String physicDoseUnitName;//剂量单位名称
    private String physicAmount;//用药总量(实际用药量)
    private String physicAmountUnit;//总量单位编码
    private String physicAmountUnitName;//总量单位名称
    private String physicInjectPlace;//注射地点编码
    private String physicInjectPlaceName;//注射地点名称
    private String physicSkinTest;//注射地点名称
    private String physicSkinTestName;//皮试类型名称
    private BigDecimal cost;//金额
    private BigDecimal charge;//自付
    private String bindFlag;//成组标志, 0.非成组,1.成组
    private Integer dayCount;//用药天数
    private String drugUsage;//用药方法编码
    private String usageName;//用药方法名称
    private String remark;//备注
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date createTime;               //处方创建时间
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPrescriptionCode() {
        return prescriptionCode;
    }
    public void setPrescriptionCode(String prescriptionCode) {
        this.prescriptionCode = prescriptionCode;
    }
    public String getDrugCode() {
        return drugCode;
    }
    public void setDrugCode(String drugCode) {
        this.drugCode = drugCode;
    }
    public String getDrugName() {
        return drugName;
    }
    public void setDrugName(String drugName) {
        this.drugName = drugName;
    }
    public String getSubjectClass() {
        return subjectClass;
    }
    public void setSubjectClass(String subjectClass) {
        this.subjectClass = subjectClass;
    }
    public String getDrugRate() {
        return drugRate;
    }
    public void setDrugRate(String drugRate) {
        this.drugRate = drugRate;
    }
    public String getDrugRateName() {
        return drugRateName;
    }
    public void setDrugRateName(String drugRateName) {
        this.drugRateName = drugRateName;
    }
    public String getDrugFormat() {
        return drugFormat;
    }
    public void setDrugFormat(String drugFormat) {
        this.drugFormat = drugFormat;
    }
    public Integer getNum() {
        return num;
    }
    public void setNum(Integer num) {
        this.num = num;
    }
    public Integer getIsRefrigerate() {
        return isRefrigerate;
    }
    public void setIsRefrigerate(Integer isRefrigerate) {
        this.isRefrigerate = isRefrigerate;
    }
    public String getDirection() {
        return direction;
    }
    public void setDirection(String direction) {
        this.direction = direction;
    }
    public BigDecimal getPrice() {
        return price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public String getJwSubCode() {
        return jwSubCode;
    }
    public void setJwSubCode(String jwSubCode) {
        this.jwSubCode = jwSubCode;
    }
    public String getDrugNumUnit() {
        return drugNumUnit;
    }
    public void setDrugNumUnit(String drugNumUnit) {
        this.drugNumUnit = drugNumUnit;
    }
    public String getDrugNumUnitName() {
        return drugNumUnitName;
    }
    public void setDrugNumUnitName(String drugNumUnitName) {
        this.drugNumUnitName = drugNumUnitName;
    }
    public BigDecimal getCost() {
        return cost;
    }
    public void setCost(BigDecimal cost) {
        this.cost = cost;
    }
    public BigDecimal getCharge() {
        return charge;
    }
    public void setCharge(BigDecimal charge) {
        this.charge = charge;
    }
    public String getBindFlag() {
        return bindFlag;
    }
    public void setBindFlag(String bindFlag) {
        this.bindFlag = bindFlag;
    }
    public Integer getDayCount() {
        return dayCount;
    }
    public void setDayCount(Integer dayCount) {
        this.dayCount = dayCount;
    }
    public String getDrugUsage() {
        return drugUsage;
    }
    public void setDrugUsage(String drugUsage) {
        this.drugUsage = drugUsage;
    }
    public String getUsageName() {
        return usageName;
    }
    public void setUsageName(String usageName) {
        this.usageName = usageName;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getPhysicDose() {
        return physicDose;
    }
    public void setPhysicDose(String physicDose) {
        this.physicDose = physicDose;
    }
    public String getPhysicDoseUnit() {
        return physicDoseUnit;
    }
    public void setPhysicDoseUnit(String physicDoseUnit) {
        this.physicDoseUnit = physicDoseUnit;
    }
    public String getPhysicDoseUnitName() {
        return physicDoseUnitName;
    }
    public void setPhysicDoseUnitName(String physicDoseUnitName) {
        this.physicDoseUnitName = physicDoseUnitName;
    }
    public String getPhysicAmount() {
        return physicAmount;
    }
    public void setPhysicAmount(String physicAmount) {
        this.physicAmount = physicAmount;
    }
    public String getPhysicAmountUnit() {
        return physicAmountUnit;
    }
    public void setPhysicAmountUnit(String physicAmountUnit) {
        this.physicAmountUnit = physicAmountUnit;
    }
    public String getPhysicAmountUnitName() {
        return physicAmountUnitName;
    }
    public void setPhysicAmountUnitName(String physicAmountUnitName) {
        this.physicAmountUnitName = physicAmountUnitName;
    }
    public String getPhysicInjectPlace() {
        return physicInjectPlace;
    }
    public void setPhysicInjectPlace(String physicInjectPlace) {
        this.physicInjectPlace = physicInjectPlace;
    }
    public String getPhysicInjectPlaceName() {
        return physicInjectPlaceName;
    }
    public void setPhysicInjectPlaceName(String physicInjectPlaceName) {
        this.physicInjectPlaceName = physicInjectPlaceName;
    }
    public String getPhysicSkinTest() {
        return physicSkinTest;
    }
    public void setPhysicSkinTest(String physicSkinTest) {
        this.physicSkinTest = physicSkinTest;
    }
    public String getPhysicSkinTestName() {
        return physicSkinTestName;
    }
    public void setPhysicSkinTestName(String physicSkinTestName) {
        this.physicSkinTestName = physicSkinTestName;
    }
}

+ 91 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorProcessLogDO.java

@ -0,0 +1,91 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
* 工单状态变更记录(调度员操作记录)实体
*
* @author Administrator on  2019年04月09日
*
*/
@Entity
@Table(name = "wlyy_door_process_log")
public class WlyyDoorProcessLogDO extends UuidIdentityEntity {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 工单处理状态
	 */
	private Integer status;
    /**
	 * 变更状态的调度员
	 */
	private String dispatcher;
    /**
	 * 变更状态的调度员姓名
	 */
	private String dispatcherName;
    /**
	 * 
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date createTime;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
	@Column(name = "dispatcher")
    public String getDispatcher() {
        return dispatcher;
    }
    public void setDispatcher(String dispatcher) {
        this.dispatcher = dispatcher;
    }
	@Column(name = "dispatcher_name")
    public String getDispatcherName() {
        return dispatcherName;
    }
    public void setDispatcherName(String dispatcherName) {
        this.dispatcherName = dispatcherName;
    }
	@Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 231 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceApplicationDo.java

@ -0,0 +1,231 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.BaseIdentityEntity;
import org.springframework.data.annotation.LastModifiedBy;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务资质评审表
 */
@Entity
@Table(name = "wlyy_door_service_application")
public class WlyyDoorServiceApplicationDo extends BaseIdentityEntity {
    /**居民code*/
    private String patient;
    /**居民姓名*/
    private String patientName;
    /**居民身份证*/
    private String patientIdcard;
    /**居民地址*/
    private String patientAddr;
    /**联系方式*/
    private String patientPhone;
    /**补充描述*/
    private String applicationDescribe;
    /**代理申请居民code*/
    private String proxyPatient;
    /**代理申请居民姓名*/
    private String proxyPatientName;
    /**有效开始时间*/
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date startTime;
    /**有效截止时间*/
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date endTime;
    /**是否为永久生效:0不是,1是*/
    private Integer effectiveFlag;
    /**审核人类型:1调度员、2家医*/
    private Integer auditorType;
    /**审核人code*/
    private String auditorCode;
    /**审核人姓名*/
    private String auditorName;
    /**审核时间*/
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date auditTime;
    /**审核未通过原因*/
    private String failureReasons;
    /**是否有效 -1删除,0审核中,1未通过,2审核通过,3已过期*/
    private Integer status;
    /**
     * 资质凭证
     */
    private List<WlyyDoorServiceVoucherDo> wlyyDoorServiceVoucherDos;
    //更新者
    @LastModifiedBy
    protected String updateUser;
    //更新者
    @LastModifiedBy
    protected String updateUserName;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getProxyPatient() {
        return proxyPatient;
    }
    public void setProxyPatient(String proxyPatient) {
        this.proxyPatient = proxyPatient;
    }
    public String getProxyPatientName() {
        return proxyPatientName;
    }
    public void setProxyPatientName(String proxyPatientName) {
        this.proxyPatientName = proxyPatientName;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getPatientIdcard() {
        return patientIdcard;
    }
    public void setPatientIdcard(String patientIdcard) {
        this.patientIdcard = patientIdcard;
    }
    public String getPatientAddr() {
        return patientAddr;
    }
    public void setPatientAddr(String patientAddr) {
        this.patientAddr = patientAddr;
    }
    public String getPatientPhone() {
        return patientPhone;
    }
    public void setPatientPhone(String patientPhone) {
        this.patientPhone = patientPhone;
    }
    public String getApplicationDescribe() {
        return applicationDescribe;
    }
    public void setApplicationDescribe(String applicationDescribe) {
        this.applicationDescribe = applicationDescribe;
    }
    public Date getStartTime() {
        return startTime;
    }
    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
    public Date getEndTime() {
        return endTime;
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    @Transient
    public Integer getEffectiveFlag() {
        return effectiveFlag;
    }
    public void setEffectiveFlag(Integer effectiveFlag) {
        this.effectiveFlag = effectiveFlag;
    }
    public Integer getAuditorType() {
        return auditorType;
    }
    public void setAuditorType(Integer auditorType) {
        this.auditorType = auditorType;
    }
    public String getAuditorCode() {
        return auditorCode;
    }
    public void setAuditorCode(String auditorCode) {
        this.auditorCode = auditorCode;
    }
    public String getAuditorName() {
        return auditorName;
    }
    public void setAuditorName(String auditorName) {
        this.auditorName = auditorName;
    }
    public Date getAuditTime() {
        return auditTime;
    }
    public void setAuditTime(Date auditTime) {
        this.auditTime = auditTime;
    }
    public String getFailureReasons() {
        return failureReasons;
    }
    public void setFailureReasons(String failureReasons) {
        this.failureReasons = failureReasons;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Transient
    public List<WlyyDoorServiceVoucherDo> getWlyyDoorServiceVoucherDos() {
        return wlyyDoorServiceVoucherDos;
    }
    public void setWlyyDoorServiceVoucherDos(List<WlyyDoorServiceVoucherDo> wlyyDoorServiceVoucherDos) {
        this.wlyyDoorServiceVoucherDos = wlyyDoorServiceVoucherDos;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getUpdateUserName() {
        return updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
}

+ 65 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceConfigureDo.java

@ -0,0 +1,65 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.BaseIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by zdm on 2019/3/14.
 */
@Entity
@Table(name = "wlyy_door_service_configure")
public class WlyyDoorServiceConfigureDo extends BaseIdentityEntity {
    /**内容类型:1上门服务资质限制*/
    private String contentType;
    /** 类型:1区、2机构*/
    private String type;
    /**区、机构编码*/
    private String hospital;
    /**区、机构名称*/
    private String hospitalName;
    /**是否有效 0失效、1有效*/
    private Integer status;
    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 1184 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java

@ -0,0 +1,1184 @@
package com.yihu.jw.entity.door;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 上门服务工单实体
 *
 * @author Administrator on  2019年03月19日
 *
 */
@Entity
@Table(name = "wlyy_door_service_order")
public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    /**
     * 工单状态
     */
    public enum Status {
        cancel(-1, "已取消"),
        waitForSend(1, "待(调度员)派单"),
        waitForAccept(2, "待(医生)接单"),
        accept(3, "已接单"),
        waitForServe(4, "待服务"),
        waitForCommnet(5, "待评价"),
        complete(6,"已完成");
        private Integer type;
        private String desc;
        Status(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 支付方式
     */
    public enum PayWay {
        wechat(1, "微信支付"),
        offLine(2,"线下支付");
        private Integer type;
        private String desc;
        PayWay(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 取消类型
     */
    public enum CancelType {
        dispatcher(1, "调度员取消"),
        patient(2,"居民取消"),
        doctor(3, "医生取消");
        private Integer type;
        private String desc;
        CancelType(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 化验检查报告补录方式
     */
    public enum ExamPaperUploadWay {
        photo(1, "拍照补录"),
        interfaceData(2,"接口数据");
        private Integer type;
        private String desc;
        ExamPaperUploadWay(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 医生签到方式
     */
    public enum DoctorSignWay {
        locate(1, "定位"),
        sacn(2,"扫码");
        private Integer type;
        private String desc;
        DoctorSignWay(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 居民对工单需要服务情况是否已确认
     */
    public enum IsPatientConfirm {
        no(0, "未确认"),
        yes(1,"已确认");
        private Integer type;
        private String desc;
        IsPatientConfirm(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }  /**
     * 居民对工单需要服务情况是否已确认
     */
    public enum IsTransOtherOrg {
        no(0, "不转"),
        yes(1,"已转");
        private Integer type;
        private String desc;
        IsTransOtherOrg(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * 服务编号
     */
    private String number;
    /**
     * 代理发起工单的居民code,替父母,孩子等发起工单
     */
    private String proxyPatient;
    /**
     * 代理发起工单的居民code,替父母,孩子等发起工单
     */
    private String proxyPatientName;
    /**
     * 代理发起工单的居民联系电话
     */
    private String proxyPatientPhone;
    /**
     * 被服务的居民code,发起工单的居民的亲属
     */
    private String patient;
    /**
     * 被服务的居民姓名,发起工单的居民的亲属
     */
    private String patientName;
    /**
     * 被服务的居民联系电话
     */
    private String patientPhone;
    /**
     * 发起人与被服务人的关系:自己,父亲,母亲,儿子等
     */
    private String patientRelation;
    /**
     * 调度员code
     */
    private String dispatcher;
    /**
     * 调度员name
     */
    private String dispatcherName;
    /**
     * 居民期望服务时间
     */
//	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private String patientExpectedServeTime;
    /**
     * 居民自己服务描述
     */
    private String serveDesc;
    /**
     * 上门服务的区
     */
    private String serveTown;
    /**
     * 上门服务详细地址
     */
    private String serveAddress;
    /**
     * 上门服务地址纬度
     */
    private String serveLat;
    /**
     * 上门服务地址经度
     */
    private String serveLon;
    /**
     * 调度员备注
     */
    private String remark;
    /**
     * 居民对工单需要服务情况是否已确认,0-未确认,1-已确认, 2-不同意
     */
    private Integer isPatientConfirm;
    /**
     * 居民对工单需要服务情况确认时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date patientConfirmTime;
    /**
     * 工单是否转给其他机构,0-不转,1-已转
     */
    private Integer isTransOtherOrg;
    /**
     * 最后转接的机构code
     */
    private String transedOrgCode;
    /**
     * 最后转接的机构调度员code
     */
    private String transedDispatcher;
    /**
     * 最后转接的机构调度员name
     */
    private String transedDispatcherName;
    /**
     * 服务总费用
     */
    private BigDecimal totalFee;
    /**
     * 居民期望服务的医生姓名
     */
    private String expectedDoctorName;
    /**
     * 接单的医生code
     */
    private String doctor;
    /**
     * 接单的医生name
     */
    private String doctorName;
    /**
     * 接单的医生类型:医生,健管师,护士等
     */
    private String doctorType;
    /**
     * 医生预计到达时间
     */
    private String doctorArrivingTime;
    /**
     * 医生签到时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date doctorSignTime;
    /**
     * 医生签到方式:1-定位,2-扫码
     */
    private Integer doctorSignWay;
    /**
     * 医生签到位置,记录详细地址
     */
    private String doctorSignLocation;
    /**
     * 医生签到照片
     */
    private String doctorSignImg;
    /**
     * 居民确认结束服务方式:1-电子签名,2-手持身份证拍照
     */
    private Integer patientConfirmFinishWay;
    /**
     * 居民确认结束服务照片
     */
    private String patientConfirmFinishImg;
    /**
     * 居民确认医生结束服务时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date patientConfirmFinishTime;
    /**
     * 医生诊疗现场照片,最多9张,逗号分隔
     */
    private String presentImgs;
    /**
     * 是否需要上传补录报告:0-不需要,1-需要,待补录;2-需要,已补录
     */
    private Integer examPaperStatus;
    /**
     * 医生上传居民的化验检查报告照片
     */
    private String examPaperImgs;
    /**
     * 化验检查报告补录时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date examPaperUploadTime;
    /**
     * 化验检查报告补录方式,1-拍照补录,2-接口数据
     */
    private Integer examPaperUploadWay;
    /**
     * 工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待付款,5-待评价,6-已完成
     */
    private Integer status;
    /**
     * 工单完成时间(对工单评价完即工单完成)
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date completeTime;
    /**
     * 取消类型:1-调度员取消,2-居民取消
     */
    private Integer cancelType;
    /**
     * 取消理由
     */
    private String cancelReason;
    /**
     * 取消时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date cancelTime;
    /**
     * 付款方式:1-微信支付,2-线下支付(居民自己向医院支付,具体怎么支付由医院来定)
     */
    private Integer payWay;
    /**
     * 支付流水号
     */
    private String payNumber;
    /**
     * 支付时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date payTime;
    /**
     * 工单对应的服务项
     */
    private List<Map<String, Object>> doorFeeDetailList;
    /**
     * 工单对应的出诊费
     */
    private List<WlyyDoorDoctorDO> djDetailList;
    /**
     * 工单服务医生
     */
    private List<Map<String, Object>> doctors;
    /**
     * 服务小结
     */
    private WlyyDoorConclusionDO doorConclusion;
    /**
     * 调度员响应时间(派单时间或取消时间)
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date dispatcherResponseTime;
    /**
     * 服务医生响应时间(第一条咨询或者接单时间)
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date serviceResponseTime;
    /**
     * 出诊费用
     */
    private List<Map<String, Object>> visitCost;
    /**
     * 服务费用 服务包支付、待支付
     */
    private Map<String, Object> serviceCost;
    /**
     * 患者性别
     */
    private String sex;
    /**
     * 患者年龄
     */
    private Integer age;
    /**
     * 患者头像
     */
    private String photo;
    /**
     * 人群类型名称
     */
    private String typeValue;
    /**
     * 会话id
     */
    private String sessionId;
    /**
     * 服务机构
     */
    private String hospital;
    private Integer conclusionStatus;//服务小结登记状态:1待补录;2-已补录
    private Integer prescriptionStatus;//开方状态:1开方完成,0未开方
    private String prescriptionCode;//处方单号,多个用逗号隔开
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date prescriptionTime;//开方完成时间
    private Integer type;//发起工单类型(1本人发起 2家人待预约 3医生代预约)
    private String authorizeImage;//电子健康卡授权图片
    private String relationCode;//业务关联
    private String serviceStatus;//服务类型 1-预约项目 2-即时项目
    private String orderInfo;//工单详情 0-未推送 1-未确认 2-已确认
    private List<WlyyDoorPrescriptionDO> prescriptionDOList;//上门前开的方
    private List<WlyyDoorPrescriptionDO> afterPrescriptionList;//上门后开的方
    /**
     * 快捷类型,1是快捷类型,其他值不是
     */
    private String shortcutType;
    @Transient
    public List<WlyyDoorPrescriptionDO> getPrescriptionDOList() {
        return prescriptionDOList;
    }
    public void setPrescriptionDOList(List<WlyyDoorPrescriptionDO> prescriptionDOList) {
        this.prescriptionDOList = prescriptionDOList;
    }
    @Transient
    public List<WlyyDoorPrescriptionDO> getAfterPrescriptionList() {
        return afterPrescriptionList;
    }
    public void setAfterPrescriptionList(List<WlyyDoorPrescriptionDO> afterPrescriptionList) {
        this.afterPrescriptionList = afterPrescriptionList;
    }
    @Column(name = "number")
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    @Column(name = "proxy_patient")
    public String getProxyPatient() {
        return proxyPatient;
    }
    public void setProxyPatient(String proxyPatient) {
        this.proxyPatient = proxyPatient;
    }
    @Column(name = "proxy_patient_name")
    public String getProxyPatientName() {
        return proxyPatientName;
    }
    public void setProxyPatientName(String proxyPatientName) {
        this.proxyPatientName = proxyPatientName;
    }
    @Column(name = "proxy_patient_phone")
    public String getProxyPatientPhone() {
        return proxyPatientPhone;
    }
    public void setProxyPatientPhone(String proxyPatientPhone) {
        this.proxyPatientPhone = proxyPatientPhone;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    @Column(name = "patient_phone")
    public String getPatientPhone() {
        return patientPhone;
    }
    public void setPatientPhone(String patientPhone) {
        this.patientPhone = patientPhone;
    }
    @Column(name = "patient_relation")
    public String getPatientRelation() {
        return patientRelation;
    }
    public void setPatientRelation(String patientRelation) {
        this.patientRelation = patientRelation;
    }
    @Column(name = "dispatcher")
    public String getDispatcher() {
        return dispatcher;
    }
    public void setDispatcher(String dispatcher) {
        this.dispatcher = dispatcher;
    }
    @Column(name = "dispatcher_name")
    public String getDispatcherName() {
        return dispatcherName;
    }
    public void setDispatcherName(String dispatcherName) {
        this.dispatcherName = dispatcherName;
    }
    @Column(name = "patient_expected_serve_time")
    public String getPatientExpectedServeTime() {
        return patientExpectedServeTime;
    }
    public void setPatientExpectedServeTime(String patientExpectedServeTime) {
        this.patientExpectedServeTime = patientExpectedServeTime;
    }
    @Column(name = "serve_desc")
    public String getServeDesc() {
        return serveDesc;
    }
    public void setServeDesc(String serveDesc) {
        this.serveDesc = serveDesc;
    }
    @Column(name = "serve_town")
    public String getServeTown() {
        return serveTown;
    }
    public void setServeTown(String serveTown) {
        this.serveTown = serveTown;
    }
    @Column(name = "serve_address")
    public String getServeAddress() {
        return serveAddress;
    }
    public void setServeAddress(String serveAddress) {
        this.serveAddress = serveAddress;
    }
    @Column(name = "serve_lat")
    public String getServeLat() {
        return serveLat;
    }
    public void setServeLat(String serveLat) {
        this.serveLat = serveLat;
    }
    @Column(name = "serve_lon")
    public String getServeLon() {
        return serveLon;
    }
    public void setServeLon(String serveLon) {
        this.serveLon = serveLon;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Column(name = "is_patient_confirm")
    public Integer getIsPatientConfirm() {
        return isPatientConfirm;
    }
    public void setIsPatientConfirm(Integer isPatientConfirm) {
        this.isPatientConfirm = isPatientConfirm;
    }
    @Column(name = "patient_confirm_time")
    public Date getPatientConfirmTime() {
        return patientConfirmTime;
    }
    public void setPatientConfirmTime(Date patientConfirmTime) {
        this.patientConfirmTime = patientConfirmTime;
    }
    @Column(name = "is_trans_other_org")
    public Integer getIsTransOtherOrg() {
        return isTransOtherOrg;
    }
    public void setIsTransOtherOrg(Integer isTransOtherOrg) {
        this.isTransOtherOrg = isTransOtherOrg;
    }
    @Column(name = "transed_org_code")
    public String getTransedOrgCode() {
        return transedOrgCode;
    }
    @Column(name = "expected_doctor_name")
    public String getExpectedDoctorName() {
        return expectedDoctorName;
    }
    public void setExpectedDoctorName(String expectedDoctorName) {
        this.expectedDoctorName = expectedDoctorName;
    }
    public void setTransedOrgCode(String transedOrgCode) {
        this.transedOrgCode = transedOrgCode;
    }
    @Column(name = "transed_dispatcher")
    public String getTransedDispatcher() {
        return transedDispatcher;
    }
    public void setTransedDispatcher(String transedDispatcher) {
        this.transedDispatcher = transedDispatcher;
    }
    @Column(name = "transed_dispatcher_name")
    public String getTransedDispatcherName() {
        return transedDispatcherName;
    }
    public void setTransedDispatcherName(String transedDispatcherName) {
        this.transedDispatcherName = transedDispatcherName;
    }
    @Column(name = "total_fee")
    public BigDecimal getTotalFee() {
        return totalFee;
    }
    public void setTotalFee(BigDecimal totalFee) {
        this.totalFee = totalFee;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "doctor_type")
    public String getDoctorType() {
        return doctorType;
    }
    public void setDoctorType(String doctorType) {
        this.doctorType = doctorType;
    }
    @Column(name = "doctor_arriving_time")
    public String getDoctorArrivingTime() {
        return doctorArrivingTime;
    }
    public void setDoctorArrivingTime(String doctorArrivingTime) {
        this.doctorArrivingTime = doctorArrivingTime;
    }
    @Column(name = "doctor_sign_time")
    public Date getDoctorSignTime() {
        return doctorSignTime;
    }
    public void setDoctorSignTime(Date doctorSignTime) {
        this.doctorSignTime = doctorSignTime;
    }
    @Column(name = "doctor_sign_way")
    public Integer getDoctorSignWay() {
        return doctorSignWay;
    }
    public void setDoctorSignWay(Integer doctorSignWay) {
        this.doctorSignWay = doctorSignWay;
    }
    @Column(name = "doctor_sign_location")
    public String getDoctorSignLocation() {
        return doctorSignLocation;
    }
    public void setDoctorSignLocation(String doctorSignLocation) {
        this.doctorSignLocation = doctorSignLocation;
    }
    @Column(name = "doctor_sign_img")
    public String getDoctorSignImg() {
        return doctorSignImg;
    }
    public void setDoctorSignImg(String doctorSignImg) {
        this.doctorSignImg = doctorSignImg;
    }
    @Column(name = "patient_confirm_finish_way")
    public Integer getPatientConfirmFinishWay() {
        return patientConfirmFinishWay;
    }
    public void setPatientConfirmFinishWay(Integer patientConfirmFinishWay) {
        this.patientConfirmFinishWay = patientConfirmFinishWay;
    }
    @Column(name = "patient_confirm_finish_img")
    public String getPatientConfirmFinishImg() {
        return patientConfirmFinishImg;
    }
    public void setPatientConfirmFinishImg(String patientConfirmFinishImg) {
        this.patientConfirmFinishImg = patientConfirmFinishImg;
    }
    @Column(name = "patient_confirm_finish_time")
    public Date getPatientConfirmFinishTime() {
        return patientConfirmFinishTime;
    }
    public void setPatientConfirmFinishTime(Date patientConfirmFinishTime) {
        this.patientConfirmFinishTime = patientConfirmFinishTime;
    }
    @Column(name = "present_imgs")
    public String getPresentImgs() {
        return presentImgs;
    }
    public void setPresentImgs(String presentImgs) {
        this.presentImgs = presentImgs;
    }
    @Column(name = "exam_paper_status")
    public Integer getExamPaperStatus() {
        return examPaperStatus;
    }
    public void setExamPaperStatus(Integer examPaperStatus) {
        this.examPaperStatus = examPaperStatus;
    }
    @Column(name = "exam_paper_imgs")
    public String getExamPaperImgs() {
        return examPaperImgs;
    }
    public void setExamPaperImgs(String examPaperImgs) {
        this.examPaperImgs = examPaperImgs;
    }
    @Column(name = "exam_paper_upload_time")
    public Date getExamPaperUploadTime() {
        return examPaperUploadTime;
    }
    public void setExamPaperUploadTime(Date examPaperUploadTime) {
        this.examPaperUploadTime = examPaperUploadTime;
    }
    @Column(name = "exam_paper_upload_way")
    public Integer getExamPaperUploadWay() {
        return examPaperUploadWay;
    }
    public void setExamPaperUploadWay(Integer examPaperUploadWay) {
        this.examPaperUploadWay = examPaperUploadWay;
    }
    @Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    @Column(name = "complete_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCompleteTime() {
        return completeTime;
    }
    public void setCompleteTime(Date completeTime) {
        this.completeTime = completeTime;
    }
    @Column(name = "cancel_type")
    public Integer getCancelType() {
        return cancelType;
    }
    public void setCancelType(Integer cancelType) {
        this.cancelType = cancelType;
    }
    @Column(name = "cancel_reason")
    public String getCancelReason() {
        return cancelReason;
    }
    public void setCancelReason(String cancelReason) {
        this.cancelReason = cancelReason;
    }
    @Column(name = "cancel_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCancelTime() {
        return cancelTime;
    }
    public void setCancelTime(Date cancelTime) {
        this.cancelTime = cancelTime;
    }
    @Column(name = "pay_way")
    public Integer getPayWay() {
        return payWay;
    }
    public void setPayWay(Integer payWay) {
        this.payWay = payWay;
    }
    @Column(name = "pay_number")
    public String getPayNumber() {
        return payNumber;
    }
    public void setPayNumber(String payNumber) {
        this.payNumber = payNumber;
    }
    @Column(name = "pay_time")
    public Date getPayTime() {
        return payTime;
    }
    public void setPayTime(Date payTime) {
        this.payTime = payTime;
    }
    @Column(name = "hospital")
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Transient
    public List<Map<String, Object>> getDoorFeeDetailList() {
        return doorFeeDetailList;
    }
    public void setDoorFeeDetailList(List<Map<String, Object>> doorFeeDetailList) {
        this.doorFeeDetailList = doorFeeDetailList;
    }
    @Transient
    public List<WlyyDoorDoctorDO> getDjDetailList() {
        return djDetailList;
    }
    public void setDjDetailList(List<WlyyDoorDoctorDO> djDetailList) {
        this.djDetailList = djDetailList;
    }
    @Transient
    public List<Map<String, Object>> getDoctors() {
        return doctors;
    }
    public void setDoctors(List<Map<String, Object>> doctors) {
        this.doctors = doctors;
    }
    @Transient
    public WlyyDoorConclusionDO getDoorConclusion() {
        return doorConclusion;
    }
    public void setDoorConclusion(WlyyDoorConclusionDO doorConclusion) {
        this.doorConclusion = doorConclusion;
    }
    @Column(name = "dispatcher_response_time")
    public Date getDispatcherResponseTime() {
        return dispatcherResponseTime;
    }
    public void setDispatcherResponseTime(Date dispatcherResponseTime) {
        this.dispatcherResponseTime = dispatcherResponseTime;
    }
    @Column(name = "service_response_time")
    public Date getServiceResponseTime() {
        return serviceResponseTime;
    }
    public void setServiceResponseTime(Date serviceResponseTime) {
        this.serviceResponseTime = serviceResponseTime;
    }
    @Transient
    public List<Map<String, Object>> getVisitCost() {
        return visitCost;
    }
    public void setVisitCost(List<Map<String, Object>> visitCost) {
        this.visitCost = visitCost;
    }
    @Transient
    public Map<String, Object> getServiceCost() {
        return serviceCost;
    }
    public void setServiceCost(Map<String, Object> serviceCost) {
        this.serviceCost = serviceCost;
    }
    @Transient
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Transient
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Transient
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    @Transient
    public String getTypeValue() {
        return typeValue;
    }
    public void setTypeValue(String typeValue) {
        this.typeValue = typeValue;
    }
    @Transient
    public String getSessionId() {
        return sessionId;
    }
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
    public Integer getConclusionStatus() {
        return conclusionStatus;
    }
    public void setConclusionStatus(Integer conclusionStatus) {
        this.conclusionStatus = conclusionStatus;
    }
    public Integer getPrescriptionStatus() {
        return prescriptionStatus;
    }
    public void setPrescriptionStatus(Integer prescriptionStatus) {
        this.prescriptionStatus = prescriptionStatus;
    }
    public String getPrescriptionCode() {
        return prescriptionCode;
    }
    public void setPrescriptionCode(String prescriptionCode) {
        this.prescriptionCode = prescriptionCode;
    }
    public Date getPrescriptionTime() {
        return prescriptionTime;
    }
    public void setPrescriptionTime(Date prescriptionTime) {
        this.prescriptionTime = prescriptionTime;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getAuthorizeImage() {
        return authorizeImage;
    }
    public void setAuthorizeImage(String authorizeImage) {
        this.authorizeImage = authorizeImage;
    }
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
    }
    public void setRelationCode(String relationCode) {
        this.relationCode = relationCode;
    }
    @Column(name = "service_status")
    public String getServiceStatus() {
        return serviceStatus;
    }
    public void setServiceStatus(String serviceStatus) {
        this.serviceStatus = serviceStatus;
    }
    @Column(name = "order_info")
    public String getOrderInfo() {
        return orderInfo;
    }
    public void setOrderInfo(String orderInfo) {
        this.orderInfo = orderInfo;
    }
    @Column(name = "shortcut_type")
    public String getShortcutType() {
        return shortcutType;
    }
    public void setShortcutType(String shortcutType) {
        this.shortcutType = shortcutType;
    }
}

+ 98 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceVoucherDo.java

@ -0,0 +1,98 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.BaseIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务凭证
 */
@Entity
@Table(name = "wlyy_door_service_voucher")
public class WlyyDoorServiceVoucherDo extends BaseIdentityEntity {
    /**上门服务申请审核id*/
    private Long serviceId;
    /**居民code*/
    private String patientCode;
    /**居民姓名*/
    private String patientName;
    /** 人群类型:1残疾人,2肺结核患者,3残疾人,3计生特殊家庭,4重性精神病,5失能/半失能老人,6其他*/
    private String type;
    /**
     * 人群类型值
     */
    private String typeValue;
    /**凭证地址*/
    private String image;
    /**是否有效 0失效、1有效*/
    private Integer status;
    /**排序*/
    private Integer sort;
    public Long getServiceId() {
        return serviceId;
    }
    public void setServiceId(Long serviceId) {
        this.serviceId = serviceId;
    }
    public String getPatientCode() {
        return patientCode;
    }
    public void setPatientCode(String patientCode) {
        this.patientCode = patientCode;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    public String getTypeValue() {
        return typeValue;
    }
    public void setTypeValue(String typeValue) {
        this.typeValue = typeValue;
    }
}

+ 102 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorTransRecordDO.java

@ -0,0 +1,102 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 服务工单转接给其他结构的转接记录实体
*
* @author Administrator on  2019年03月15日
*
*/
@Entity
@Table(name = "wlyy_door_trans_record")
public class WlyyDoorTransRecordDO extends UuidIdentityEntityWithOperator {
    /**
	 * 工单id
	 */
	private String orderId;
    /**
	 * 调度员code
	 */
	private String dispatcher;
    /**
	 * 调度员code
	 */
	private String dispatcherName;
    /**
	 * 转接的机构code
	 */
	private String transedOrgCode;
    /**
	 * 转接的机构调度员code
	 */
	private String transedDispatcher;
    /**
	 * 转接的机构调度员code
	 */
	private String transedDispatcherName;
	@Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
	@Column(name = "dispatcher")
    public String getDispatcher() {
        return dispatcher;
    }
    public void setDispatcher(String dispatcher) {
        this.dispatcher = dispatcher;
    }
	@Column(name = "dispatcher_name")
    public String getDispatcherName() {
        return dispatcherName;
    }
    public void setDispatcherName(String dispatcherName) {
        this.dispatcherName = dispatcherName;
    }
	@Column(name = "transed_org_code")
    public String getTransedOrgCode() {
        return transedOrgCode;
    }
    public void setTransedOrgCode(String transedOrgCode) {
        this.transedOrgCode = transedOrgCode;
    }
	@Column(name = "transed_dispatcher")
    public String getTransedDispatcher() {
        return transedDispatcher;
    }
    public void setTransedDispatcher(String transedDispatcher) {
        this.transedDispatcher = transedDispatcher;
    }
	@Column(name = "transed_dispatcher_name")
    public String getTransedDispatcherName() {
        return transedDispatcherName;
    }
    public void setTransedDispatcherName(String transedDispatcherName) {
        this.transedDispatcherName = transedDispatcherName;
    }
}

+ 106 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyFeldsherCADO.java

@ -0,0 +1,106 @@
package com.yihu.jw.entity.door;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * create by hmf on 2019.10.23
 */
@Entity
@Table(name = "wlyy_feldsher_ca")
public class WlyyFeldsherCADO extends IdEntity {
    private String recipeNo;//医嘱号
    private String patient;//居民code
    private String patientName;//居民名称
    private String doctor;//医生code
    private String doctorName;//医生名称
    private String doctorOpenid;//医生openid
    private String hospital;//机构
    private String hospitalName;//机构名称
    private Integer status;//1未通知 0已通知
    private Date createTime;//创建时间
    public String getRecipeNo() {
        return recipeNo;
    }
    public void setRecipeNo(String recipeNo) {
        this.recipeNo = recipeNo;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getDoctorOpenid() {
        return doctorOpenid;
    }
    public void setDoctorOpenid(String doctorOpenid) {
        this.doctorOpenid = doctorOpenid;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 23 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/ResponseContant.java

@ -0,0 +1,23 @@
package com.yihu.jw.restmodel;
/**
 * Created by lith on 2019/03/19.
 */
public class ResponseContant {
    //****************有效状态标志*********************
    public static final int status_valid = 1;
    //****************无效状态标志*********************
    public static final int status_invalid = 2;
    //****************方法执行是否成功标志**************
    public static final String resultFlag = "resultFlag";
    public static final String resultMsg = "resultMsg";
    public static final int success = 1;
    public static final int fail = 0;
    public static final String count = "count";
}

+ 1 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/PageEnvelop.java

@ -107,6 +107,7 @@ public class PageEnvelop<T> extends Envelop implements Serializable {
    public static PageEnvelop getError(String message, int errorCode) {
        PageEnvelop envelop = new PageEnvelop();
        envelop.setMessage(message);
        envelop.setStatus(errorCode);
        return envelop;
    }

+ 54 - 2
common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java

@ -160,8 +160,7 @@ public class IdCardUtil {
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard_new(String CardCode)
            throws Exception {
    public static String getSexForIdcard_new(String CardCode){
        String sex = level_sex_3;
        try {
            if (CardCode.length() == 18) {
@ -225,4 +224,57 @@ public class IdCardUtil {
        }
        return sex;
    }
    public static int getAgeByIdcardOrBirthday(String idcard,Date birthday){
        int age = getAgeForIdcard(idcard);
        if(age<=0&&birthday!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(birthday);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DATE);
            Calendar cal = Calendar.getInstance();
            age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
                age--;
            }
            return age;
        }
        return age;
    }
    public static String getSexNameForIdcard_new(String idCard){
        String sex = getSexForIdcard_new(idCard);
        if(level_sex_1.equals(sex)){
            return level_sex_1_name;
        }else if(level_sex_2.equals(sex)){
            return level_sex_2_name;
        }else{
            return level_sex_3_name;
        }
    }
    /**
     * 身份证提取出身日期
     *
     * @param card
     * @return
     * @throws Exception
     */
    public static String getBirthdayForIdcardStr(String card)
            throws Exception {
        if (card.length() == 18) {
            String year = card.substring(6).substring(0, 4);// 得到年份
            String yue = card.substring(10).substring(0, 2);// 得到月份
            String ri = card.substring(12).substring(0, 2);// 得到日
            return year + "-" + yue + "-" + ri;
        } else if (card.length() == 15) {
            String uyear = "19" + card.substring(6, 8);// 年份
            String uyue = card.substring(8, 10);// 月份
            String uri = card.substring(10, 12);// 得到日
            return uyear + "-" + uyue + "-" + uri;
        }
        return null;
    }
}

+ 20 - 0
common/common-util/src/main/java/com/yihu/jw/util/entity/EntityUtils.java

@ -0,0 +1,20 @@
package com.yihu.jw.util.entity;
import com.fasterxml.jackson.databind.ObjectMapper;
public class EntityUtils {
    protected static ObjectMapper objectMapper = new ObjectMapper();
    public static <T> T jsonToEntity(String json,Class<T> target){
        T entity = null;
        try {
            entity  = objectMapper.readValue(json,target);
        } catch (Exception e) {
           throw new ServiceException("Json字符串转换成【"+target.getName()+"】实体类异常:" + e.getMessage());
        }
        return entity;
    }
}

+ 34 - 0
common/common-util/src/main/java/com/yihu/jw/util/entity/ServiceException.java

@ -0,0 +1,34 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.util.entity;
/**
 * Service层公用的Exception.
 * 
 * 继承自RuntimeException, 从由Spring管理事务的函数中抛出时会触发事务回滚.
 * 
 * @author calvin
 */
public class ServiceException extends RuntimeException {
	private static final long serialVersionUID = 3583566093089790852L;
	public ServiceException() {
		super();
	}
	public ServiceException(String message) {
		super(message);
	}
	public ServiceException(Throwable cause) {
		super(cause);
	}
	public ServiceException(String message, Throwable cause) {
		super(message, cause);
	}
}

+ 169 - 0
svr/svr-door-serivce/pom.xml

@ -0,0 +1,169 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.door</groupId>
    <artifactId>svr-door-service</artifactId>
    <version>${parent.version}</version>
    <packaging>war</packaging>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${version.json}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-request-mapping</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-exception</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <!--基础业务组件-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>base-service</artifactId>
            <version>2.0.0</version>
            <exclusions>
                <exclusion>
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>es-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- jkzl starter -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>fastdfs-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- redis start  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- redis end  -->
    </dependencies>
    <build>
        <finalName>svr-door-service</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.yihu.SvrDoorServiceApplication</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

+ 1 - 0
svr/svr-door-serivce/readme.MD

@ -0,0 +1 @@
svr-door-service 基础业务-上门服务

+ 24 - 0
svr/svr-door-serivce/src/main/java/com/yihu/SvrDoorServiceApplication.java

@ -0,0 +1,24 @@
package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
 *
 */
@SpringBootApplication
@EnableAspectJAutoProxy
public class SvrDoorServiceApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(SvrDoorServiceApplication.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SvrDoorServiceApplication.class);
    }
}

+ 57 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/config/jpa/DoorServiceJpa.java

@ -0,0 +1,57 @@
package com.yihu.jw.door.config.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "doorServiceEntityManagerFactory",
        transactionManagerRef = "doorServiceTransactionManager",
        basePackages = {"com.yihu.jw.*"})   //设置Repository所在位置
public class DoorServiceJpa {
    @Autowired
    private HibernateProperties hibernateProperties;
    @Bean(name = "doorServiceEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.jw.*");
        emfb.setPersistenceUnitName("door");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);
//        Properties properties = hibernateProperties.hibProperties();
//        properties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
        emfb.setJpaProperties(hibernateProperties.hibProperties());
        return emfb;
    }
    @Bean(name = "doorServiceTransactionManager")
    @Primary
    JpaTransactionManager transactionManagerSecondary(
            @Qualifier("doorServiceEntityManagerFactory") EntityManagerFactory builder) {
        return new JpaTransactionManager(builder);
    }
}

+ 35 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/config/jpa/HibernateProperties.java

@ -0,0 +1,35 @@
package com.yihu.jw.door.config.jpa;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
 * Created by chenweida on 2017/4/6.
 */
@Component
@RefreshScope
public class HibernateProperties {
    @Value("${hibernate.dialect}")
    private String dialect;
    @Value("${hibernate.show_sql}")
    private String show_sql;
    @Value("${hibernate.ejb.naming_strategy}")
    private String naming_strategy;
    @Value("${hibernate.physical_naming_strategy}")
    private String physical_naming_strategy;
    @Value("${hibernate.implicit_naming_strategy}")
    private String implicit_naming_strategy;
    public  Properties hibProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect",dialect);
        properties.put("hibernate.show_sql", show_sql);
//        properties.put("hibernate.ejb.naming_strategy", naming_strategy);
        properties.put("hibernate.physical_naming_strategy",physical_naming_strategy);
        properties.put("hibernate.implicit_naming_strategy",implicit_naming_strategy);
        return properties;
    }
}

+ 781 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/BaseController.java

@ -0,0 +1,781 @@
package com.yihu.jw.door.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "返回的json里的status是200,成功"),
        @ApiResponse(code = 403, message = "返回的json里的status是403,该操作没有权限"),
        @ApiResponse(code = 997, message = "返回的json里的status是997,重新登陆"),
        @ApiResponse(code = 998, message = "返回的json里的status是998,登录超时,请重新登录"),
        @ApiResponse(code = 999, message = "返回的json里的status是999,帐号在别处登录,请重新登录")
})
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger("error_logger");
    @Autowired
    protected HttpServletRequest request;
/*    @Autowired
    private HospitalDao hospitalDao;*/
    /**
     * 獲取髮送請求用戶的uid
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
//            return "xh1D2017031502222";// wjw00000001000e6badcfa163e424589/wjw00000001000e6badcfa163e424525
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取平台端
     * @return
     */
    public Integer getPlatform() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getInt("platform");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String id = json.getString("lastUid");
            if(StringUtils.isNoneBlank(id)){
                return id;
            }else{
               return json.getString("uid");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色code
     * @return
     */
    public String getCurrentRoleCode(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String currentUserRole = json.getJSONObject("currentUserRole").getString("code");
            if(StringUtils.isNotEmpty(currentUserRole)){
 /*               Hospital hospital = hospitalDao.findByCode(currentUserRole);
                if(hospital!=null&&hospital.getLevel()==3){
                    return hospital.getTown();
                }*/
            }
            return currentUserRole;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色级别
     * @return
     */
    public String getCurrentRoleLevel(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").get("level")+"";
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色是否是管理员
     * @return
     */
    public String getCurrentRoleIsManange(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").getString("isManage");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value,String key2, JSONObject value2) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            json.put(key2, value2);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, int total, String key, List<?> list) {
        try {
            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", code);
            map.put("msg", msg);
            map.put("total", total);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return error(defaultCode, defaultMsg);
        } catch (Exception e2) {
            return null;
        }
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    /**
     * 数据保留两位小数,**.0 去掉小数点
     * @param obj
     * @return
     */
    public String getNumberFormat(Object obj){
        if(obj != null){
            Double d = Double.valueOf(obj.toString());
            NumberFormat df = NumberFormat.getInstance();
            df.setGroupingUsed(false);
            df.setMaximumFractionDigits(2);
            return df.format(d);
        }else {
            return "";
        }
    }
    public String write(int code, String errorMsg, int page, int rows, long total, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("successFlg", code == 0);
            map.put("errorMsg", errorMsg);
            // 是否为第一页
            map.put("errorCode", code);
            // 是否为最后一页
            map.put("currPage", page);
            // 分页大小
            map.put("pageSize", rows);
            // 总条数
            map.put("totalCount", total);
            // 总页数
            map.put("totalPage", Math.ceil((double)total/(rows)));
            // 结果集
            map.put("detailModelList", list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    
    /**
     * 判断是否是观察者模式
     * @return
     */
    public boolean getObserverStatus () {
    
        String userAgent = request.getHeader("userAgent");
        if (StringUtils.isEmpty(userAgent)) {
            userAgent = request.getHeader("User-Agent");
        }
        logger.debug("userAgent:" + userAgent);
        JSONObject json = new JSONObject(userAgent);
        String observer = json.has("observer") ? json.getString("observer") : "";
        //如果是观察者直接返回true
        if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
            return true;
        }else{
            return false;
        }
    }
    //获取ip地址
    public String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
    //获取手机型号
    public String getPhoneType(){
        String userAgent = request.getHeader("User-Agent");
        Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");
        Matcher matcher = pattern.matcher(userAgent);
        String model = null;
        if (matcher.find()) {
            model = matcher.group(1).trim();
        }else{
            model = "未知型号";
        }
        return model;
    }
}

+ 170 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoctorDoorServiceAuditController.java

@ -0,0 +1,170 @@
package com.yihu.jw.door.controller.doctor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.door.controller.BaseController;
import com.yihu.jw.door.service.DoorServiceApplicationService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceApplicationDo;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
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;
/**
 * Created by zdm on 2019/3/13.
 */
@RestController
@RequestMapping(value = "/doctor/doorServiceAuditing", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-上门服务资质申请审核")
public class DoctorDoorServiceAuditController extends BaseController {
    @Autowired
    private DoorServiceApplicationService doorServiceApplicationService;
    @Autowired
    private BasePatientDao patientService;
    @RequestMapping(value = "getDoorSericeApplicationStatus", method = RequestMethod.GET)
    @ApiOperation(value = "获取资质审核状态")
    public String getDoorSericeApplicationStatus(
            @ApiParam(name = "patient", value = "patient")
            @RequestParam(value = "patient", required = true) String patient) {
        try {
            return write(200, "获取成功", "data", doorServiceApplicationService.getDoorSericeApplicationStatus(patient));
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "getPOnsiteServiceByDoctor", method = RequestMethod.GET)
    @ApiOperation(value = "获取待审核的居民上门服务资质申请")
    public String getPOnsiteServiceByDoctor(
            @ApiParam(name = "doctorCode", value = "当前医生code")
            @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(name = "auditorType", value = "医生角色:1调度员、2家医",required = true)
            @RequestParam(value = "auditorType", required = true) String auditorType,
            @ApiParam(name = "patientName", value = "居民姓名")
            @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(name = "mobile", value = "居民联系方式")
            @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(name = "crowdType", value = "人群类型:1失能老人,2半失能老人,3残疾人,4计生特殊家庭,5其他")
            @RequestParam(value = "crowdType", required = false) String crowdType,
            @ApiParam(name = "status", value = "资质状态:为空默认查找审核过的申请,0审核中,1未通过,2审核通过,3已过期")
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "15") Integer pageSize) {
        try {
            if(StringUtils.isBlank(doctorCode)){
                doctorCode=getRepUID();
            }
            JSONObject jsonObject = doorServiceApplicationService.getPOnsiteServiceByDoctor( doctorCode, auditorType, patientName, mobile, crowdType, status, page, pageSize);
            return write(200, "获取成功", "data", jsonObject);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "auditing", method = RequestMethod.POST)
    @ApiOperation(value = "获取居民上门服务资质审核及调度")
    public String auditing(
            @ApiParam(name = "id", value = "资质申请id")
            @RequestParam(value = "id", required = false) Long id,
            @ApiParam(name = "operationType", value = "操作类型:1审核,2调度",required = true)
            @RequestParam(value = "operationType", required = true) String operationType,
            @ApiParam(name = "doctorCode", value = "当前医生code,可不传")
            @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(name = "status", value = "审核状态:1未通过,2审核通过")
            @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "startDate", value = "开始时间", required = false)
            @RequestParam(value = "startDate",required = false)String startDate,
            @ApiParam(name = "endDate", value = "结束时间", required = false)
            @RequestParam(value = "endDate",required = false)String endDate,
            @ApiParam(name = "failureReasons", value = "拒绝的原因")
            @RequestParam(value = "failureReasons", required = false) String failureReasons) {
        try {
            if(StringUtils.isBlank(doctorCode)){
                doctorCode=getRepUID();
            }
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.auditing( id,doctorCode,status, startDate,endDate,operationType,failureReasons);
            return write(200, "审核成功", "data", wlyyDoorServiceApplicationDo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1, "审核失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "getPOnsiteServiceById", method = RequestMethod.GET)
    @ApiOperation(value = "获取居民上门服务资质申请详情")
    public String getPOnsiteServiceById(
            @ApiParam(name = "id", value = "资质申请id")
            @RequestParam(value = "id", required = false) Long id) {
        try {
            JSONObject jsonObject = doorServiceApplicationService.getPOnsiteServiceById(id);
            return write(200, "获取成功", "data", jsonObject);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "getPOnsiteServiceByPatient", method = RequestMethod.GET)
    @ApiOperation(value = "医生根据查找的居民code获取居民的资质申请信息")
    public String getPOnsiteServiceByPatient(
            @ApiParam(name = "patientCode", value = "居民code")
            @RequestParam(value = "patientCode", required = true) String patientCode) {
        try {
            ObjectMapper objectMapper=new ObjectMapper();
            JSONObject jsonObject=new JSONObject();
            BasePatientDO patientDo=patientService.findById(patientCode);
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.findOnsiteServiceByPatient(patientCode);
            if (null == wlyyDoorServiceApplicationDo.getId()) {
                JSONObject patient = doorServiceApplicationService.findPatientByCode(patientCode);
                jsonObject.put("applicationStatus",0);
                jsonObject.put("patient",patient);
                jsonObject.put("photo",patientDo.getPhoto());
                return write(200, "获取成功", "data", jsonObject);
            }else{
                jsonObject.put("applicationStatus","1");
                jsonObject.put("age", IdCardUtil.getAgeForIdcard(wlyyDoorServiceApplicationDo.getPatientIdcard()));
                jsonObject.put("sex",IdCardUtil.getSexForIdcard_new(wlyyDoorServiceApplicationDo.getPatientIdcard()));
                jsonObject.put("photo",patientDo.getPhoto());
                jsonObject.put("patient",com.alibaba.fastjson.JSONObject.toJSON(patientDo));
                jsonObject.put("wlyyDoorServiceApplicationDo", objectMapper.writeValueAsString(wlyyDoorServiceApplicationDo));
            }
            return write(200, "获取成功", "data", jsonObject);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ApiOperation(value = "医生为居民开通服务资格")
    public String create(
            @ApiParam(name = "jsonData", value = "开通服务资格内容jsonData")
            @RequestParam(value = "jsonData",required = true)String jsonData,
            @ApiParam(name = "doctorCode", value = "医生doctorCode")
            @RequestParam(value = "doctorCode",required = false)String doctorCode){
        try {
            if(StringUtils.isBlank(doctorCode)){
                doctorCode=getRepUID();
            }
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.create("2",jsonData,doctorCode);
            return write(200, "获取成功", "data", wlyyDoorServiceApplicationDo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取失败!"+e.getMessage());
        }
    }
}

+ 1298 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoorOrderController.java

@ -0,0 +1,1298 @@
package com.yihu.jw.door.controller.doctor;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.controller.BaseController;
import com.yihu.jw.door.dao.WlyyDoorDoctorDao;
import com.yihu.jw.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.door.service.DoorOrderService;
import com.yihu.jw.door.service.WlyyDoorPrescriptionService;
import com.yihu.jw.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.door.service.common.HospitalService;
import com.yihu.jw.door.service.common.ServerPackageService;
import com.yihu.jw.door.service.prescription.JwDoorPrescriptionService;
import com.yihu.jw.entity.door.WlyyDoorConclusionDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.restmodel.ResponseContant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
/**
 * Created by wxw on 2019/3/15.
 *
 * @author wxw.
 */
@RestController
@RequestMapping(value = "/doctor/serviceOrder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-上门服务")
public class DoorOrderController extends BaseController {
    @Autowired
    private DoorOrderService doorOrderService;
    @Autowired
    private WlyyDoorDoctorDao doorDoctorDao;
    @Autowired
    private WlyyDoorServiceOrderDao doorServiceOrderDao;
    @Autowired
    private ServerPackageService serverPackageService;
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private WlyyDoorPrescriptionService doorPrescriptionService;
    @Autowired
    private JwDoorPrescriptionService jwDoorPrescriptionService;
    @GetMapping("/getDispatchOrderSwitch")
    @ApiOperation(value = "获取医生分派订单开关状态")
    public String getDispatchOrderSwitch(
            @ApiParam(name = "doctor", value = "医生codedoctor")
            @RequestParam(value = "doctor", required = true) String doctor) {
        try {
            String status = doorOrderService.findDispatchStatusByDoctor(doctor);
            return write(200, "获取成功", "data", status);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("/dispatchOrderSwitch")
    @ApiOperation(value = "分派订单开关修改")
    public String dispatchOrderSwitch(
            @ApiParam(name = "doctor", value = "医生code")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(value = "开关值,5关闭 1开启", name = "value")
            @RequestParam(value = "value", required = true) Integer value) {
        try {
            doorOrderService.updateDispatchStatusByDoctor(doctor, value);
            return write(200, "修改成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "修改失败!" + e.getMessage());
        }
    }
    @GetMapping("/topStatusBarNum")
    @ApiOperation(value = "顶部状态栏订单分类tab")
    public String topStatusBarNum(
            @ApiParam(name = "doctor", value = "医生code")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(value = "发起类型(1本人发起 2家人待预约 3医生代预约)", name = "type")
            @RequestParam(value = "type", required = false) Integer type) {
        try {
            Map<String, String> map = doorOrderService.getNumGroupByStatus(doctor, type);
            return write(200, "获取成功", "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @GetMapping("getByOrderId")
    @ApiOperation(value = "根据工单id获取相应的工单,如果为空,则获取该医生当前最新一条的工单")
    public String getByOrderId(
            @ApiParam(value = "医生code", name = "doctor")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = false) String orderId,
            @ApiParam(name = "level", value = "医院等级,1.三级医院,2.二级医院,3.一级及以下")
            @RequestParam(value = "level",required = true)Integer level) {
        try {
            // 没有提供工单id的情况下,则获取该医生当前最新一条的工单
            if (StringUtils.isEmpty(orderId)) {
                // 根据接单医生code获取最近一次服务orderId
                orderId = doorOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return error(-1, "获取失败, 该医生暂无工单" );
                }
            }
            // 根据orderId获取工单信息
            WlyyDoorServiceOrderDO doorServiceOrderDO = doorOrderService.getDoorServiceOrderById(orderId, level);
            return write(200, "获取成功", "data", doorServiceOrderDO);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败, 该医生暂无工单!" + e.getMessage());
        }
    }
    @PostMapping("acceptOrder")
    @ApiOperation(value = "接单")
    public String acceptOrder(
            @ApiParam(value = "工单id", name = "orderId", required = true) @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "医生职称code", name = "jobCode", required = true) @RequestParam(value = "jobCode", required = true) String jobCode,
            @ApiParam(value = "医生职称", name = "jobCodeName", required = true) @RequestParam(value = "jobCodeName", required = true) String jobCodeName,
            @ApiParam(value = "医院级别", name = "hospitalLevel", required = true) @RequestParam(value = "hospitalLevel", required = true) int hospitalLevel) {
        try {
            doorOrderService.acceptOrder(orderId,jobCode,jobCodeName,hospitalLevel);
            return write(200, "操作成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @PostMapping(value = "transferOrder")
    @ApiOperation(value = "医生转派单")
    public String transferOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "当前医生备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(name = "dispatcher", value = "当前医生code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "dispathcherName", value = "当前医生姓名") @RequestParam(value = "dispathcherName", required = true) String dispathcherName,
            @ApiParam(name = "doctor", value = "医生code") @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = true) String doctorName,
            @ApiParam(name = "doctorJobName", value = "医生职称") @RequestParam(value = "doctorJobName", required = true) String doctorJobName) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.transferOrder(orderId, remark,dispatcher,dispathcherName, doctor, doctorName ,doctorJobName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error( -1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"派单成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "派单失败!");
        }
    }
    @PostMapping("refuse")
    @ApiOperation(value = "拒单")
    public String refuseOrder(
            @ApiParam(value = "工单id", name = "orderId", required = true)
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "拒绝原因", name = "reason", required = false)
            @RequestParam(value = "reason", required = false) String reason) {
        try {
            doorOrderService.refuseOrder(getUID(),orderId, reason);
            return write(200, "操作成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @PostMapping("updateArrivingTime")
    @ApiOperation(value = "修改预计到达时间")
    public String updateArrivingTime(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "医生预计到达时间", name = "arrivingTime")
            @RequestParam(value = "arrivingTime", required = true) String arrivingTime) {
        try {
            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = doorOrderService.updateArrivingTime(orderId, arrivingTime);
            return write(200, "修改成功", "data", wlyyDoorServiceOrderDO);
        } catch (Exception e) {
            error(e);
            return error(-1, "修改失败!" + e.getMessage());
        }
    }
    @RequestMapping(value = "/urlAnalysis",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("门牌解析上门地址")
    @ResponseBody
    public String urlAnalysis(@ApiParam(name = "url", value = "地址解析", defaultValue = "")
                              @RequestParam(value = "url", required = true)String url)throws Exception {
        try {
            return write(200, "操作成功!","data",doorOrderService.urlAnalysis(url));
        }catch (Exception e){
            //日志文件中记录异常信息
            error(e);
            //返回接口异常信息处理结果
            return error(-1, "操作失败!");
        }
    }
    @PostMapping("signIn")
    @ApiOperation(value = "上门服务签到")
    public String signIn(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "签到时间", name = "signTime")
            @RequestParam(value = "signTime", required = false) String signTime,
            @ApiParam(value = "签到方式:1-定位,2-扫码,3-拍照,4-二维码", name = "signWay")
            @RequestParam(value = "signWay", required = false) Integer signWay,
            @ApiParam(value = "签到地址", name = "signLocation")
            @RequestParam(value = "signLocation", required = false) String signLocation,
            @ApiParam(value = "签到照片", name = "signImg")
            @RequestParam(value = "signImg", required = false) String signImg,
            @ApiParam(value = "二维码内容", name = "twoDimensionalCode")
            @RequestParam(value = "twoDimensionalCode", required = false) String twoDimensionalCode) {
        try {
            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = doorOrderService.signIn(orderId, signTime, signWay, signLocation, signImg,twoDimensionalCode);
            if (wlyyDoorServiceOrderDO != null){
                return write(200, "操作成功", "data", wlyyDoorServiceOrderDO);
            }else {
             return error(-1,"扫码签到失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @GetMapping("getDoorConclusion")
    @ApiOperation("获取服务工单小结")
    public String getDoorConclusion(
            @ApiParam(value = "医生code", name = "doctor")
            @RequestParam(value = "doctor", required = false) String doctor,
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = false) String orderId) {
        try {
            // 没有提供工单id的情况下,默认代入上一次服务信息记录
            if (StringUtils.isEmpty(orderId)) {
                orderId = doorOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return error(204, "获取失败,该医生暂无工单" );
                }
            }
            // 根据orderId查询工单小结表
            WlyyDoorConclusionDO doorConclusion = doorOrderService.getDoorConclusion(orderId, true);
            return write(200, "获取成功", "data", doorConclusion);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("updateDoorConclusion")
    @ApiOperation("编辑保存服务工单小结")
    public String updateDoorConclusion(
            @RequestParam String model,
            @ApiParam(value = "补录状态", name = "examPapeStatus")
            @RequestParam(value = "examPapeStatus", required = false) Integer examPapeStatus) {
        try {
            WlyyDoorConclusionDO doorConclusion = doorOrderService.updateDoorConclusion(model, examPapeStatus);
            return write(200, "保存成功", "data", doorConclusion);
        } catch (Exception e) {
            error(e);
            return error(-1, "保存失败!" + e.getMessage());
        }
    }
    @PostMapping("savePatientSignOrCertificate")
    @ApiOperation(value = "居民确认记录")
    public String savePatientSignOrCertificate(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "居民确认结束服务方式", name = "finishWay")
            @RequestParam(value = "finishWay", required = false) Integer finishWay,
            @ApiParam(value = "居民确认结束服务照片", name = "finishImg")
            @RequestParam(value = "finishImg", required = false) String finishImg,
            @ApiParam(name = "level", value = "医院等级,1.三级医院,2.二级医院,3.一级及以下")
            @RequestParam(value = "level",required = true)Integer level) {
        try {
            return write(200, "获取成功", "data", doorOrderService.savePatientSignOrCertificate(orderId, finishWay, finishImg, level));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("saveExamPaperInfo")
    @ApiOperation(value = "医生补录报告")
    public String saveExamPaperInfo(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "化验检查报告补录方式,1-拍照补录,2-接口数据", name = "examPaperWay")
            @RequestParam(value = "examPaperWay", required = false) Integer examPaperWay,
            @ApiParam(value = "化验检查报告补录时间", name = "examPaperTime")
            @RequestParam(value = "examPaperTime", required = false) String examPaperTime,
            @ApiParam(value = "居民的化验检查报告照片", name = "examPaperImg")
            @RequestParam(value = "examPaperImg", required = false) String examPaperImg,
            @ApiParam(name = "level", value = "医院等级,1.三级医院,2.二级医院,3.一级及以下")
            @RequestParam(value = "level",required = true)Integer level) {
        try {
            return write(200, "获取成功", "data", doorOrderService.saveExamPaperInfo(orderId, examPaperWay, examPaperTime, examPaperImg, level));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("confirmReceipt")
    @ApiOperation(value = "医生确认线下收款")
    public String confirmReceipt(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "level", value = "医院等级,1.三级医院,2.二级医院,3.一级及以下")
            @RequestParam(value = "level",required = true)Integer level) {
        try {
            return write(200, "获取成功", "data", doorOrderService.confirmReceipt(orderId, level));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @GetMapping("/getDoorOrderList")
    @ApiOperation(value = "服务工单列表")
    public String getDoorOrderList(
            @ApiParam(value = "工单id", name = "orderId",required = false)
            @RequestParam(value = "orderId", required = false) String orderId,
            @ApiParam(value = "居民姓名", name = "patientName",required = false)
            @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(value = "联系方式", name = "patientPhone",required = false)
            @RequestParam(value = "patientPhone", required = false) String patientPhone,
            @ApiParam(value = "服务机构", name = "hospitalCode",required = false)
            @RequestParam(value = "hospitalCode", required = false) String hospitalCode,
            @ApiParam(value = "工单状态", name = "status",required = false)
            @RequestParam(value = "status", required = false) Integer[] status,
            @ApiParam(value = "创建时间开始,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeStart",required = false)
            @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
            @ApiParam(value = "创建时间结束,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeEnd",required = false)
            @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
            @ApiParam(value = "服务医生的名称", name = "serverDoctorName",required = false)
            @RequestParam(value = "serverDoctorName", required = false) String serverDoctorName,
            @ApiParam(value = "医生的code", name = "doctorCode",required = false)
            @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(value = "角色0、医生,1、管理员", name = "isManage",required = false)
            @RequestParam(value = "isManage", required = false) String isManage,
            @ApiParam(value = "0-不需要,1-需要,待补录;2-需要,已补录", name = "examPaperStatus",required = false)
            @RequestParam(value = "examPaperStatus", required = false) Integer examPaperStatus,
            @ApiParam(value = "发起类型(1本人发起 2家人待预约 3医生代预约)", name = "type")
            @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
            @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "10",required = true)
            @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            if(StringUtils.isEmpty(isManage)){
                isManage = getCurrentRoleIsManange();
            }
            if("0".equals(isManage)){
                if(StringUtils.isEmpty(doctorCode)){
                    doctorCode=getUID();
                }
            }else if ("1".equals(isManage) && StringUtils.isBlank(hospitalCode)){
                //如果是管理员并且未筛选机构,就默认展示其管理下所有机构
                String level = getCurrentRoleLevel();
                String currentRoleCode = getCurrentRoleCode();
                if(level.equals("2")) {
                    //市管理员
                    hospitalCode = currentRoleCode.substring(0, currentRoleCode.length() - 2) + "%";
                }else if(level.equals("3")){
                    //区管理员
                    hospitalCode = currentRoleCode + "%";
                }else if (level.equals("4")){
                    //机构管理员
                    hospitalCode = currentRoleCode;
                }
            }else if(StringUtils.isNotBlank(hospitalCode) && hospitalCode.length() < 10 ){
                hospitalCode += "%";
            }
            StringBuffer ss = new StringBuffer();
            if (status != null && status.length > 0){
                int statusLength = status.length;
                for (int i =0 ; i < statusLength ; i++){
                    ss .append(status[i]);
                    if (i<statusLength-1){
                        ss.append(",");
                    }
                }
            }else {
                ss = null;
            }
            JSONObject result = doorOrderService.getDoorOrderList(orderId,patientName,patientPhone,hospitalCode,
                    ss,createTimeStart,createTimeEnd,serverDoctorName,doctorCode,examPaperStatus,page,pageSize, type);
            return write(200, "获取成功","data",result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @ApiOperation("导出工单到excel")
    @GetMapping(value = "/doorOrderOutExcel")
    public void doorOrderOutExcel(
            @ApiParam(value = "工单id", name = "orderId",required = false)
            @RequestParam(value = "orderId", required = false) String orderId,
            @ApiParam(value = "居民姓名", name = "patientName",required = false)
            @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(value = "联系方式", name = "patientPhone",required = false)
            @RequestParam(value = "patientPhone", required = false) String patientPhone,
            @ApiParam(value = "服务机构", name = "hospitalCode",required = false)
            @RequestParam(value = "hospitalCode", required = false) String hospitalCode,
            @ApiParam(value = "工单状态", name = "status",required = false)
            @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "创建时间开始,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeStart",required = false)
            @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
            @ApiParam(value = "创建时间结束,格式(yyyy-MM-dd mm:dd:ss)", name = "createTimeEnd",required = false)
            @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
            @ApiParam(value = "服务医生的名称", name = "serverDoctorName",required = false)
            @RequestParam(value = "serverDoctorName", required = false) String serverDoctorName,
            @ApiParam(value = "医生的code", name = "doctorCode",required = false)
            @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(value = "角色0、医生,1、管理员", name = "isManage",required = false)
            @RequestParam(value = "isManage", required = false) String isManage,
            @ApiParam(value = "0-不需要,1-需要,待补录;2-需要,已补录", name = "examPaperStatus",required = false)
            @RequestParam(value = "examPaperStatus", required = false) Integer examPaperStatus,
            @ApiParam(value = "角色等级", name = "level",required = false)
            @RequestParam(value = "level", required = false) String level,
            HttpServletResponse response){
        try{
            if(StringUtils.isEmpty(isManage)){
                isManage = getCurrentRoleIsManange();
            }
            if("0".equals(isManage)){
                if(StringUtils.isEmpty(doctorCode)){
                    doctorCode=getUID();
                }
            }else if ("1".equals(isManage)){
                //如果是管理员并且未筛选机构,就默认展示其管理下所有机构
                if(level.equals("2")) {
                    //市管理员
                    hospitalCode = hospitalCode.substring(0, hospitalCode.length() - 2) + "%";
                }else if(level.equals("3")){
                    //区管理员
                    hospitalCode = hospitalCode + "%";
                }
            }
            doorOrderService.doorOrderOutExcel(orderId,patientName,patientPhone,hospitalCode,
                    status,createTimeStart,createTimeEnd,serverDoctorName,doctorCode,examPaperStatus,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 获取服务项目
     *
     * @param hospital
     * @return
     */
    @GetMapping("selectByHospital")
    @ApiOperation(value = "获取服务项目")
    public String selectByHospital(
            @ApiParam(value = "机构code", name = "hospital")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(value = "服务项目名称", name = "serverItemName")
            @RequestParam(value = "serverItemName", required = false) String serverItemName) {
        try {
//            return write(200, "获取成功","dara",serviceItemService.selectByHospital(hospital,serverItemName));
            return write(200, "获取成功","dara","");
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    /**
     * 获取服务项目-上门服务
     *
     * @param hospital
     * @return
     */
    @GetMapping("selectServiceByHospital")
    @ApiOperation(value = "获取服务项目-上门服务")
    public String selectServiceByHospital(
            @ApiParam(value = "机构code", name = "hospital")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(value = "服务项目名称", name = "serverItemName")
            @RequestParam(value = "serverItemName", required = false) String serverItemName,
            @ApiParam(value = "类型", name = "type")
            @RequestParam(value = "type", required = false) String type,
            @ApiParam(value = "居民", name = "patient")
            @RequestParam(value = "patient", required = false) String patient) {
        try {
            return write(200, "获取成功","dara",serverPackageService.selectServiceByHospital(hospital,serverItemName,type,patient,getUID()));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @RequestMapping(value = "selectServiceTypes", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取服务项目类型-上门服务")
    public String selectServiceTypes(){
        try {
            return write(200, "查询成功", "data",serverPackageService.selectTypes());
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败");
        }
    }
    @PostMapping("updateDoctorInfo")
    @ApiOperation(value = "修改保存服务医生")
    public String updateDoctorInfo(
            @ApiParam(value = "jsonData", name = "jsonData")
            @RequestParam(value = "jsonData", required = false) String jsonData) {
        try {
            // 医生更新上门信息
            wlyyDoorServiceOrderService.updateDoctorInfo(jsonData);
            return write(200, "修改成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "修改失败!" + e.getMessage());
        }
    }
    @PostMapping("updateDoctorInfoNoPatient")
    @ApiOperation(value = "修改保存服务医生(不用经过居民同意)")
    public String updateDoctorInfoNoPatient(
            @ApiParam(value = "jsonData", name = "jsonData")
            @RequestParam(value = "jsonData", required = false) String jsonData) {
        try {
            // 医生更新上门信息
            wlyyDoorServiceOrderService.updateDoctorInfoNoPatient(jsonData);
            return write(200, "修改成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "修改失败!" + e.getMessage());
        }
    }
    @PostMapping("updatePackageItemInfo")
    @ApiOperation(value = "修改保存服务项")
    public String updatePackageItemInfo(
            @ApiParam(value = "jsonData", name = "jsonData")
            @RequestParam(value = "jsonData", required = false) String jsonData) {
        try {
            doorOrderService.updatePackageItemInfo(jsonData);
            return write(200, "修改成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "修改失败!" + e.getMessage());
        }
    }
    @ApiOperation("社区医院下医生列表查询接口 没分页")
    @RequestMapping(value = "getDoctorListByHospitalNoPage",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorListByHospitalNoPage(
            @RequestParam(required = true) String orderId,
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type) {
        try {
            List<JSONObject> array = new ArrayList<>();
            WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
            // 被服务的居民的次数(非代理居民)
            Integer times = wlyyDoorServiceOrderService.countPatientDoorTimes(one.getPatient());
            List<String> doctors = doorDoctorDao.findDoctors(orderId);
            List<Map<String, Object>> list = hospitalService.getDoctorsByhospitalNoPage(hospital, name, type, times);
            if (list != null) {
                for (Map<String, Object> doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.get("id"));
                    // 医生标识
                    json.put("code", doctor.get("code"));
                    // 医生姓名
                    json.put("name", doctor.get("name"));
                    // 所在医院名称
                    json.put("hospital", doctor.get("hospital"));
                    // 所在医院名称
                    json.put("hospital_name", doctor.get("hospital_name"));
                    // 科室名称
                    json.put("dept_name", (doctor.get("dept_name") == null ||
                            org.apache.commons.lang3.StringUtils.isEmpty(doctor.get("dept_name").toString())) ? " " : doctor.get("dept_name"));
                    json.put("level", doctor.get("level") );
                    json.put("job", doctor.get("job") );
                    // 职称名称
                    json.put("job_name", (doctor.get("job_name") == null ||
                            org.apache.commons.lang3.StringUtils.isEmpty(doctor.get("job_name").toString())) ? " " : doctor.get("job_name"));
                    // 头像
                    json.put("photo", doctor.get("photo"));
                    // 简介
                    json.put("introduce", doctor.get("introduce"));
                    // 专长
                    json.put("expertise", doctor.get("expertise"));
                    json.put("flag", doctors.contains(String.valueOf(doctor.get("code"))) ? true : false);
                    json.put("fixed", one != null && String.valueOf(doctor.get("code")).equals(one.getDoctor()) ? true : false);
                    //出诊费用
                    json.put("fee", doctor.get("fee"));
                    array.add(json);
                }
            }
            // 排序
            Collections.sort(array, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    Integer flag1 = (Boolean)o1.get("flag") ? 2 : 1;
                    Integer flag2 = (Boolean)o2.get("flag") ? 2 : 1;
                    if (flag1 - flag2 > 0) {
                        return -1;
                    } else if (flag1 - flag2 < 0) {
                        return 1;
                    } else {return 0;}
                }
            });
            Collections.sort(array, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    Integer fixed = (Boolean)o1.get("fixed") ? 2 : 1;
                    Integer fixed2 = (Boolean)o2.get("fixed") ? 2 : 1;
                    int sort = fixed - fixed2;
                    if (sort > 0) {
                        return -1;
                    } else if (sort < 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    @GetMapping(value = "queryBriefList")
    @ApiOperation(value = "调度员查询工单列表")
    public String queryBriefList(
            @ApiParam(name = "dispatcher", value = "调度员code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "hospital", value = "调度员所在机构code") @RequestParam(value = "hospital", required = true) String hospital,
            @ApiParam(name = "orderNumber", value = "工单号") @RequestParam(value = "orderNumber", required = false) String orderNumber,
            @ApiParam(name = "patientName", value = "工单服务对象姓名") @RequestParam(value = "patientName", required = false) String patientName,
            @ApiParam(name = "phone", value = "发起工单的居民的联系方式") @RequestParam(value = "phone", required = false) String phone,
            @ApiParam(name = "status", value = "工单状态") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "patientType", value = "居民类型") @RequestParam(value = "patientType", required = false) String patientType,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.queryBriefList(dispatcher,hospital, orderNumber, patientName, phone, status,patientType, page, size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            int count = result.getIntValue(ResponseContant.count);
            JSONObject object = new JSONObject();
            object.put("total",count);
            object.put("detailModelList",result.get(ResponseContant.resultMsg));
            object.put("currPage",page);
            object.put("pageSize",size);
            return write(200,"查询成功","data",object);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @GetMapping(value = "queryDoctorList")
    @ApiOperation(value = "服务人员列表(医生列表)")
    public String queryDoctorList(
            @ApiParam(name = "town", value = "调度员所在的机构code") @RequestParam(value = "town", required = true) String town,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = false) String doctorName,
            @ApiParam(name = "status", value = "医生接单状态,状态为全部时不传") @RequestParam(value = "status", required = false) String status,
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.queryDoctorList(patient,town, doctorName, status, page, size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            int count = result.getIntValue(ResponseContant.count);
            JSONObject object = new JSONObject();
            object.put("total",count);
            if (count > 0){
                object.put("detailModelList",result.get(ResponseContant.resultMsg));
            }else {
                List list = new ArrayList();
                object.put("detailModelList",list);
            }
            object.put("currPage",page);
            object.put("pageSize",size);
            return write(200,"查询成功","data",object);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @GetMapping(value = "queryDoctorListNotStopped")
    @ApiOperation(value = "服务人员列表(可接单状态的医生列表)")
    public String queryDoctorListWithNotStopped(
            @ApiParam(name = "patient", value = "服务对象code", required = true) @RequestParam(value = "patient") String patient,
            @ApiParam(name = "hospital", value = "机构code", required = true) @RequestParam(value = "hospital") String hospital,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.queryDoctorListWithNotStopped(patient,hospital,page, size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            int count = result.getIntValue(ResponseContant.count);
            JSONObject object = new JSONObject();
            object.put("total",count);
            object.put("detailModelList",result.get(ResponseContant.resultMsg));
            object.put("currPage",page);
            object.put("pageSize",size);
            return write(200,"查询成功","data",object);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @PostMapping(value = "sendOrderToDoctor")
    @ApiOperation(value = "调度员给医生派单")
    public String sendOrderToDoctor(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "调度员备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(name = "dispatcher", value = "调度员code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "dispathcherName", value = "调度员姓名") @RequestParam(value = "dispathcherName", required = true) String dispathcherName,
            @ApiParam(name = "doctor", value = "医生code") @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = true) String doctorName,
            @ApiParam(name = "doctorJobName", value = "医生职称") @RequestParam(value = "doctorJobName", required = true) String doctorJobName) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.sendOrderToDoctor(orderId, remark,dispatcher,dispathcherName, doctor, doctorName ,doctorJobName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error( -1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"派单成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"派单失败");
    }
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
    public String cancelOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "type", value = "取消类型:1-调度员主动取消,2-居民取消, 3-医生取消") @RequestParam(value = "type", required = true) int type,
            @ApiParam(name = "reason", value = "取消理由") @RequestParam(value = "reason", required = false) String reason,
            @ApiParam(name = "dispatcher", value = "取消工单的调度员(只允许调度员来操作)") @RequestParam(value = "dispatcher", required = false) String dispatcher,
            @ApiParam(name = "dispathcherName", value = "调度员姓名") @RequestParam(value = "dispathcherName", required = false) String dispatcherName) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.cancelOrder(orderId, type, reason,dispatcher,dispatcherName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"取消成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"取消失败");
    }
    @PostMapping(value = "transOrderToOtherOrg")
    @ApiOperation(value = "调度员将工单转接给其他机构")
    public String transOrderToOtherOrg(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "hospital", value = "机构code") @RequestParam(value = "hospital", required = true) String hospital) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.transOrderToOtherOrg(orderId, hospital);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"转接成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"转接失败");
    }
    @PostMapping(value = "dispatcherIntoTopic")
    @ApiOperation(value = "调度员进入会话")
    public String dispatcherIntoTopic(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "hospitalName", value = "机构名称", required = true) @RequestParam String hospitalName,
            @ApiParam(name = "dispatcher", value = "调度员code", required = true) @RequestParam String dispatcher,
            @ApiParam(name = "dispatcherName", value = "调度员姓名", required = true) @RequestParam  String dispatcherName
    ) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.dispatcherIntoTopic(orderId,hospitalName,dispatcher,dispatcherName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"转接成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"转接失败");
    }
    @PostMapping(value = "saveLastDispatcher")
    @ApiOperation(value = "保存最后一个回复内容的调度员到工单")
    public String saveLastDispatcher(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "dispatcher", value = "调度员code", required = true) @RequestParam String dispatcher,
            @ApiParam(name = "dispatcherName", value = "调度员姓名", required = true) @RequestParam  String dispatcherName
    ) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.saveLastDispatcher(orderId,dispatcher,dispatcherName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"保存成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"保存失败");
    }
    @PostMapping(value = "updateOrderCardInfo")
    @ApiOperation(value = "更新预约简要信息")
    public String updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"保存成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"保存失败");
    }
    @PostMapping(value = "updateServiceStatus")
    @ApiOperation(value = "更新预约服务项目类型")
    public String updateServiceStatus(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        try{
            Integer result = doorOrderService.updateServiceStatus(id);
            if (result<1) {
                return error(-1,"修改服务类型失败");
            }
            return write(200,"修改成功","data",result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"修改失败");
    }
    @GetMapping(value = "orderIsCancel")
    @ApiOperation(value = "查看消息时判断工单是否取消")
    public String orderIsCancel(
            @ApiParam(name = "messageId", value = "消息id", required = true) @RequestParam String messageId) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.orderIsCancel(messageId);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1,result.getString(ResponseContant.resultMsg));
            }
            return write(200,"查询成功","data",result.get(ResponseContant.resultMsg));
        }catch (Exception e){
            e.printStackTrace();
        }
        return error(-1,"查询失败");
    }
    @GetMapping(value = "getWorkingTimeByDoctor")
    @ResponseBody
    @ApiOperation("获取居民家签机构的上班时间")
    public String getWorkingTimeByPatient(@RequestParam String patient) {
        try {
            return write(200, "查询成功", "data", hospitalService.getWorkingTimeByPatient(patient));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    @PostMapping(value = "cancelConclusion")
    @ResponseBody
    @ApiOperation("取消登记服务小结")
    public String cancelConclusion(@ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId) {
        try {
            wlyyDoorServiceOrderService.cancelConclusion(orderId);
            return write(200, "取消成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "取消失败");
        }
    }
    @PostMapping(value = "createPrescription")
    @ResponseBody
    @ApiOperation("上门服务前手工开方接口")
    public String createPrescription(@ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
                                     @ApiParam(name = "prescriptionCode", value = "处方单号,多个用逗号隔开", required = true) @RequestParam String prescriptionCode,
                                     @ApiParam(name = "commitPrescriptionCode", value = "已提交处方表code") @RequestParam(required = false) String commitPrescriptionCode) {
        try {
            JSONObject json = wlyyDoorServiceOrderService.createPrescription(orderId, prescriptionCode, commitPrescriptionCode);
            if(json.getInteger("status") == -1){
                return error(-1, json.getString("msg"));
            }
            return write(200, "开方完成");
        } catch (Exception e) {
            error(e);
            return error(-1, "开方失败");
        }
    }
    @PostMapping(value = "updateDoctorStatus")
    @ResponseBody
    @ApiOperation("更新医生地理位置状态")
    public String updateDoctorStatus(@ApiParam(name = "positionStatus", value = "医生地理位置状态", required = true) @RequestParam Integer positionStatus,
                                     @ApiParam(name = "position", value = "地理位置,用逗号隔开", required = false) @RequestParam String position) {
        try {
            wlyyDoorServiceOrderService.updateDoctorStatus(getUID(),positionStatus,position);
            return write(200, "更新完成");
        } catch (Exception e) {
            error(e);
            return error(-1, "更新失败");
        }
    }
    @GetMapping(value = "getPrescription")
    @ResponseBody
    @ApiOperation("获取长处方信息")
    public String getPrescription(@ApiParam(name="patient",value="居民code") @RequestParam(required = true) String patient,
                                  @ApiParam(name="visitDept",value="挂号科室编码") @RequestParam(required = false) String visitDept,
                                  @ApiParam(name="visitTimeFrom",value="开始时间") @RequestParam(required = false) String visitTimeFrom,
                                  @ApiParam(name="visitTimeEnd",value="结束时间") @RequestParam(required = false) String visitTimeEnd) {
        try {
            JSONArray json = doorPrescriptionService.getPrescription(getUID(), patient, visitDept, visitTimeFrom, visitTimeEnd);
            return write(200, "获取成功", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败");
        }
    }
    @PostMapping(value = "createDoorPrescription")
    @ResponseBody
    @ApiOperation("开方接口")
    public String createDoorPrescription(@ApiParam(name = "orderId", value = "订单id", required = true) @RequestParam String orderId,
                                         @ApiParam(name = "jsonData", value = "有关处方相关数据", required = true) @RequestParam String jsonData) {
        try {
            JSONObject jsonObject = doorPrescriptionService.createDoorPrescription(orderId, jsonData, getUID());
            if(jsonObject.getInteger("status") == 200) {
                return write(200, "开方成功", "data", jsonObject.get("data"));
            }else {
                return error(-1, jsonObject.getString("msg"));
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "开方失败");
        }
    }
    @GetMapping(value = "getPrescriptionByCode")
    @ResponseBody
    @ApiOperation("获取长处方详情")
    public String getPrescriptionByCode(@ApiParam(name = "recipeNo", value = "医嘱号",required = true)
                                        @RequestParam String recipeNo,
                                        @ApiParam(name = "patientCode", value = "居民code",required = true)
                                        @RequestParam String patientCode) {
        try {
            JSONObject json = doorPrescriptionService.getPrescriptionByCode(recipeNo, patientCode);
            return write(200, "获取成功", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败");
        }
    }
    @PostMapping(value = "cancelPrescriptionByCode")
    @ResponseBody
    @ApiOperation("取消开方")
    public String cancelPrescriptionByCode(@ApiParam(name = "prescriptionCode", value = "处方表code",required = true)
                                           @RequestParam String prescriptionCode) {
        try {
            JSONObject result = jwDoorPrescriptionService.fadeRecipeUnion(prescriptionCode, getUID());
            if(result.getInteger("status") == 200) {
                return write(200, "取消成功", "data", result.getString("msg"));
            }else {
                return error(-1, result.getString("msg"));
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "取消失败");
        }
    }
    @PostMapping(value = "skipPrescription")
    @ResponseBody
    @ApiOperation("跳过开方")
    public String skipPrescription(@ApiParam(name = "orderId", value = "订单id", required = true) @RequestParam String orderId) {
        try {
            doorPrescriptionService.skipPrescriptionByOrderId(orderId);
            return write(200, "成功跳过");
        } catch (Exception e) {
            error(e);
            return error(-1, "跳过失败");
        }
    }
    @RequestMapping(value = "/findDictByName", method = RequestMethod.GET)
    @ApiOperation(value = "药品列表")
    public String findDictByName(@ApiParam(name = "name", value = "药品名称(中文或拼音首字母查询)", defaultValue = "胰岛素")
                                 @RequestParam(value = "name", required = false) String name,
                                 @ApiParam(name = "subjectClass", value = "药品科目, 0101西成药,0103中草药", required = true)
                                 @RequestParam(value = "subjectClass") String subjectClass) {
        try {
            return write(200, "操作成功!", "data","");
//            return write(200, "操作成功!", "data",zyDictService.findDictByDoctorAndName(getUID(), name,null, subjectClass));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @PostMapping(value = "proxyCreate")
    @ApiOperation(value = "创建上门服务咨询--医生代预约")
    public String create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.proxyCreate(jsonData,getUID());
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1, result.getString(ResponseContant.resultMsg));
            }
            return write(200, "提交成功!","orderId",result.getString("orderId"));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, e.getMessage());
        }
    }
    @PostMapping(value = "proxyUpdate")
    @ApiOperation(value = "上门服务-工单编辑")
    public String proxyUpdate(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        try{
            JSONObject result = wlyyDoorServiceOrderService.proxyUpdate(jsonData,getUID());
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return error(-1, result.getString(ResponseContant.resultMsg));
            }
            return write(200, "修改成功!");
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, e.getMessage());
        }
    }
    @GetMapping(value = "getDoorPatientList")
    @ResponseBody
    @ApiOperation("获取代预约服务对象列表")
    public String getDoorPatientList(@ApiParam(name = "teamCode", value = "医生所在团队code", required = true) @RequestParam String teamCode,
                                     @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = false) String patientName,
                                     @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
                                     @RequestParam(value = "page") Integer page,
                                     @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "10",required = true)
                                     @RequestParam(value = "pageSize") Integer pageSize) {
        try {
            List<Map<String, Object>> list = wlyyDoorServiceOrderService.getDoorPatientList(teamCode, getUID(), patientName, page, pageSize);
            return write(200, "获取成功", "data", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败");
        }
    }
    @PostMapping(value = "saveAuthorizeImage")
    @ResponseBody
    @ApiOperation("保存电子健康卡图片")
    public String saveAuthorizeImage(@ApiParam(name = "orderId", value = "订单id", required = true) @RequestParam String orderId,
                                     @ApiParam(name = "authorizeImage", value = "电子健康卡授权图片", required = true) @RequestParam String authorizeImage) {
        try {
            doorPrescriptionService.saveAuthorizeImage(orderId, authorizeImage);
            return write(200, "保存成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "保存失败");
        }
    }
    //ca认证
    @ApiOperation("请求实名软证书并进行数字签名")
    @ResponseBody
    @RequestMapping(value = "/requestRealNameSoftCertAndSign", method = RequestMethod.POST)
    public String requestRealNameSoftCertAndSign(
            @ApiParam(required = true, name = "strRealNameSoftCertCalledPasswd", value = "证书被调用保护口令")
            @RequestParam(value = "strRealNameSoftCertCalledPasswd",required = true) String strRealNameSoftCertCalledPasswd,
            @ApiParam(name = "strOriginalData", value = "原文")
            @RequestParam(value = "strOriginalData",required = false) String strOriginalData,
            @ApiParam(required = true, name = "prescriptionCode", value = "处方code")
            @RequestParam(value = "prescriptionCode",required = true) String prescriptionCode){
        try {
            org.json.JSONObject jsonObject = jwDoorPrescriptionService.requestRealNameSoftCertAndSign(getUID(), strRealNameSoftCertCalledPasswd, strOriginalData, prescriptionCode);
            return write(200, "获取信息成功!", "data", jsonObject);
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "uploadCaDigital",method = RequestMethod.POST)
    @ApiOperation("上传基位ca认证信息")
    public String uploadCaDigital(@ApiParam(name = "prescriptionCode", value = "处方code")
                                  @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode){
        try{
            JSONObject json = jwDoorPrescriptionService.uploadCaDigital(prescriptionCode);
            if(json.getInteger("status")==-1){
                return error(-1,json.getString("msg"));
            }
            return write(200,"上传ca认证信息成功");
        }catch (Exception e){
            error(e);
            return error(-1,"上传ca认证信息失败");
        }
    }
    @RequestMapping(value = "/getIcd10Info", method = RequestMethod.GET)
    @ApiOperation(value = "获取诊断结果")
    public String getIcd10Info(@RequestParam(required = false)
                               @ApiParam(value = "诊断结果关键字", name = "nameKey") String nameKey,
                               @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
                               @RequestParam(value = "page") Integer page,
                               @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "15",required = true)
                               @RequestParam(value = "pageSize") Integer pageSize) {
        try {
            return write(200, "操作成功!", "data", doorPrescriptionService.getIcd10Info(nameKey, page, pageSize));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @GetMapping("/getAdministratorStatusBarNum")
    @ApiOperation(value = "获取管理员顶部状态栏订单分类tab")
    public String getAdministratorStatusBarNum(
            @ApiParam(value = "服务机构", name = "hospital",required = false)
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(value = "角色0、医生,1、管理员", name = "isManage",required = false)
            @RequestParam(value = "isManage", required = false) String isManage) {
        try {
            if(StringUtils.isEmpty(isManage)){
                isManage = getCurrentRoleIsManange();
            }
            if ("1".equals(isManage) && StringUtils.isBlank(hospital)){
                //如果是管理员并且未筛选机构,就默认展示其管理下所有机构
                String level = getCurrentRoleLevel();
                String currentRoleCode = getCurrentRoleCode();
                if(level.equals("2")) {
                    //市管理员
                    hospital = currentRoleCode.substring(0, currentRoleCode.length() - 2) + "%";
                }else if(level.equals("3")){
                    //区管理员
                    hospital = currentRoleCode + "%";
                }else if (level.equals("4")){
                    //机构管理员
                    hospital = currentRoleCode;
                }
            }else if(StringUtils.isNotBlank(hospital) && hospital.length() < 10){
                hospital += "%";
            }
            Map<String, String> map = doorOrderService.getAdministratorStatusBarNum(hospital);
            return write(200, "获取成功", "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @ApiOperation("导出服务小结到word")
    @RequestMapping(value = "exportConclusion", method = RequestMethod.GET)
    public void writeWordFile(@ApiParam(name = "urlString", value = "链接地址") @RequestParam(required = false) String urlString,
                              @ApiParam(name = "orderId", value = "订单id", required = true) @RequestParam String orderId,
                              HttpServletResponse response) {
        try {
            //导出路径
            WlyyDoorServiceOrderDO orderDO = doorOrderService.findById(orderId);
            response.setContentType("application/msword");
            response.setCharacterEncoding("utf-8");
            // 生成临时文件名称
            String fileName = orderDO.getPatientName() + "服务小结.doc";
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            OutputStream os = response.getOutputStream();
            //获取相对路径
            String pathName = DoorOrderController.class.getResource("/").getPath().replaceFirst("/", "");
            pathName = pathName.replace("target/classes/", "src/main/resources/conclusion.mht");
            Document doc = Jsoup.parse(new File(pathName), "UTF-8");
            String html = doorOrderService.handleData(doc,orderId);
            byte b[] = html.getBytes();
            ByteArrayInputStream bais = new ByteArrayInputStream(b);
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            poifs.writeFilesystem(os);
            os.flush();
            os.close();
            bais.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation("推送知情同意書")
    @RequestMapping(value = "/sendInformedConsent" , method = RequestMethod.GET)
    public String sendInformedConsent(   @ApiParam(value = "医生code", name = "doctor")
                                         @RequestParam(value = "doctor", required = true) String doctor,
                                         @ApiParam(value = "工单id", name = "orderId")
                                         @RequestParam(value = "orderId", required = false) String orderId,
                                         @ApiParam(name = "level", value = "医院等级,1.三级医院,2.二级医院,3.一级及以下")
                                         @RequestParam(value = "level",required = true)Integer level ){
        try {
            // 没有提供工单id的情况下,则获取该医生当前最新一条的工单
            if (StringUtils.isEmpty(orderId)) {
                // 根据接单医生code获取最近一次服务orderId
                orderId = doorOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return error(-1, "获取失败, 该医生暂无工单" );
                }
            }
            // 根据orderId获取工单信息
            WlyyDoorServiceOrderDO doorServiceOrderDO = doorOrderService.getDoorServiceOrderById(orderId, level);
            if(doorServiceOrderDO != null){
                doorServiceOrderDO.getServeDesc();//服务描述
                doorServiceOrderDO.getServeAddress();//服务地址
                doorServiceOrderDO.getDoctorArrivingTime();//服务时间
                doorServiceOrderDO.getPatientName();//服务对象
                doorServiceOrderDO.getPatientPhone();//服务电话
                doorServiceOrderDO.getIsPatientConfirm();//当前状态
                Integer success = doorOrderService.sendInformedConsent(orderId , doorServiceOrderDO.getServeDesc(),doctor);
                wlyyDoorServiceOrderService.orderMsgTask(orderId);
                if(success == 1){
                        return write(200, "知情同意书推送成功", "data", doorServiceOrderDO);
                }else {
                    return write(-1,"知情同意书推送失败");
                }
            }else {
                return write(-1,"请检查工单");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

+ 783 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/doctor/DoorStatisticAnalyzeController.java

@ -0,0 +1,783 @@
package com.yihu.jw.door.controller.doctor;
import com.yihu.jw.door.controller.BaseController;
import com.yihu.jw.door.service.statics.DoorStatisticAnalyzeService;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
 * @author liuwenbin on 2019/3/21.
 */
@Controller
@RequestMapping(value = "/doctor/statisticAnalyze", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-上门服务-统计分析")
public class DoorStatisticAnalyzeController extends BaseController {
    @Autowired
    private DoorStatisticAnalyzeService doorStatisticAnalyzeService;
    @Autowired
    ElasticsearchUtil elasticsearchUtil;
    /*********************************************app端 start*******************************************************************/
    @GetMapping("/doorQualificationAnalyzeHead")
    @ResponseBody
    @ApiOperation(value = "资质分析-app-头部")
    public String doorQualificationAnalyzeHead(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            Map<String,Object> result = doorStatisticAnalyzeService.doorQualificationAnalyzeHead(area,startDate,endDate,level);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorQualificationAnalyzeList")
    @ResponseBody
    @ApiOperation(value = "资质分析-app-列表")
    public String doorQualificationAnalyzeList(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(required = false) String lowLevel,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorQualificationAnalyzeList(area,startDate,endDate,level,lowLevel);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/subsidyExpenseList")
    @ResponseBody
    @ApiOperation(value = "补助费用-app-列表")
    public String subsidyExpenseList(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(required = false) String lowLevel,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.subsidyExpenseList(area,startDate,endDate,level,lowLevel);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/subsidyExpenseHead")
    @ResponseBody
    @ApiOperation(value = "补助费用-app-头部")
    public String subsidyExpenseHead(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            Map<String,Object> result = doorStatisticAnalyzeService.subsidyExpenseHead(area,startDate,endDate,level);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorServiceOrderAnalyzeHead")
    @ResponseBody
    @ApiOperation(value = "服务工单分析-app-头部")
    public String doorServiceOrderAnalyzeHead(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            Map<String,Object> result = doorStatisticAnalyzeService.doorServiceOrderAnalyzeHead(area,startDate,endDate, type,level);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorServiceOrderAnalyzeList")
    @ResponseBody
    @ApiOperation(value = "服务工单分析-app-列表")
    public String doorServiceOrderAnalyzeList(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(required = false) String lowLevel,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorServiceOrderAnalyzeList(area,startDate,endDate, type,level,lowLevel);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorResponseAnalyzeHead")
    @ResponseBody
    @ApiOperation(value = "响应速度分析-app-头部")
    public String doorResponseAnalyzeHead(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "roleType", value = "1、调度员,2、服务医生",required = true)
            @RequestParam(value = "roleType", required = true) Integer roleType,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            Map<String,Object> result = doorStatisticAnalyzeService.doorResponseAnalyzeHead(area,startDate,endDate,roleType, level);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorResponseAnalyzeList")
    @ResponseBody
    @ApiOperation(value = "响应速度分析-app-列表")
    public String doorResponseAnalyzeList(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = true)
            @RequestParam(value = "area", required = true) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(required = false) String lowLevel,
            @ApiParam(name = "roleType", value = "1、调度员,2、服务医生",required = true)
            @RequestParam(value = "roleType", required = true) Integer roleType,
            @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorResponseAnalyzeList(area,startDate,endDate,roleType, level,lowLevel);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    /*********************************************app端 end *******************************************************************/
    @GetMapping("/doorQualificationAnalyze")
    @ResponseBody
    @ApiOperation(value = "资质分析")
    public String doorQualificationAnalyze(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorQualificationAnalyze(area,startDate,endDate);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorResponseAnalyze")
    @ResponseBody
    @ApiOperation(value = "响应速度分析")
    public String doorResponseAnalyze(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "roleType", value = "1、调度员,2、服务医生",required = true)
            @RequestParam(value = "roleType", required = true) Integer roleType,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorResponseAnalyze(area,startDate,endDate,roleType, type);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/doorServiceOrderAnalyze")
    @ResponseBody
    @ApiOperation(value = "服务工单分析")
    public String doorServiceOrderAnalyze(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.doorServiceOrderAnalyze(area,startDate,endDate, type);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    @GetMapping("/subsidyExpense")
    @ResponseBody
    @ApiOperation(value = "补助费用")
    public String subsidyExpense(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            List<Map<String,Object>> result = doorStatisticAnalyzeService.subsidyExpense(area,startDate,endDate);
            return write(200,"获取成功!","data",result);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"当前时间段还未统计");
        }
    }
    /*********************************************导出excel*******************************************************************/
    @ApiOperation(value = "资质分析导出excel")
    @GetMapping(value = "/doorQualificationAnalyzeExport")
    public void doorQualificationAnalyzeExport(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            HttpServletResponse response
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            doorStatisticAnalyzeService.doorQualificationAnalyzeExport(area,startDate,endDate,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "响应速度分析导出excel")
    @GetMapping(value = "/doorResponseAnalyzeExport")
    public void doorResponseAnalyzeExport(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "roleType", value = "1、调度员,2、服务医生",required = true)
            @RequestParam(value = "roleType", required = true) Integer roleType,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type,
            HttpServletResponse response
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            doorStatisticAnalyzeService.doorResponseAnalyzeExport(area,startDate,endDate,roleType,response, type);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "补助费用导出excel")
    @GetMapping(value = "/subsidyExpenseExport")
    public void subsidyExpenseExport(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            HttpServletResponse response
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            doorStatisticAnalyzeService.subsidyExpenseExport(area,startDate,endDate,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "服务工单分析导出excel")
    @GetMapping(value = "/doorServiceOrderAnalyzeExport")
    public void doorServiceOrderAnalyzeExport(
            @ApiParam(name = "area", value = "区域code:如思明区350203",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "type", value = "发起类型(1本人发起 2家人待预约 3医生代预约)",required = false)
            @RequestParam(value = "type", required = false) Integer type,
            HttpServletResponse response
    ){
        try{
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            doorStatisticAnalyzeService.doorServiceOrderAnalyzeExport(area,startDate,endDate,response, type);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "上门服务工单总体分析")
    @GetMapping(value = "/doorAggregateAnalysis")
    @ResponseBody
    public String doorAggregateAnalysis(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            //默认显示本月
            if(StringUtils.isEmpty(startDate)){
                startDate = DateUtil.getCurMonthFirstDayShort();
            }
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            Map<String,Object> map = doorStatisticAnalyzeService.doorAggregateAnalysis(area,level, startDate,endDate);
            return write(200, "查询成功", "data", map);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "获取上门服务疾病分析")
    @GetMapping(value = "/getDoorDiagnosisAnalysis")
    @ResponseBody
    public String getDoorDiagnosisAnalysis(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "page", value = "第几页",required = true)
            @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(name = "pageSize", value = "页面大小",required = true)
            @RequestParam(value = "pageSize", required = true) Integer pageSize){
        try{
            //默认显示本月
            if(StringUtils.isEmpty(startDate)){
                startDate = DateUtil.getCurMonthFirstDayShort();
            }
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            return write(200, "查询成功", "data", doorStatisticAnalyzeService.getOrderByDiagnosis(area, level, startDate, endDate, page, pageSize));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "获取上门服务服务项目分析")
    @GetMapping(value = "/getDoorDrugCodeAnalysis")
    @ResponseBody
    public String getDoorDrugCodeAnalysis(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name = "subjectClass", value = "科目类别,010开头为药品,020为服务项目",required = false)
            @RequestParam(value = "subjectClass", required = false) String subjectClass,
            @ApiParam(name = "page", value = "第几页",required = true)
            @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(name = "pageSize", value = "页面大小",required = true)
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            //默认显示本月
            if(StringUtils.isEmpty(startDate)){
                startDate = DateUtil.getCurMonthFirstDayShort();
            }
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            return write(200, "查询成功", "data", doorStatisticAnalyzeService.getGroupbyDrugCodeList(area, level, subjectClass, page, pageSize, startDate, endDate));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 服务工单排行
     * @param endDate     结束时间
     * @param area        父code
     * @param level       等级   4 市  3区  2社区 1团队
     * @param sort        排序 1倒叙 2是 正序
     * @param lowLevel   等级 1:团队 2社区机构 3区级 4市级
     * @return
     */
    @ApiOperation(value = "获取上门服务工单排行列表")
    @GetMapping("/order_lowlevel_all")
    @ResponseBody
    public String getOrderLowlevelAll(@ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
                                          @RequestParam(value = "startDate") String startDate,
                                      @RequestParam(required = true) String endDate,
                                           @RequestParam(required = true) String area,
                                           @RequestParam(required = true) int level,
                                           @RequestParam(required = true) int sort,
                                           @RequestParam(required = false) String lowLevel,
                                           @RequestParam(required = false) String year) {
        try{
            lowLevel = String.valueOf(org.apache.commons.lang3.StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
            //新版与旧版统计适配
            level = elasticsearchUtil.changeLevel(level);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(lowLevel)) {
                lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel)) + "";
            }
            JSONObject result = new JSONObject();
            result.put("index_121",doorStatisticAnalyzeService.getOrderLowlevelAll(startDate, endDate, area, level, sort, lowLevel, year));
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /*******************************上门服务统计 1.6.8.3 版本 start **************************************************************/
    @ApiOperation(value = "上门服务分析-v1.6.8.3")
    @GetMapping(value = "/doorServiceAnalysis")
    @ResponseBody
    public String doorServiceAnalysis(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            Map<String,Object> map = doorStatisticAnalyzeService.doorServiceAnalysis(area,level, startDate,endDate);
            return write(200, "查询成功", "data", map);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "新增服务工单趋势-v1.6.8.3")
    @GetMapping(value = "/serviceOrderTrend")
    @ResponseBody
    public String serviceOrderTrend(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name="interval",value="统计类型:1按天,2按周,3按月",defaultValue = "")
            @RequestParam(required = true) String interval,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = true)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            List<Map<String,Object>> list = doorStatisticAnalyzeService.serviceOrderTrend(area,level, startDate,endDate,interval);
            return write(200, "查询成功", "data", list);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 服务工单排行
     * @param endDate     结束时间
     * @param area        父code
     * @param level       等级   4 市  3区  2社区 1团队
     * @param lowLevel   等级 1:团队 2社区机构 3区级 4市级
     * @return
     */
    @ApiOperation(value = "获取上门服务工单排行列表-v1.6.8.3")
    @GetMapping("doorServiceOrderLowlevelAll")
    @ResponseBody
    public String doorServiceOrderLowlevelAll(@ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
                                      @RequestParam(value = "startDate") String startDate,
                                      @RequestParam(required = true) String endDate,
                                      @RequestParam(required = true) String area,
                                      @RequestParam(required = false) String slaveKey1,
                                      @RequestParam(required = true) int level,
                                      @RequestParam(required = true) String lowLevel) {
        try{
            lowLevel = String.valueOf(org.apache.commons.lang3.StringUtils.isEmpty(lowLevel) ? (level - 1) : lowLevel);
            JSONObject result = new JSONObject();
            result.put("index_177",doorStatisticAnalyzeService.doorServiceOrderLowlevelAll(startDate, endDate, area, level,slaveKey1, lowLevel));
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "获取上门服务服务项目分析-v1.6.8.3")
    @GetMapping(value = "doorServiceItemAnalysis")
    @ResponseBody
    public String doorServiceItemAnalysis(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name = "pageSize", value = "页面大小,默认6 返回全部传999",required = true)
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = false)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = false)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            //默认显示本月
            if(StringUtils.isEmpty(startDate)){
                startDate = DateUtil.getCurMonthFirstDayShort();
            }
            if(StringUtils.isEmpty(endDate)){
                endDate = DateUtil.getStringDate();
            }
            return write(200, "查询成功", "data", doorStatisticAnalyzeService.doorServiceItemAnalysis(area, level, pageSize, startDate, endDate));
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /*******************************上门服务统计 1.6.8.3 版本 end **************************************************************/
    /*******************************入户访视统计 1.6.8.3 版本 start **************************************************************/
    @ApiOperation("入户访视统计-获取总量头部-v1.6.8.3")
    @GetMapping("getHomeVisitTotalHead")
    @ResponseBody
    public String getHomeVisitTotalHead(@ApiParam(name="startDate",value="开始时间",defaultValue = "")@RequestParam(required = true) String startDate,
                                        @ApiParam(name="endDate",value="结束时间",defaultValue = "")@RequestParam(required = true) String endDate,
                                        @ApiParam(name="slaveKey1",value="类型 5 产后,6 新生儿,7 严重精神疾病,8 80岁以上老人,9 肺结核",defaultValue = "")
                                            @RequestParam(required = false) String slaveKey1,
                                        @ApiParam(name="area",value="区域code",defaultValue = "")@RequestParam(required = true) String area,
                                        @ApiParam(name="level",value="1 省 2 市 3 区县 4 机构 5团队",defaultValue = "")@RequestParam(required = true) Integer level) {
        try {
            JSONObject jsonObject = doorStatisticAnalyzeService.getHomeVisitTotalHead(startDate,endDate,area,level,slaveKey1);
            return write(200, "查询成功", "data", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "通用单条折线图趋势-v1.6.8.3")
    @GetMapping(value = "generalSingleLineChartTrend")
    @ResponseBody
    public String generalSingleLineChartTrend(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name="index",value="指标",defaultValue = "")@RequestParam(required = true) String index,
            @ApiParam(name="interval",value="统计类型:1按天,2按周,3按月",defaultValue = "")
            @RequestParam(required = true) String interval,
            @ApiParam(name="slaveKey1",value="index=150 类型 5 产后,6 新生儿,7 严重精神疾病,8 80岁以上老人,9 肺结核",defaultValue = "")
            @RequestParam(required = false) String slaveKey1,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = true)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            List<Map<String,Object>> list = doorStatisticAnalyzeService.generalSingleLineChartTrend(area,level,index,startDate,endDate,interval,slaveKey1);
            return write(200, "查询成功", "data", list);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "通用饼图-v1.6.8.3")
    @GetMapping(value = "generalPieChartTrend")
    @ResponseBody
    public String generalPieChartTrend(
            @ApiParam(name = "area", value = "区域code:如思明区350203,团队641",required = false)
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "level", value = "等级,2市  3区  4社区 5团队",required = false)
            @RequestParam(required = true) int level,
            @ApiParam(name="index",value="指标",defaultValue = "")@RequestParam(required = true) String index,
            @ApiParam(name="slaveKey1",value="index=150 类型 5 产后,6 新生儿,7 严重精神疾病,8 80岁以上老人,9 肺结核",defaultValue = "")
            @RequestParam(required = false) String slaveKey1,
            @ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
            @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "搜索,结束时间",required = true)
            @RequestParam(value = "endDate", required = false) String endDate){
        try{
            List<Map<String,Object>> list = doorStatisticAnalyzeService.generalPieChartTrend(area,level,index,startDate,endDate,slaveKey1);
            return write(200, "查询成功", "data", list);
        }catch (Exception e){
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    @ApiOperation(value = "通用下砖接口 区-社区-团队-v1.6.8.3")
    @GetMapping("generalLowlevelAll")
    @ResponseBody
    public String generalLowlevelAll(@ApiParam(name = "startDate", value = "搜索,开始时间",required = true)
                                     @RequestParam(value = "startDate") String startDate,
                                     @RequestParam(required = true) String endDate,
                                     @RequestParam(required = true) String area,
                                     @ApiParam(name="index",value="指标",defaultValue = "")@RequestParam(required = true) String index,
                                     @ApiParam(name="slaveKey1",value="index=150 类型 5 产后,6 新生儿,7 严重精神疾病,8 80岁以上老人,9 肺结核",defaultValue = "")
                                     @RequestParam(required = false) String slaveKey1,
                                     @RequestParam(required = true) int level,
                                     @RequestParam(required = true) String lowLevel) {
        try{
            List<Map<String, Object>> resultList = doorStatisticAnalyzeService.generalLowlevelAll(startDate, endDate, area, level,index,slaveKey1, lowLevel);
            return write(200, "查询成功", "data", resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /*******************************入户访视统计 1.6.8.3 版本 end **************************************************************/
}

+ 117 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/PatientDoorServiceApplicationController.java

@ -0,0 +1,117 @@
package com.yihu.jw.door.controller.patient;
import com.yihu.jw.door.controller.BaseController;
import com.yihu.jw.door.service.DoorServiceApplicationService;
import com.yihu.jw.entity.door.WlyyDoorServiceApplicationDo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
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;
/**
 * Created by zdm on 2019/3/13.
 */
@RestController
@RequestMapping(value = "/patient/onsiteService", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "居民端-上门服务")
public class PatientDoorServiceApplicationController extends BaseController {
    @Autowired
    private DoorServiceApplicationService doorServiceApplicationService;
    @RequestMapping(value = "findPatientOnsiteService", method = RequestMethod.GET)
    @ApiOperation(value = "首页获取居民上门服务开通状况及取消预约次数")
    public String findPatientOnsiteService(
            @ApiParam(name = "patientCode", value = "当前居民code")
            @RequestParam(value = "patientCode",required = false)String patientCode) {
        try {
            if(StringUtils.isBlank(patientCode)){
                patientCode=getRepUID();
            }
            JSONObject jsonObject = doorServiceApplicationService.findPatientOnsiteService(patientCode);
            return write(200, "获取成功", "data", jsonObject);
        } catch (Exception ex) {
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
    @RequestMapping(value = "getPatientFamilyMembersInfo", method = RequestMethod.GET)
    @ApiOperation(value = "获取当前居民家庭成员信息")
    public String getPatientFamilyMembersInfo(
            @ApiParam(name = "patientCode", value = "当前居民code")
            @RequestParam(value = "patientCode",required = false)String patientCode){
        try {
            if(StringUtils.isBlank(patientCode)){
                patientCode=getLastUid();
            }
            JSONArray jsonArray= doorServiceApplicationService.getPatientFamilyMembers(patientCode);
            return write(200, "获取成功", "data", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取失败!"+e.getMessage());
        }
    }
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ApiOperation(value = "开通服务资格")
    public String create(
            @ApiParam(name = "jsonData", value = "开通服务资格内容jsonData")
            @RequestParam(value = "jsonData",required = true)String jsonData,
            @ApiParam(name = "patientCode", value = "patientCode")
            @RequestParam(value = "patientCode",required = false)String patientCode){
        try {
            if(StringUtils.isBlank(patientCode)){
                patientCode=getRepUID();
            }
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.create("1",jsonData,patientCode);
            return write(200, "获取成功", "data", wlyyDoorServiceApplicationDo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取失败!"+e.getMessage());
        }
    }
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ApiOperation(value = "变更开通服务资格")
    public String update(
            @ApiParam(name = "jsonData", value = "开通服务资格内容jsonData")
            @RequestParam(value = "jsonData",required = true)String jsonData,
            @ApiParam(name = "patientCode", value = "patientCode")
            @RequestParam(value = "patientCode",required = false)String patientCode){
        try {
            if(StringUtils.isBlank(patientCode)){
                patientCode=getRepUID();
            }
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.update(jsonData,patientCode);
            return write(200, "获取成功", "data", wlyyDoorServiceApplicationDo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "获取失败!"+e.getMessage());
        }
    }
    @RequestMapping(value = "findPatientOnsiteServiceStatus", method = RequestMethod.GET)
    @ApiOperation(value = "获取居民审核状态: -1删除,0审核中,1未通过,2审核通过,3已过期")
    public String findPatientOnsiteServiceStatus(
            @ApiParam(name = "patientCode", value = "当前居民code")
            @RequestParam(value = "patientCode",required = false)String patientCode) {
        try {
            if(StringUtils.isBlank(patientCode)){
                patientCode=getRepUID();
            }
            Integer status= doorServiceApplicationService.findOnsiteServiceStatusByPatient(patientCode);
            return write(200, "获取成功", "data", status);
        } catch (Exception ex) {
            return error(-1, "获取失败!"+ex.getMessage());
        }
    }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorCommentController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorCommentService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 服务工单评价控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorComment")
@Api(value = "服务工单评价管理", description = "服务工单评价管理服务接口") //, tags = {"健康商城-服务工单评价管理服务接口"}
public class WlyyDoorCommentController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorCommentService wlyyDoorCommentService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorCommentService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorCommentService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorCommentService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorCommentService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorCommentService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorCommentDoctorController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorCommentDoctorService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 服务工单中的医生评价控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorCommentDoctor")
@Api(value = "服务工单中的医生评价管理", description = "服务工单中的医生评价管理服务接口") //, tags = {"健康商城-服务工单中的医生评价管理服务接口"}
public class WlyyDoorCommentDoctorController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorCommentDoctorService wlyyDoorCommentDoctorService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorCommentDoctorService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorCommentDoctorService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorCommentDoctorService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorCommentDoctorService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorCommentDoctorService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorConclusionController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorConclusionService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 工单服务小结控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorConclusion")
@Api(value = "工单服务小结管理", description = "工单服务小结管理服务接口") //, tags = {"健康商城-工单服务小结管理服务接口"}
public class WlyyDoorConclusionController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorConclusionService wlyyDoorConclusionService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorConclusionService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorConclusionService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorConclusionService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorConclusionService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorConclusionService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorDoctorController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorDoctorService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 服务工单关联的医护人员控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorDoctor")
@Api(value = "服务工单关联的医护人员管理", description = "服务工单关联的医护人员管理服务接口") //, tags = {"健康商城-服务工单关联的医护人员管理服务接口"}
public class WlyyDoorDoctorController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorDoctorService wlyyDoorDoctorService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorDoctorService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorDoctorService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorDoctorService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorDoctorService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorDoctorService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorDoctorFeeController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorDoctorFeeDictService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 医生出诊费用字典控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorDoctorFee")
@Api(value = "医生出诊费用字典管理", description = "医生出诊费用字典管理服务接口") //, tags = {"健康商城-医生出诊费用字典管理服务接口"}
public class WlyyDoorDoctorFeeController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorDoctorFeeDictService wlyyDoorDoctorFeeDictService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorDoctorFeeDictService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorDoctorFeeDictService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorDoctorFeeDictService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorDoctorFeeDictService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorDoctorFeeDictService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorFeeDetailController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorFeeDetailService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 服务工单价格明细(服务项价格,医生出诊费用)控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorFeeDetail")
@Api(value = "服务工单价格明细(服务项价格,医生出诊费用)管理", description = "服务工单价格明细(服务项价格,医生出诊费用)管理服务接口") //, tags = {"健康商城-服务工单价格明细(服务项价格,医生出诊费用)管理服务接口"}
public class WlyyDoorFeeDetailController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorFeeDetailService wlyyDoorFeeDetailService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorFeeDetailService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorFeeDetailService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorFeeDetailService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorFeeDetailService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorFeeDetailService.search(fields, filters, sorts));
     }
}

+ 92 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorPatientConfirmLogController.java

@ -0,0 +1,92 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.WlyyDoorPatientConfirmLogService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 服务工单居民确认操作日志记录控制器
*
* @version
*
<pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
* @since 1.
*/
@RestController
@RequestMapping(value = "/wlyyDoorPatientConfirmLog")
@Api(value = "服务工单居民确认操作日志记录管理", description = "服务工单居民确认操作日志记录管理服务接口") //, tags = {"健康商城-服务工单居民确认操作日志记录管理服务接口"}
public class WlyyDoorPatientConfirmLogController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorPatientConfirmLogService wlyyDoorPatientConfirmLogService;
    @PostMapping(value = "create")
    @ApiOperation(value = "创建")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorPatientConfirmLogService.create(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
    @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
            wlyyDoorPatientConfirmLogService.delete(ids.split(","));
            return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update (@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) throws Exception {
        JSONObject result = wlyyDoorPatientConfirmLogService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
        return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "获取列表分页")
    public PageEnvelop page(
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
                @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
                @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
            JSONObject result = wlyyDoorPatientConfirmLogService.queryInfoList(fields,filters,sorts,page,size);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
            }
            int count = result.getIntValue(ResponseContant.count);
            return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public ListEnvelop list (
                @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
                @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
                @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
         return success(wlyyDoorPatientConfirmLogService.search(fields, filters, sorts));
     }
}

+ 315 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/controller/patient/WlyyDoorServiceOrderController.java

@ -0,0 +1,315 @@
package com.yihu.jw.door.controller.patient;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.service.DoorOrderService;
import com.yihu.jw.door.service.WlyyDoorPrescriptionService;
import com.yihu.jw.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 上门服务工单控制器
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0        2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
@RestController
@RequestMapping(value = "/patient/wlyyDoorServiceOrder")
@Api(value = "上门服务工单管理", description = "上门服务工单管理服务接口") //, tags = {"健康商城-上门服务工单管理服务接口"}
public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private DoorOrderService doorOrderService;
    @Autowired
    private WlyyDoorPrescriptionService doorPrescriptionService;
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Value("${wechat.accId}")
    private String accId;
    @PostMapping(value = "qucikSendIM")
    @ApiOperation(value = "通过IM向客户端推送消息")
    public Envelop qucikSendIM(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "sendId", value = "发送者code", required = false) @RequestParam String sendId,
            @ApiParam(name = "sendName", value = "发送者姓名", required = false) @RequestParam String sendName,
            @ApiParam(name = "contentType", value = "消息内容类型:1-文本信息,19-服务工单格式化消息", required = true) @RequestParam String contentType,
            @ApiParam(name = "content", value = "消息内容json", required = true) @RequestParam String content
    ) {
        int result = wlyyDoorServiceOrderService.qucikSendIM(orderId, sendId, sendName, contentType, content);
        if (result == -1) {
            return failed("发送失败!");
        }
        return success("发送成功");
    }
    @PostMapping(value = "create")
    @ApiOperation(value = "创建上门服务咨询")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        JSONObject result = new JSONObject();
        try{
            result = wlyyDoorServiceOrderService.create(jsonData);
        }catch (Exception e){
            e.printStackTrace();
            return failed(e.getMessage());
        }
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
        wlyyDoorServiceOrderService.delete(ids.split(","));
        return success("删除成功");
    }
    @PostMapping(value = "update")
    @ApiOperation(value = "更新")
    public Envelop update(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        JSONObject result = wlyyDoorServiceOrderService.update(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryDispatcherInfoByPatient")
    @ApiOperation(value = "获取居民所签约的机构的调度员信息")
    public Envelop queryDispatcherInfoByPatient(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
        JSONObject result = wlyyDoorServiceOrderService.queryDispatcherInfoByPatient(patient);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        int count = result.getIntValue(ResponseContant.count);
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "查询预约咨询记录")
    public PageEnvelop page(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "status", value = "工单状态,状态为全部时不传") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoList(patient, status, page, size);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
        }
        int count = result.getIntValue(ResponseContant.count);
        return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "queryInfoStatusCountList")
    @ApiOperation(value = "统计上门服务工单各状态下的数量列表")
    public Envelop queryInfoStatusCountList(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patient) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoStatusCountList(patient);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
    public Envelop list(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts) {
        List  result = new ArrayList();
        try {
            result = wlyyDoorServiceOrderService.search(fields, filters, sorts);
        } catch (ParseException e) {
            e.printStackTrace();
            return failed("查询列表失败!",-1);
        }
        return success(result);
    }
    @GetMapping(value = "queryOne")
    @ApiOperation(value = "查询单个咨询工单详情")
    public ObjEnvelop queryOneDetail(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        return success(wlyyDoorServiceOrderService.queryOneDetail(id));
    }
    @GetMapping(value = "twoDimensionalCode")
    @ApiOperation(value = "生成二维码接口")
    public Envelop twoDimensionalCode(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
/*        if (wlyyDoorServiceOrderService.twoDimensionalCode(id, weiXinAccessTokenUtils.getAccessToken()) != null){
            return success("获取二维码成功",200,wlyyDoorServiceOrderService.twoDimensionalCode(id, weiXinAccessTokenUtils.getAccessToken()));
        }else {
            return failed("获取二维码失败,请确认工单",-1);
        }*/
        return null;
    }
    @PostMapping(value = "updateOrderInfo")
    @ApiOperation(value = "查看知情同意书,修改状态")
    public Envelop updateOrderInfo(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        Integer orderInfo = wlyyDoorServiceOrderService.updateOrderInfo(id);
        if(orderInfo > 0){
            return success("状态修改成功",orderInfo);
        }
        return failed("状态修改失败",-1);
    }
    @GetMapping(value = "countPatientDoorTimes")
    @ApiOperation(value = "获取居民已经享受出诊服务的次数")
    public ObjEnvelop countPatientDoorTimes(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
        return success(wlyyDoorServiceOrderService.countPatientDoorTimes(patient));
    }
    @PostMapping(value = "payOrder")
    @ApiOperation(value = "居民付款")
    public ObjEnvelop payOrder(
            @ApiParam(name = "orderId ", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "payWay", value = "支付方式:1-微信支付,2-线下支付") @RequestParam(value = "payWay", required = true) int payWay) {
        return success(wlyyDoorServiceOrderService.payOrder(orderId, payWay));
    }
    @PostMapping("updateDoctorInfo")
    @ApiOperation(value = "修改保存服务医生(更新上门医生)")
    public Envelop updateDoctorInfo(
            @ApiParam(value = "jsonData", name = "jsonData")
            @RequestParam(value = "jsonData", required = false) String jsonData) {
        try {
            wlyyDoorServiceOrderService.updateDoctorInfo(jsonData);
            return success("修改成功");
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "updateOrderCardInfo")
    @ApiOperation(value = "更新预约简要信息")
    public Envelop updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryOneConclusion")
    @ApiOperation(value = "查询服务小结")
    public Envelop queryOneConclusion(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        return success(doorOrderService.getDoorConclusion(id, true));
    }
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
    public Envelop cancelOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "reason", value = "取消理由") @RequestParam(value = "reason", required = true) String reason) {
        JSONObject result = new JSONObject();
        try{
            result = wlyyDoorServiceOrderService.cancelOrder(orderId, 2, reason,null,null);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
        }catch (Exception e){
            e.printStackTrace();
            return failed(e.getMessage());
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryDoctorList")
    @ApiOperation(value = "服务人员列表(医生列表)")
    public PageEnvelop queryDoctorList(
            @ApiParam(name = "hospital", value = "居民签约机构code") @RequestParam(value = "hospital", required = true) String hospital,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName") String doctorName,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        JSONObject result = wlyyDoorServiceOrderService.queryDoctorList(getUID(),hospital, doctorName, null, page, size);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
        }
        int count = result.getIntValue(ResponseContant.count);
        return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @PostMapping("updateIsPatientConfirm")
    @ApiOperation(value = "更新居民确认情况状态")
    public Envelop updateIsPatientConfirm(
            @ApiParam(name = "orderId", value = "工单id")
            @RequestParam(value = "orderId") String orderId,
            @ApiParam(value = "isPatientConfirm", name = "isPatientConfirm")
            @RequestParam(value = "isPatientConfirm") Integer isPatientConfirm) {
        try {
            wlyyDoorServiceOrderService.updateIsPatientConfirm(orderId, isPatientConfirm);
            return success("修改成功");
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping(value = "getPrescriptionByCode")
    @ResponseBody
    @ApiOperation("获取长处方详情")
    public Envelop getPrescriptionByCode(@ApiParam(name = "recipeNo", value = "挂号号",required = true)
                                         @RequestParam String recipeNo) {
        try {
            JSONObject json = doorPrescriptionService.getPrescriptionByCode(recipeNo, getUID());
            return success(json);
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping(value = "getProxyPatientList")
    @ResponseBody
    @ApiOperation("获取代预约服务对象列表")
    public Envelop getProxyPatientList() {
        try {
            List<Map<String,Object>> list = wlyyDoorServiceOrderService.getProxyPatientList(getUID());
            return success(list);
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
}

+ 16 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoctorRegistrationDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.DoctorRegistration;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by wangpeiqiang on 2019/3/12.
 */
public interface DoctorRegistrationDao extends PagingAndSortingRepository<DoctorRegistration, Long> {
    @Query("select t from DoctorRegistration t order by t.createTime asc")
    List<DoctorRegistration> findAll();
}

+ 27 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoctorRegistrationTempDao.java

@ -0,0 +1,27 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.DoctorRegistrationTemp;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by wangpeiqiang on 2019/3/12.
 */
public interface DoctorRegistrationTempDao extends PagingAndSortingRepository<DoctorRegistrationTemp, Long> {
    DoctorRegistrationTemp findByCode(String code);
    int deleteByCode(String code);
    @Query("select t from DoctorRegistrationTemp t where t.content like ?1 order by t.createTime asc")
    List<DoctorRegistrationTemp> findAllRegistrationTemp(String filter);
    @Query("select t from DoctorRegistrationTemp t where t.doctor = ?1 and t.content like ?2 order by t.createTime asc")
    List<DoctorRegistrationTemp> findAllByDoctorCode(String doctor, String filter);
    @Query("select t from DoctorRegistrationTemp t where t.registration = ?1 and t.doctor is null order by t.createTime asc")
    List<DoctorRegistrationTemp> findRegistrationTempByRegistration(String code);
}

+ 24 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceApplicationDao.java

@ -0,0 +1,24 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorServiceApplicationDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务开通及审核
 */
public interface DoorServiceApplicationDao extends PagingAndSortingRepository<WlyyDoorServiceApplicationDo, Long>, JpaSpecificationExecutor<WlyyDoorServiceApplicationDo> {
    @Query("select os from WlyyDoorServiceApplicationDo os where os.patient=?1 and os.status=?2")
    List<WlyyDoorServiceApplicationDo> findByPatientAndStatus(String patient, Integer status);
    @Query("select os from WlyyDoorServiceApplicationDo os where os.patient=?1 and os.status<>-1")
    List<WlyyDoorServiceApplicationDo> findByPatientOrderByCreateTimeDesc(String patient);
}

+ 14 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceConfigureDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorServiceConfigureDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by zdm on 2019/3/14.
 * 服务权限配置
 */
public interface DoorServiceConfigureDao extends PagingAndSortingRepository<WlyyDoorServiceConfigureDo, Long>, JpaSpecificationExecutor<WlyyDoorServiceConfigureDo> {
}

+ 29 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceOrderDao.java

@ -0,0 +1,29 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
/**
 * Created by wxw on 2019/3/18.
 * 上门服务工单
 * @author wxw.
 */
public interface DoorServiceOrderDao extends PagingAndSortingRepository<WlyyDoorServiceOrderDO, String>, JpaSpecificationExecutor<WlyyDoorServiceOrderDO> {
    @Query("update WlyyDoorServiceOrderDO o set o.dispatcherResponseTime=?2 where o.id=?1 and o.dispatcherResponseTime is null")
    @Modifying
    int updateDispatcherResponseTime(String orderId, Date responseTime);
    @Query("update WlyyDoorServiceOrderDO o set o.serviceResponseTime=?2 where o.id=?1 and o.serviceResponseTime is null")
    @Modifying
    int updateServiceResponseTime(String orderId, Date responseTime);
    @Modifying
    @Query("update WlyyDoorServiceOrderDO o set o.prescriptionStatus = 0,o.status = 4  where o.id = ?1")
    void updatePrescriptionStatusAndStatusById(String orderId);
}

+ 28 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/DoorServiceVoucherDao.java

@ -0,0 +1,28 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorServiceVoucherDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Set;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务凭证
 */
public interface DoorServiceVoucherDao extends PagingAndSortingRepository<WlyyDoorServiceVoucherDo, Long>, JpaSpecificationExecutor<WlyyDoorServiceVoucherDo> {
    @Modifying
    @Query("update WlyyDoorServiceVoucherDo d set d.status=0 where d.serviceId=?1")
    void deleteByPatientCode(Long serviceId);
    List<WlyyDoorServiceVoucherDo> findByServiceIdAndStatusOrderBySortAsc(Long serviceId, Integer status);
    @Query("select d.typeValue from WlyyDoorServiceVoucherDo d where patientCode=?1 and status=1")
    List<String> findTypeValueByPatientCode(String patientCode);
    @Query(value = "select patient_code from wlyy_door_service_voucher where type in ?1 and status=1",nativeQuery = true)
    Set<String> queryByTypeIn(String[] type);
}

+ 25 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCancelLogDao.java

@ -0,0 +1,25 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorCancelLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 工单取消记录 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月26日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorCancelLogDao extends PagingAndSortingRepository<WlyyDoorCancelLogDO, String>, JpaSpecificationExecutor<WlyyDoorCancelLogDO>  {
    @Query(value = "select count(cl.id) from wlyy_door_cancel_log cl where cl.patient = ?1 and cl.cancel_type = 2 and DATE(cl.time) BETWEEN DATE_SUB(DATE(NOW()),INTERVAL DAYOFMONTH(NOW())-1 DAY) and LAST_DAY(NOW())",nativeQuery = true)
    int countCancelTimes(String patient);
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCommentDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorCommentDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 服务工单评价 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorCommentDao extends PagingAndSortingRepository<WlyyDoorCommentDO, Integer>, JpaSpecificationExecutor<WlyyDoorCommentDO>  {
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorCommentDoctorDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorCommentDoctorDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 服务工单中的医生评价 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorCommentDoctorDao extends PagingAndSortingRepository<WlyyDoorCommentDoctorDO, Integer>, JpaSpecificationExecutor<WlyyDoorCommentDoctorDO>  {
}

+ 29 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorConclusionDao.java

@ -0,0 +1,29 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorConclusionDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 
 * 工单服务小结 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorConclusionDao extends PagingAndSortingRepository<WlyyDoorConclusionDO, String>, JpaSpecificationExecutor<WlyyDoorConclusionDO>  {
    @Query("select c from WlyyDoorConclusionDO c where c.orderId = ?1")
    WlyyDoorConclusionDO findByOrderId(String orderId);
    @Query("select c from WlyyDoorConclusionDO c where c.patient = ?1 order by c.updateTime desc ")
    List<WlyyDoorConclusionDO> findByPatient(String patient);
}

+ 36 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorDao.java

@ -0,0 +1,36 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorDoctorDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Set;
/**
 * 
 * 服务工单关联的医护人员 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorDoctorDao extends PagingAndSortingRepository<WlyyDoorDoctorDO, String>, JpaSpecificationExecutor<WlyyDoorDoctorDO>  {
    @Query("select d from WlyyDoorDoctorDO d where d.orderId=?1")
    List<WlyyDoorDoctorDO> findByOrderId(String orderId);
    @Query("select d.doctor from WlyyDoorDoctorDO d where d.id in(:ids)")
    List<String> findDoctorByIds(@Param("ids") Set<String> ids);
    @Query("select d.doctor from WlyyDoorDoctorDO d where d.orderId = ?1")
    List<String> findDoctors(String orderId);
    boolean existsByOrderIdAndDoctor(String orderId, String doctor);
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorFeeDictDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorDoctorFeeDictDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 医生出诊费用字典 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorDoctorFeeDictDao extends PagingAndSortingRepository<WlyyDoorDoctorFeeDictDO, String>, JpaSpecificationExecutor<WlyyDoorDoctorFeeDictDO>  {
}

+ 33 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorDoctorStatusDao.java

@ -0,0 +1,33 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorDoctorStatusDO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 
 * 上门服务工单 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorDoctorStatusDao extends PagingAndSortingRepository<WlyyDoorDoctorStatusDO, String>, JpaSpecificationExecutor<WlyyDoorDoctorStatusDO>  {
    WlyyDoorDoctorStatusDO findByDoctor(String doctor);
    WlyyDoorDoctorStatusDO queryByDoctorAndStatusIn(String doctor, Integer[] status);
    List<WlyyDoorDoctorStatusDO> queryByStatusIn(Integer[] status, Pageable pageable);
    Integer countByStatusIn(Integer[] status);
    boolean existsByDoctorAndStatusIn(String doctor, Integer[] status);
}

+ 34 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorFeeDetailDao.java

@ -0,0 +1,34 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorFeeDetailDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Map;
/**
 * 
 * 服务工单价格明细(服务项价格,医生出诊费用) 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorFeeDetailDao extends PagingAndSortingRepository<WlyyDoorFeeDetailDO, String>, JpaSpecificationExecutor<WlyyDoorFeeDetailDO>  {
    @Query(value = "select fd.code code,fd.name name,fd.fee fee,fd.type type,fd.`number` number,fd.`status` status,dd.doctor_job_name doctorJobName from wlyy_door_fee_detail fd LEFT JOIN wlyy_door_doctor dd ON fd.order_id = dd.order_id where fd.order_id = ?1 group by code",nativeQuery = true)
    List<Map<String,Object>> findByOrderId(String orderId);
    @Query("select d from WlyyDoorFeeDetailDO d where d.orderId = ?1 and d.type=?2 and d.status <> 3")
    List<WlyyDoorFeeDetailDO> findByOrderIdAndType(String orderId, Integer type);
    @Query("select d.id as id,d.fee as fee,d.orderId as orderId from WlyyDoorFeeDetailDO d where d.code in(:codes) and d.type = :type")
    List<Map<String,Object>> findIdByCodeAndType(@Param("codes") List<String> codes, @Param("type") Integer type);
}

+ 15 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorOrderItemDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorOrderItemDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 *
 * 上门服务待预约服务项
 * Created by yeshijie on 2020/11/5.
 */
public interface WlyyDoorOrderItemDao extends PagingAndSortingRepository<WlyyDoorOrderItemDO, Integer>, JpaSpecificationExecutor<WlyyDoorOrderItemDO>  {
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPatientConfirmLogDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorPatientConfirmLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 服务工单居民确认操作日志记录 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorPatientConfirmLogDao extends PagingAndSortingRepository<WlyyDoorPatientConfirmLogDO, String>, JpaSpecificationExecutor<WlyyDoorPatientConfirmLogDO>  {
}

+ 29 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDao.java

@ -0,0 +1,29 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface WlyyDoorPrescriptionDao extends PagingAndSortingRepository<WlyyDoorPrescriptionDO, Integer>, JpaSpecificationExecutor<WlyyDoorPrescriptionDO> {
    @Query("select p from WlyyDoorPrescriptionDO p where p.orderId = ?1 and p.isAfterDoor = ?2  order by p.createTime desc")
    List<WlyyDoorPrescriptionDO> findByOrderIdAndIsAfterDoor(String id, Integer isAfterDoor);
    @Query("select p from WlyyDoorPrescriptionDO p where p.code = ?1 ")
    WlyyDoorPrescriptionDO findByCode(String code);
    List<WlyyDoorPrescriptionDO> findByVisitNoAndStatus(String visitNo, Integer status);
    @Query("select p from WlyyDoorPrescriptionDO p where p.visitNo = ?1 ")
    List<WlyyDoorPrescriptionDO> findByVisitNoAndOrderIdNot(String visitNo);
    WlyyDoorPrescriptionDO findByRecipeNo(String recipeNo);
    /*@Query("select p from WlyyDoorPrescriptionDO p where p.number = ?1 and p.status = ?2 and p.recipeNo is null ")
    WlyyDoorPrescriptionDO findByNumberAndStatus(String prescriptionNumber, Integer status);
    @Query("select p from WlyyDoorPrescriptionDO p where p.number = ?1 and p.status = 1 and p.code <> ?2 order by p.createTime ")
    List<WlyyDoorPrescriptionDO> findRecipeNosByNumber(String number, String code);*/
}

+ 18 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDetailDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDetailDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface WlyyDoorPrescriptionDetailDao extends PagingAndSortingRepository<WlyyDoorPrescriptionDetailDO, Integer>, JpaSpecificationExecutor<WlyyDoorPrescriptionDetailDO> {
    @Query("select d from WlyyDoorPrescriptionDetailDO d where d.prescriptionCode = ?1 ")
    List<WlyyDoorPrescriptionDetailDO> findByPrescriptionCode(String prescriptionCode);
    @Modifying
    @Query("update WlyyDoorPrescriptionDetailDO d set d.status = 0 where d.prescriptionCode = ?1 and d.status = 1")
    void updateStatusByPrescriptionCode(String prescriptionCode);
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorPrescriptionDrugDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDrugDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface WlyyDoorPrescriptionDrugDao extends PagingAndSortingRepository<WlyyDoorPrescriptionDrugDO, Integer>, JpaSpecificationExecutor<WlyyDoorPrescriptionDrugDO> {
    @Modifying
    @Transactional
    @Query("update WlyyDoorPrescriptionDrugDO d set d.del = 0 where d.prescriptionCode = ?1 and d.del = 1")
    void updateDelByPrescriptionCode(String prescriptionCode);
    @Query("select d from WlyyDoorPrescriptionDrugDO d where d.prescriptionCode = ?1 order by d.subjectClass desc")
    List<WlyyDoorPrescriptionDrugDO> findByPrescriptionCode(String prescriptionCode);
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorProcessLogDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorProcessLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 工单状态变更记录(调度员操作记录) 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年04月09日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorProcessLogDao extends PagingAndSortingRepository<WlyyDoorProcessLogDO, String>, JpaSpecificationExecutor<WlyyDoorProcessLogDO>  {
}

+ 50 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorServiceOrderDao.java

@ -0,0 +1,50 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
 * 
 * 上门服务工单 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorServiceOrderDao extends PagingAndSortingRepository<WlyyDoorServiceOrderDO, String>, JpaSpecificationExecutor<WlyyDoorServiceOrderDO>  {
    boolean existsByPatientAndStatusNot(String patient, int status);
    boolean existsByPatientAndStatusIn(String patient, Integer[] status);
    @Modifying
    @Transactional
    @Query("update WlyyDoorServiceOrderDO o set o.conclusionStatus = 1 where o.id = ?1")
    void updateConclusionStatus(String orderId);
    @Query("select o from WlyyDoorServiceOrderDO o where o.doctor = ?1 and o.status in (2,3)")
    List<WlyyDoorServiceOrderDO> getNotFinishOrderByDoctor(String doctor);
    @Modifying
    @Transactional
    @Query("update WlyyDoorServiceOrderDO o set o.prescriptionStatus = 1,o.status = 4, o.prescriptionCode = ?2, o.prescriptionTime = ?3 where o.id = ?1")
    void updatePrescriptionById(String orderId, String prescriptionCode, Date prescriptionTime);
    @Query("select o from WlyyDoorServiceOrderDO o where o.prescriptionCode like ?1 and o.status <> -1 ")
    List<WlyyDoorServiceOrderDO> findByPrescriptionCode(String prescriptionCode);
    @Query("select o from WlyyDoorServiceOrderDO o where o.relationCode = ?1 order by o.createTime desc")
    List<WlyyDoorServiceOrderDO> findByRelationCode(String relationCode);
}

+ 20 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/dao/WlyyDoorTransRecordDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.door.dao;
import com.yihu.jw.entity.door.WlyyDoorTransRecordDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 服务工单转接给其他结构的转接记录 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorTransRecordDao extends PagingAndSortingRepository<WlyyDoorTransRecordDO, String>, JpaSpecificationExecutor<WlyyDoorTransRecordDO>  {
}

+ 169 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoctorRegistrationTempService.java

@ -0,0 +1,169 @@
package com.yihu.jw.door.service;
import com.yihu.jw.door.dao.DoctorRegistrationDao;
import com.yihu.jw.door.dao.DoctorRegistrationTempDao;
import com.yihu.jw.entity.door.DoctorRegistration;
import com.yihu.jw.entity.door.DoctorRegistrationTemp;
import com.yihu.mysql.query.BaseJpaService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 医生登记服务模板
 * Created by wangpeiqiang on 2019/3/12.
 */
@Service
@Transactional
public class DoctorRegistrationTempService extends BaseJpaService<DoctorRegistrationTemp, DoctorRegistrationTempDao> {
    @Autowired
    DoctorRegistrationTempDao doctorRegistrationTempDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    DoctorRegistrationDao doctorRegistrationDao;
    public  List<Map<String, Object>> getRegistrationTempData(String filter) {
        //List<Map> doctorRegistrationList =  doctorRegistrationDao.findAll();
        String sql = "select id,code,model_name,create_time,is_hide from wlyy_doctor_registration";
        List<Map<String, Object>> doctorRegistrationList = jdbcTemplate.queryForList(sql);
        List<DoctorRegistrationTemp> doctorRegistrationTempList = this.doctorRegistrationTempDao.findAllRegistrationTemp("%"+filter+"%");
        if(doctorRegistrationList!=null && doctorRegistrationList.size()>0){
            for(Map map:doctorRegistrationList){
                String code = map.get("code").toString();
                List<DoctorRegistrationTemp> secRegistrationTempList = this.getChildrenList(doctorRegistrationTempList,code);
                map.put("secRegistrationTempList",secRegistrationTempList);
            }
        }
        return doctorRegistrationList;
    }
    public  List<Map<String, Object>> getListByDoctorCode(String doctor,String filter) {
        //List<Map> doctorRegistrationList =  doctorRegistrationDao.findAll();
        String sql = "select id,code,model_name,create_time,is_hide from wlyy_doctor_registration";
        List<Map<String, Object>> doctorRegistrationList = jdbcTemplate.queryForList(sql);
//        List<DoctorRegistrationTemp> doctorRegistrationTempList = this.doctorRegistrationTempDao.findAllByDoctorCode(doctor,"%"+filter+"%");
        if(doctorRegistrationList!=null && doctorRegistrationList.size()>0){
            for(Map map:doctorRegistrationList){
                String code = map.get("code").toString();
                List<DoctorRegistrationTemp> secRegistrationTempList = doctorRegistrationTempDao.findRegistrationTempByRegistration(code);
//                List<DoctorRegistrationTemp> secRegistrationTempList = this.getChildrenList(doctorRegistrationTempList,code);
                map.put("secRegistrationTempList",secRegistrationTempList);
            }
        }
        return doctorRegistrationList;
    }
    private List<DoctorRegistrationTemp> getChildrenList(List<DoctorRegistrationTemp> doctorRegistrationTempList, String code) {
        List<DoctorRegistrationTemp> doctorRegistrationTempArrayList = new ArrayList<>();
        for (DoctorRegistrationTemp doctorRegistrationTemp: doctorRegistrationTempList) {
            if(doctorRegistrationTemp.getRegistration().equals(code)){
                doctorRegistrationTempArrayList.add(doctorRegistrationTemp);
            }
        }
        return doctorRegistrationTempArrayList;
    }
    public List<DoctorRegistration> findAllRegistrationList() throws Exception{
        List<DoctorRegistration> list =  doctorRegistrationDao.findAll();
        return list;
    }
    /**
     * 添加登记服务模板
     *
     * @param doctor  医生
     * @param content 登记服务内容
     * @return
     */
    public DoctorRegistrationTemp add(String doctor, String content, String registration) throws Exception{
        DoctorRegistrationTemp doctorRegistrationTemp = new DoctorRegistrationTemp();
        doctorRegistrationTemp.setCode(getCode());
        doctorRegistrationTemp.setDoctor(doctor);
        doctorRegistrationTemp.setContent(content);
        doctorRegistrationTemp.setSendTimes(0);
        doctorRegistrationTemp.setCreateTime(new Date());
        doctorRegistrationTemp.setRegistration(registration);
        return doctorRegistrationTempDao.save(doctorRegistrationTemp);
    }
    /**
     * 查询单个登记服务模板详情
     *
     * @param modelCode
     * @returnxiang
     * @throws Exception
     */
    public JSONObject listDetail(String modelCode) throws Exception {
        String sql =  "SELECT a.`model_name`,b.`content`,b.`create_time`,b.`send_times`" +
                "FROM wlyy_doctor_registration as a LEFT JOIN wlyy_doctor_registration_temp as b ON a.`code` =b.`registration`" +
                "WHERE b.`code`=?";
        Map temp = (Map) jdbcTemplate.queryForMap(sql, modelCode);
        String modelName = (String) temp.get("model_name");
        String content = (String) temp.get("content");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = (Date) temp.get("create_time");
        String dateTime = sdf.format(createTime);
        String sendTimes = (String) temp.get("send_times").toString();
        JSONObject json = new JSONObject();
        json.put("modelName", modelName);
        json.put("content", content);
        json.put("createTime", dateTime);
        json.put("sendTimes", sendTimes);
        return json;
    }
    /**
     * 修改登记服务模板
     *
     * @param code    模板编码
     * @param content 内容
     * @return
     */
    public DoctorRegistrationTemp modify(String code, String content) throws Exception {
        DoctorRegistrationTemp doctorRegistrationTemp = doctorRegistrationTempDao.findByCode(code);
        if (doctorRegistrationTemp == null) {
            throw new Exception("模板不存在");
        }
        doctorRegistrationTemp.setContent(content);
        return doctorRegistrationTempDao.save(doctorRegistrationTemp);
    }
    /**
     * 删除登记服务模板
     *
     * @param code 模板编码
     * @return
     */
    public int delete(String code) throws Exception {
        String[] codes = code.split(",");
        if (codes != null && codes.length > 0) {
            for (String temp : codes) {
                String sql = "SELECT t.doctor FROM wlyy_doctor_registration_temp t WHERE t.code=?";
                String doctor = jdbcTemplate.queryForObject(sql, String.class, temp);
                if (!"system".equals(doctor)) {
                    doctorRegistrationTempDao.deleteByCode(temp);
                }
            }
        }
        return 1;
    }
}

+ 1750 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorOrderService.java

@ -0,0 +1,1750 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.door.dao.*;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.*;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.lang.Boolean;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * Created by wxw on 2019/3/18.
 *
 * @author wxw.
 */
@Service
@Transactional
public class DoorOrderService {
    private Logger logger = LoggerFactory.getLogger(DoorOrderService.class);
/*    @Value("${server.server_url}")
    private String wxServerUrl;*/
    //图片服务地址
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyDoorConclusionDao doorConclusionDao;
    @Autowired
    private DoorServiceOrderDao doorServiceOrderDao;
    @Autowired
    private DoctorRegistrationTempService templateService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private WlyyDoorFeeDetailDao doorFeeDetailDao;
    @Autowired
    private WlyyDoorDoctorDao doorDoctorDao;
    @Autowired
    private WlyyDoorPatientConfirmLogDao confirmLogDao;
    @Autowired
    private WlyyDoorDoctorStatusDao doctorStatusDao;
    @Autowired
    private BaseDoctorDao doctorDao;
/*    @Autowired
    private ServerPackageItemPatientDao serverPackageItemPatientDao;
    @Autowired
    private DmJobService dmJobService;*/
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private BasePatientDao patientInfoService;
    @Autowired
    private DoorServiceVoucherDao doorServiceVoucherDao;
/*    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;*/
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private WlyyDoorPrescriptionDao doorPrescriptionDao;
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private WlyyDoorFeeDetailDao wlyyDoorFeeDetailDao;
    /**
     * 顶部状态栏订单各分类总条数
     * @param doctor
     * @param type
     * @return
     */
    public Map<String, String> getNumGroupByStatus(String doctor, Integer type) {
        String sql = "SELECT a.status, COUNT(DISTINCT a.id) as num FROM wlyy_door_service_order a " ;
        //计算代预约记录个状态数
        if(type != null && type == 3){
            sql +=  "LEFT JOIN wlyy_door_doctor d on d.order_id = a.id WHERE a.type=3 and a.proxy_patient = ? and a.proxy_patient = ? group BY a.status";
        }else{
            sql +=  "LEFT JOIN wlyy_door_doctor d on d.order_id = a.id WHERE  (d.doctor =? or a.doctor = ?) group BY a.status";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, doctor,doctor);
        Map<String, String> map = new HashMap<>();
        list.stream().forEach(one -> {
            map.put(exchangeKeyName(String.valueOf(one.get("status"))), String.valueOf(one.get("num")));
        });
        if (!map.containsKey("cancelOrder")) {
            map.put("cancelOrder", "0");
        }
        if (!map.containsKey("sendOrder")) {
            map.put("sendOrder", "0");
        }
        if (!map.containsKey("waitingOrder")) {
            map.put("waitingOrder", "0");
        }
        if (!map.containsKey("serviceOrder")) {
            map.put("serviceOrder", "0");
        }
        if (!map.containsKey("payment")) {
            map.put("payment", "0");
        }
        if (!map.containsKey("supplement")) {
            map.put("supplement", "0");
        }
        if (!map.containsKey("completed")) {
            map.put("completed", "0");
        }
        if(!map.containsKey("exampaperstatus")){
            map.put("exampaperstatus", "0");
        }
        return map;
    }
    private String exchangeKeyName(String status) {
        String key;
        switch (status) {
            case "-1":
                key = "cancelOrder";
                break;
            case "1":
                key = "sendOrder";
                break;
            case "2" :
                key = "waitingOrder";
                break;
            case "3" :
                key = "serviceOrder";
                break;
            case "4" :
                key = "payment";
                break;
            case "5" :
                key = "supplement";
                break;
            case "6" :
                key = "completed";
                break;
            case "7" :
                key = "exampaperstatus";
                break;
            default:
                key = status;
                break;
        }
        return key;
    }
    /**
     * 根据接单医生code获取最近一次服务orderId
     * @param doctor
     * @return
     */
    public String getOrderIdByDoctor(String doctor) {
        String sql = "SELECT id as orderId from wlyy_door_service_order where doctor=? and status in(2,3,4,5,6) ORDER BY patient_expected_serve_time desc,update_time desc,create_time desc, status ASC limit 1";
        String orderId = jdbcTemplate.queryForObject(sql, String.class, new Object[]{doctor});
        return orderId;
    }
    /**
     * 根据orderId获取工单服务小结
     * @param orderId
     * @param flag 是否获取模板
     * @return
     */
    public WlyyDoorConclusionDO getDoorConclusion(String orderId, Boolean flag){
        WlyyDoorConclusionDO doorConclusion = doorConclusionDao.findByOrderId(orderId);
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
        if (flag && null != one) {
            String doctor = one.getDoctor();
            // 获取医生模板信息 doctor = xx
            List<Map<String, Object>> registrationTempData = templateService.getListByDoctorCode(doctor, "");
            if (null == doorConclusion) {
                doorConclusion = new WlyyDoorConclusionDO();
                BasePatientDO patient = patientInfoService.findById(one.getPatient());
                if (patient != null) {
                    doorConclusion.setOrderId(orderId);
                    doorConclusion.setPatient(patient.getId());
                    doorConclusion.setPatientName(patient.getName());
                    doorConclusion.setAge(IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
                    doorConclusion.setSex(IdCardUtil.getSexNameForIdcard_new(patient.getIdcard()));
                    doorConclusion.setIdcard(patient.getIdcard());
                    doorConclusion.setPatientPhone(patient.getMobile());
                    doorConclusion.setAddress(one.getServeAddress());
                }
                // 设置供史者信息
                doorConclusion.setProxyPatientName(one.getProxyPatientName());
                doorConclusion.setProxyPatientPhone(one.getPatientPhone());
                doorConclusion.setProxyPatientRelation(one.getPatientRelation());
                //获取居民上次服务小结内容
                List<WlyyDoorConclusionDO> patientLastConclusionList = doorConclusionDao.findByPatient(one.getPatient());
                if(patientLastConclusionList.size() > 0){
                    doorConclusion.setPatientLastConclusion(patientLastConclusionList.get(0));
                }
            }
            doorConclusion.setTemplate(registrationTempData);
        }
        return doorConclusion;
    }
    /**
     * 根据工单id获取服务工单-服务项价格,按status分组,1-居民新增(预约),2-医生新增,3-医生删除
     * @param orderId
     * @return
     */
    public List<Map<String, Object>> getDoorFeeDetailGroupByStatus(String orderId) {
        String sql = "SELECT d.id, d.status,d.name,d.code,sum(d.number) num,fee,sum(d.number)*fee sum from wlyy_door_fee_detail d where order_id=? and type=1 GROUP BY status,code";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, orderId);
        return list;
    }
    /**
     * 获取指定工单下的服务医生
     * @param orderId
     * @return
     */
    public List<Map<String, Object>> getDoorServiceDoctor(String orderId) {
        String sql = "SELECT dd.id as id,CONCAT(d.`name`,' (',dd.doctor_job_name,')') as name, dd.doctor from wlyy_door_doctor dd join wlyy_doctor d on d.`code` = dd.doctor WHERE order_id=?";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, orderId);
        return mapList;
    }
    /**
     * 根据id获取服务工单信息
     * @param id
     * @return
     */
    public WlyyDoorServiceOrderDO getDoorServiceOrderById(String id, Integer level) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findOne(id);
        if (null == doorServiceOrder) {
            return null;
        }
        BasePatientDO patient = patientInfoService.findById(doorServiceOrder.getPatient());
        if (patient != null) {
            String sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
            int age = IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday());
            doorServiceOrder.setSex("1".equals(sex) ? "男" : "2".equals(sex) ? "女" : "未知");
            doorServiceOrder.setAge(age);
            doorServiceOrder.setPhoto(patient.getPhoto());
            String typeValues = this.getTypeValueByPatientCode(patient.getId());
            doorServiceOrder.setTypeValue(typeValues);
        }
        // 获取服务次数
        Integer count = this.serviceCount(doorServiceOrder.getPatient());
        Integer times = wlyyDoorServiceOrderService.countPatientDoorTimes(doorServiceOrder.getPatient());
        List<WlyyDoorDoctorDO> djDetailList = this.djDetailList(id,level,times);
        doorServiceOrder.setDjDetailList(djDetailList);
        List<Map<String, Object>> feeDetailDOS = this.getDoorFeeDetailGroupByStatus(id);
        String jsonData = this.serverPackagePriceByOrderId(id);
        if (null != feeDetailDOS && feeDetailDOS.size() > 0) {
            // 设置服务项及费用信息
            doorServiceOrder.setDoorFeeDetailList(feeDetailDOS);
        }
        // 服务工单关联的医护人员
        List<Map<String, Object>> doorServiceDoctors = this.getDoorServiceDoctor(id);
        if (null != doorServiceDoctors && doorServiceDoctors.size() > 0) {
            doorServiceOrder.setDoctors(doorServiceDoctors);
        }
        //获取咨询
        ConsultDo consult = consultDao.queryByRelationCode(id);
        if (null != consult) {
            doorServiceOrder.setSessionId(doorServiceOrder.getProxyPatient() + "_" + consult.getId() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
        }
        // 设置服务小结
        WlyyDoorConclusionDO doorConclusion = this.getDoorConclusion(id, true);
        if (null == doorConclusion) {
            doorConclusion = new WlyyDoorConclusionDO();
        }
        doorConclusion.setServiceCount(count);
        doorServiceOrder.setDoorConclusion(doorConclusion);
        //获取上门前后开方详情
        List<WlyyDoorPrescriptionDO> doorBeforePrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 1);
        List<WlyyDoorPrescriptionDO> doorAfterPrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 2);
        doorServiceOrder.setPrescriptionDOList(doorBeforePrescriptionDOList);
        doorServiceOrder.setAfterPrescriptionList(doorAfterPrescriptionDOList);
        return doorServiceOrder;
    }
    /**
     * 门牌地址解析
     * @param url
     * @return
     * @throws Exception
     */
    public String urlAnalysis(String url)throws Exception{
        Document doc = Jsoup.connect(url).get();
        String html = doc.toString();
        int start = html.indexOf("href=\"");
        int end = html.indexOf("\"}");
        int ed = url.indexOf("com");
        String ym = url.substring(0,ed+3);
        String path = html.substring(start+6,end);
        Document d = Jsoup.connect(ym+path).get();
        return d.select("div.dzksfd1_lz2").eq(1).text();
    }
    /**
     * 签到保存
     * @param orderId
     * @param signTime
     * @param signWay
     * @param signLocation
     * @param signImg
     * @return
     */
    public WlyyDoorServiceOrderDO signIn(String orderId, String signTime, Integer signWay, String signLocation, String signImg, String twoDimensionalCode) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findOne(orderId);
        doorServiceOrder.setDoctorSignTime(DateUtil.strToDate(signTime));
        doorServiceOrder.setDoctorSignWay(signWay);
        // 签到方式-2扫码时,需要去解析地址
        doorServiceOrder.setDoctorSignLocation(signLocation);
        doorServiceOrder.setDoctorSignImg(StringUtils.isEmpty(signImg) ? null : signImg);
        if(signWay == 4 ){//扫码签到
            if (twoDimensionalCode.equals(doorServiceOrder.getNumber())){
                this.setUpdateColumnInfo(doorServiceOrder);
                doorServiceOrder = doorServiceOrderDao.save(doorServiceOrder);
                // 修改医生上门服务工单状态 4服务中
                this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);
                return doorServiceOrder;
            }else {
                logger.info("扫码签到失败");
                return null;
            }
        }else {
            this.setUpdateColumnInfo(doorServiceOrder);
            doorServiceOrder = doorServiceOrderDao.save(doorServiceOrder);
            // 修改医生上门服务工单状态 4服务中
            this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);
            return doorServiceOrder;
        }
    }
    /**
     * 编辑保存服务工单小结
     * @param model
     * @return
     * @throws Exception
     */
    public WlyyDoorConclusionDO updateDoorConclusion(String model, Integer examPapeStatus) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        WlyyDoorConclusionDO doorConclusion = objectMapper.readValue(model, WlyyDoorConclusionDO.class);
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(doorConclusion.getOrderId());
        BaseDoctorDO doctorVO = doctorDao.findById(one.getDoctor());
        if (doorConclusion != null && StringUtils.isNotEmpty(doorConclusion.getId())) {
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setUpdateUser(one.getDoctor());
            doorConclusion.setUpdateUserName(null != doctorVO ? doctorVO.getName() : null);
        } else {
            doorConclusion.setCreateTime(new Date());
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setCreateUser(one.getDoctor());
            doorConclusion.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        doorConclusionDao.save(doorConclusion);
        // 设置是否需要上传补录报告
        one.setExamPaperStatus(examPapeStatus);
        one.setConclusionStatus(2);
        doorServiceOrderDao.save(one);
        return doorConclusion;
    }
    public WlyyDoorServiceOrderDO acceptOrder1(String orderId,String jobCode,String jobCodeName,int hospitalLevel ) throws Exception{
        WlyyDoorServiceOrderDO doorServiceOrder = doorServiceOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        doorServiceOrder.setDoctorArrivingTime(doorServiceOrder.getPatientExpectedServeTime());
        doorServiceOrder.setStatus(WlyyDoorServiceOrderDO.Status.accept.getType()); // 2-待(医生)接单,3-待服务
        this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 3);
//        this.updateServiceResponseTime(orderId);
        doorServiceOrder.setServiceResponseTime(new Date());
        //新增工单医生关联关系
        JSONObject jsonObjectParam = new JSONObject();
        JSONObject doc = new JSONObject();
        doc.put("doctor",doorServiceOrder.getDoctor());
        doc.put("doctorName",doorServiceOrder.getDoctorName());
        doc.put("hospitalLevel",hospitalLevel);
        doc.put("doctorJobCode",jobCode);
        doc.put("doctorJobName",jobCodeName);
        JSONArray docArr = new JSONArray();
        docArr.add(doc);
        jsonObjectParam.put("doctorArr",docArr);
        if (wlyyDoorServiceOrderService.orderWithDoctorAdd(new JSONObject(), jsonObjectParam, doorServiceOrder)) return null;
        doorServiceOrderDao.save(doorServiceOrder);
//        this.messageDao.orderMessageDel(doorServiceOrder.getDoctor(),orderId);
        if(doorServiceOrder.getType() == null|| doorServiceOrder.getType() != 3) {
            //获取咨询
            ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(orderId);
            consultTeam.setDoctor(doorServiceOrder.getDoctor());
            consultTeam.setDoctorName(doorServiceOrder.getDoctorName());
            consultTeamDao.save(consultTeam);
            String sessionId = doorServiceOrder.getPatient() + "_" + consultTeam.getConsult() + "_" + doorServiceOrder.getNumber() + "_" + consultTeam.getType();
            //成功创建服务工单后,居民所在机构调度员向居民发起一条通知服务消息
            // 发送IM消息通知患者医生已接单
            String noticeContent = "我已接受您的服务工单预约," + doorServiceOrder.getDoctorName() + "医生正在为您服务!";
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "1", noticeContent);
            // 发送居民上门服务简要信息
            JSONObject orderInfoContent = wlyyDoorServiceOrderService.queryOrderCardInfo(doorServiceOrder);
            orderInfoContent.put("re_msg_type", 0);
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
        }
        return doorServiceOrder;
    }
    /**
     * 接单
     * @param orderId
     */
    public void acceptOrder(String orderId,String jobCode,String jobCodeName,int hospitalLevel ) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = acceptOrder1(orderId, jobCode, jobCodeName, hospitalLevel);
        if(doorServiceOrder==null){
            return;
        }
        // 发送微信模板消息通知患者医生已接单
        BasePatientDO patient = patientInfoService.findById(doorServiceOrder.getPatient());
        // 获取微信模板
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try{
/*            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","smyyyjjd");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(patient.getName()==null?"":patient.getName()));
            first = first.replace("key2", null != doorServiceOrder.getDoctorName() ? doorServiceOrder.getDoctorName() : "");
            String keyword1 = templateConfig.getKeyword1();
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "上门服务已接单");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            if(consult != null) {
                json.put("consult", consult.getCode());
            }
            logger.info("上门服务已接单推送前");
            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
            logger.info("上门服务已接单推送后");*/
        }catch (Exception e) {
            logger.error(e.getMessage());
        }
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678
/*        List<Message> messages = messageDao.queryByRelationCodeAndTypeIn(orderId,new Integer[]{403,407});
        if(CollectionUtils.isEmpty(messages)){
            logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
        } else {
            messages.forEach(
                    message -> {
                        if (message.getType() == 403) {
                            message.setTitle("医生接单");
                            message.setContent(doorServiceOrder.getDispatcherName() + "接受了服务工单"+ doorServiceOrder.getNumber());
                            message.setType(434);
                            message.setReceiver(doorServiceOrder.getDispatcher());
                            message.setSender(doorServiceOrder.getDoctor());
                            message.setCreateTime(new Date());
                        }else{
                            message.setOver("0");
                        }
                        messageDao.save(message);
                    }
            );
        }*/
    }
    /**
     * 拒单
     * @param orderId
     * @param reason
     * @throws Exception
     */
    public void refuseOrder(String receiver, String orderId, String reason) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = doorServiceOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        //给代预约医生发消息
        if (doorServiceOrder.getType() != null && doorServiceOrder.getType() == 3) {
            this.createMessage(doorServiceOrder.getId(), "system", doorServiceOrder.getProxyPatient(), 403, "代预约服务工单重新派单", doorServiceOrder.getPatientName() + "的代预约服务工单需重新派单,请您前往处理");
        } else {
/*            this.messageDao.orderMessageDel(doorServiceOrder.getDoctor(),orderId);
            if(StringUtils.isNotBlank(doorServiceOrder.getDispatcher())){
                // 派单消息
                this.createMessage(doorServiceOrder.getId(), "system", doorServiceOrder.getDispatcher(), 404, "服务工单拒单待重新派单", doorServiceOrder.getDoctorName() + "拒绝了" + doorServiceOrder.getProxyPatientName() + "的服务预约申请,请重新派单");
                //  调度员-派单-实时工单消息:435 医生拒单-- 王五拒绝了服务工单12345678
                List<Message> messages = messageDao.queryByRelationCodeAndTypeIn(orderId, new Integer[]{431, 433});
                if (CollectionUtils.isEmpty(messages)) {
                    logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
                } else {
                    Message message = messages.get(0);
                    message.setTitle("医生拒单");
                    message.setContent(doorServiceOrder.getDoctorName() + "拒绝了服务工单" + doorServiceOrder.getNumber() + ", 请重新派单");
                    message.setType(435);
                    message.setReceiver(doorServiceOrder.getDispatcher());
                    message.setSender(doorServiceOrder.getDoctor());
                    message.setCreateTime(new Date());
                    messageDao.save(message);
                }
            }*/
        }
        doorServiceOrder.setDoctor(null);
        doorServiceOrder.setDoctorName(null);
        doorServiceOrder.setStatus(WlyyDoorServiceOrderDO.Status.waitForSend.getType());  // 设置为1-待(调度员)派单
        doorServiceOrder.setCancelReason(reason);   // 拒绝原因
        doorServiceOrder.setCancelTime(new Date());
        doorServiceOrderDao.save(doorServiceOrder);
    }
    /**
     * 添加【工单派单,转单】等系统消息
     * @param orderId
     * @param sender
     * @param receiver
     * @param Content
     */
    public void createMessage(String orderId,String sender,String receiver,int type,String title,String Content){
/*        Message message= new Message();
        message.setCzrq(new Date());
        message.setCreateTime(new Date());
        message.setRead(1);
        message.setState(1);
        message.setRelationCode(orderId);
        message.setOver("1");
        message.setReceiver(receiver);
        message.setSender(sender);
        message.setCode(getCode());
        message.setTitle(title);
        message.setContent(Content);
        //消息类型:401为资质申请审核
        message.setType(type);
        message.setDel("1");
        messageDao.save(message);*/
    }
    /**
     * 获取工单列表
     * @param orderId
     * @param patientName
     * @param patientPhone
     * @param hospitalCode
     * @param status
     * @param createTimeStart
     * @param createTimeEnd
     * @param page
     * @param pageSize
     * @param type
     * @return
     */
    public JSONObject getDoorOrderList(String orderId, String patientName, String patientPhone, String hospitalCode,
                                       StringBuffer status, String createTimeStart, String createTimeEnd, String serverDoctorName,
                                       String doctorCode, Integer examPaperStatus, Integer page, Integer pageSize, Integer type)throws Exception{
        String sqlList = "select DISTINCT o.id as orderId,o.status,f.hospital,f.hospital_name as hospitalName1,o.is_trans_other_org,o.transed_org_code,h.name as hospitalName2,o.patient_name," +
                " o.patient_phone,o.remark,o.serve_desc,o.create_time,o.patient as patientCode ,o.exam_paper_status as examPaperStatus,o.number as serverCode,o.total_fee,h.hos_level as hosLevel, " +
                "o.doctor, o.doctor_name as doctorName, o.doctor_type as doctorType "
                ;
        String sqlCount = " select count(*) as total ";
        String sql = " from wlyy_door_service_order o " +
                " LEFT JOIN wlyy_sign_family f ON f.patient = o.patient AND f. STATUS = 1 AND f.expenses_status = 1 " +
                " LEFT JOIN dm_hospital h on h.code=o.hospital and h.del=1 "
                +" LEFT JOIN wlyy_door_doctor d on d.order_id = o.id ";
        sql+= " where 1=1 ";
        if(!StringUtils.isEmpty(orderId)){
            sql+=" and o.number = '"+orderId+"'";
        }
        if(!StringUtils.isEmpty(patientName)){
            sql+=" and o.patient_name like '%"+patientName+"%'";
        }
        if(!StringUtils.isEmpty(patientPhone)){
            sql+=" and o.patient_phone ='"+patientPhone+"'";
        }
        if(!StringUtils.isEmpty(hospitalCode)&&!"350200%".equals(hospitalCode)){
            sql+=" and (f.hospital like '"+hospitalCode+"' or o.transed_org_code like '"+hospitalCode+"') ";
        }
        if(status!=null){
            sql+=" and o.status in ("+status+")";
        }
        if(!StringUtils.isEmpty(createTimeStart)){
            sql+=" and o.create_time >='"+createTimeStart+"'";
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            sql+=" and o.create_time <='"+createTimeEnd+"'";
        }
        if(!StringUtils.isEmpty(serverDoctorName)){
            sql+=" and d.doctor_name like '%"+serverDoctorName+"%'";
        }
        //获取医生代预约记录
        if(type != null && type == 3 ){
            sql += " and o.type = " + type + " and o.proxy_patient = '" + doctorCode + "'";
        }else if(!StringUtils.isEmpty(doctorCode)){
            sql+=" and (d.doctor='"+doctorCode+"' or o.doctor='"+doctorCode+"')";
        }
        if(examPaperStatus!=null){
            sql+=" and o.conclusion_status =1 ";
        }
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlCount+sql);
        sql+=" order by o.create_time desc LIMIT "+(page-1)*pageSize+","+pageSize;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sqlList+sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        JSONArray jsonArray = new JSONArray();
        for(Map<String,Object> one:list){
            JSONObject object = new JSONObject();
            object.put("id",one.get("orderId"));
            object.put("serverCode",one.get("serverCode"));
            Integer statustemp = Integer.valueOf(one.get("status")+"");
            String statusName = "";
            switch (statustemp){
                case -1:statusName="已取消";break;
                case 1:statusName="待派单";break;
                case 2:statusName="待接单";break;
                case 3:statusName="已接单";break;
                case 4:statusName="待服务";break;
                case 5:statusName="待评价";break;
                case 6:statusName="已完成";break;
            }
            object.put("status",statustemp);
            object.put("statusName",statusName);
            //工单是否转给其他机构,0-不转,1-已转
            String transOtherOrg = one.get("is_trans_other_org")+"";
            Object hospitalName = null;
            Object hospital = null;
            if("0".equals(transOtherOrg)){
                hospital = one.get("hospital");
                hospitalName = one.get("hospitalName1");//签约表中的机构
            }else if("1".equals(transOtherOrg)){
                hospital = one.get("transed_org_code");
                hospitalName = one.get("hospitalName2");//转机构中的机构
            }else if("null".equals(transOtherOrg)){
                hospital = one.get("hospital");
                hospitalName = one.get("hospitalName1");//签约表中的机构
            }
            object.put("hospital",hospital);
            object.put("hospitalName",hospitalName);
            object.put("patient",one.get("patientCode"));
            object.put("patientName",one.get("patient_name"));
            object.put("patientPhone",one.get("patient_phone"));
            object.put("remark",one.get("remark"));
            object.put("serveDesc",one.get("serve_desc"));
            object.put("hosLevel",one.get("hosLevel"));
            Date date = (Date)one.get("create_time");
            object.put("createTime",DateUtil.dateToStr(date,"yyyy-MM-dd HH:mm:ss"));
            object.put("examPaperStatus",one.get("examPaperStatus"));
            //服务人员
            List<WlyyDoorDoctorDO> doorDoctorDOs = doorDoctorDao.findByOrderId(one.get("orderId")+"");
            String serverDoctors = "";
            for (WlyyDoorDoctorDO temp : doorDoctorDOs) {
                serverDoctors += "、" + temp.getDoctorName();
            }
            object.put("serverDoctors",serverDoctors.startsWith("、")?serverDoctors.substring(1):serverDoctors);
            object.put("totalFee",one.get("total_fee"));
            List<WlyyDoorFeeDetailDO> feeDetailDOs = doorFeeDetailDao.findByOrderIdAndType(one.get("orderId")+"", 1);
            List<Map<String,Object>> feeDetailResultList = new ArrayList();
            for(WlyyDoorFeeDetailDO d:feeDetailDOs){
                Map<String,Object> map = new HashMap<>();
                map.put("code",d.getCode());
                map.put("name",d.getName());
                map.put("fee",d.getFee());
                map.put("number",d.getNumber());
                feeDetailResultList.add(map);
            }
            object.put("feeDetailResultList",feeDetailResultList);
            // 获取或者基本信息
            BasePatientDO patient = patientInfoService.findById(String.valueOf(one.get("patientCode")));
            if (patient != null) {
                String sex = IdCardUtil.getSexForIdcard(patient.getIdcard());
                object.put("sex", "1".equals(sex) ? "男" : "2".equals(sex) ? "女" : "未知");
                object.put("age", IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
                object.put("photo", patient.getPhoto());
                String typeValues = this.getTypeValueByPatientCode(patient.getId());
                object.put("typeValue", typeValues);
            }
            String id = one.get("orderId").toString();
            WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findOne(id);
            //获取咨询
            ConsultDo consult = consultDao.queryByRelationCode(id);
            if (null != consult) {
                doorServiceOrder.setSessionId(doorServiceOrder.getProxyPatient() + "_" + consult.getId() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
            }
            object.put("sessionId",doorServiceOrder.getSessionId());
            // 获取服务次数
            Integer serviceCount = this.serviceCount(doorServiceOrder.getPatient());
            object.put("serviceCount", serviceCount);
            //添加服务医生
            object.put("doctorName", doorServiceOrder.getDoctorName());
            object.put("doctorType", doorServiceOrder.getDoctorType());
            object.put("type", doorServiceOrder.getType());
            jsonArray.add(object);
        }
        JSONObject object = new JSONObject();
        object.put("total",count);
        object.put("detailModelList",jsonArray);
        object.put("currPage",page);
        object.put("pageSize",pageSize);
        return object;
    }
    public void doorOrderOutExcel(String orderId,String patientName,String patientPhone,String hospitalCode,
                                  Integer status,String createTimeStart,String createTimeEnd,String serverDoctorName,String doctorCode,Integer examPaperStatus, HttpServletResponse response)throws Exception{
        WritableWorkbook book = null;
        OutputStream os = null;
        try {
            String sql = "select DISTINCT o.id as orderId,o.number,o.status,f.hospital,f.hospital_name as hospitalName1,o.is_trans_other_org," +
                    " o.transed_org_code,h.name as hospitalName2,o.patient_name,f.idcard,o.doctor_sign_time,o.total_fee," +
                    " o.patient_phone,o.remark,o.create_time,o.patient as patientCode from wlyy_door_service_order o " +
                    " LEFT JOIN wlyy_sign_family f ON f.patient = o.patient AND f. STATUS = 1 AND f.expenses_status = 1 " +
                    " LEFT JOIN dm_hospital h on h.code=o.transed_org_code and h.del=1 " ;
            if(!StringUtils.isEmpty(serverDoctorName)){
                sql+=" RIGHT JOIN wlyy_door_doctor d on d.order_id = o.id";
            }
            sql+=" where 1=1 ";
            if (!StringUtils.isEmpty(orderId)) {
                sql += " and o.id = '" + orderId + "'";
            }
            if (!StringUtils.isEmpty(patientName)) {
                sql += " and o.patient_name like '%" + patientName + "%'";
            }
            if (!StringUtils.isEmpty(patientPhone)) {
                sql += " and o.patient_phone ='" + patientPhone + "'";
            }
            if (StringUtils.isNotBlank(hospitalCode) && !hospitalCode.contains("%")) {
                sql += " and (f.hospital = '" + hospitalCode + "' or o.transed_org_code='" + hospitalCode + "') ";
            }else if(StringUtils.isNotBlank(hospitalCode) && hospitalCode.contains("%")){
                sql += " and (f.hospital like '" + hospitalCode + "' or o.transed_org_code like '" + hospitalCode + "') ";
            }
            if (status != null) {
                sql += " and o.status ='" + status + "'";
            }
            if (!StringUtils.isEmpty(createTimeStart)) {
                sql += " and o.create_time >='" + createTimeStart + "'";
            }
            if (!StringUtils.isEmpty(createTimeEnd)) {
                sql += " and o.create_time <='" + createTimeEnd + "'";
            }
            if(!StringUtils.isEmpty(serverDoctorName)){
                sql+=" and d.doctor_name like '%"+serverDoctorName+"%'";
            }
            if(!StringUtils.isEmpty(doctorCode)){
                sql+=" and o.doctor='"+doctorCode+"'";
            }
            if(examPaperStatus!=null){
                sql+=" and o.exam_paper_status='"+examPaperStatus+"'";
            }
            sql += " order by o.create_time desc ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            response.setContentType("application/vnd.ms-excel");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "上门服务工单列表";
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "_" + sdf.format(date) + ".xls");
            os = response.getOutputStream();
            book = Workbook.createWorkbook(os);
            WritableSheet sheet = book.createSheet("按工单", 0);
            WritableCellFormat cellFormat = new WritableCellFormat();
            cellFormat.setAlignment(Alignment.CENTRE);
            sheet.addCell(new Label(0, 0, "服务工单号",cellFormat));
            sheet.addCell(new Label(1, 0, "工单状态",cellFormat));
            sheet.addCell(new Label(2, 0, "服务机构",cellFormat));
            sheet.addCell(new Label(3, 0, "创建时间",cellFormat));
            sheet.addCell(new Label(4, 0, "居民姓名",cellFormat));
            sheet.addCell(new Label(5, 0, "性别",cellFormat));
            sheet.addCell(new Label(6, 0, "年龄",cellFormat));
            sheet.addCell(new Label(7, 0, "身份证号",cellFormat));
            sheet.addCell(new Label(8, 0, "联系方式",cellFormat));
            sheet.addCell(new Label(9, 0, "服务时间",cellFormat));
            sheet.addCell(new Label(10, 0, "服务医生",cellFormat));
            sheet.addCell(new Label(11, 0, "医生职称",cellFormat));
            sheet.addCell(new Label(12, 0, "支付费用",cellFormat));
            sheet.addCell(new Label(13, 0, "服务内容",cellFormat));
            sheet.addCell(new Label(14, 0, "服务项价格",cellFormat));
            int b = 0;
            for (int i = 0; i < list.size(); i++) {
                String orderIdTemp = list.get(i).get("orderId") + "";
                //获取服务项费用和医生出诊费
                List<WlyyDoorFeeDetailDO> feeDetailDOs = doorFeeDetailDao.findByOrderIdAndType(orderIdTemp, 1);
                feeDetailDOs.addAll(doorFeeDetailDao.findByOrderIdAndType(orderIdTemp, 2));
                Integer a = feeDetailDOs.size();
                if(a>1){
                    for (int j = 0; j < 13; j++) {
                        sheet.mergeCells(j, b + 1, j, b + a);
                    }
                }
                a = (a==0?1:a);
                String serverCode = list.get(i).get("number") + "";
                sheet.addCell(new Label(0, b + 1, serverCode,cellFormat));//服务工单号
                Integer statustemp = Integer.valueOf(list.get(i).get("status") + "");
                String statusName = "";
                switch (statustemp) {
                    case -1:
                        statusName = "已取消";
                        break;
                    case 1:
                        statusName = "待派单";
                        break;
                    case 2:
                        statusName = "待接单";
                        break;
                    case 3:
                        statusName = "已接单";
                        break;
                    case 4:
                        statusName = "待服务";
                        break;
                    case 5:
                        statusName = "待评价";
                        break;
                    case 6:
                        statusName = "已完成";
                        break;
                }
                sheet.addCell(new Label(1, b + 1, statusName,cellFormat));//工单状态
                //工单是否转给其他机构,0-不转,1-已转
                String transOtherOrg = list.get(i).get("is_trans_other_org") + "";
                String hospitalName = null;
                if ("0".equals(transOtherOrg)) {
                    hospitalName = list.get(i).get("hospitalName1") + "";//签约表中的机构
                } else if ("1".equals(transOtherOrg)) {
                    hospitalName = list.get(i).get("hospitalName2") + "";//转机构中的机构
                }else if("null".equals(transOtherOrg)){
                    hospitalName = list.get(i).get("hospitalName1") + "";//签约表中的机构
                }
                sheet.addCell(new Label(2, b + 1, hospitalName,cellFormat));//服务机构
                Date createTime = (Date) list.get(i).get("create_time");
                sheet.addCell(new Label(3, b + 1, DateUtil.dateToStr(createTime, "yyyy/MM/dd HH:mm"),cellFormat));//创建时间
                sheet.addCell(new Label(4, b + 1, list.get(i).get("patient_name") + "",cellFormat));//居民姓名
                String idcard = list.get(i).get("idcard") + "";
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                String sex = IdCardUtil.getSexNameForIdcard_new(idcard);
                sheet.addCell(new Label(5, b + 1, sex,cellFormat));//性别
                sheet.addCell(new Label(6, b + 1, age + "",cellFormat));//年龄
                sheet.addCell(new Label(7, b + 1, idcard,cellFormat));//身份证
                sheet.addCell(new Label(8, b + 1, list.get(i).get("patient_phone") + "",cellFormat));//联系方式
                Date doctorSignTime = list.get(i).get("doctor_sign_time") != null ? (Date) list.get(i).get("doctor_sign_time") : null;
                sheet.addCell(new Label(9, b + 1, doctorSignTime != null ? DateUtil.dateToStr(doctorSignTime, "yyyy/MM/dd HH:mm") : "",cellFormat));//服务时间
                List<WlyyDoorDoctorDO> doorDoctorDOs = doorDoctorDao.findByOrderId(orderIdTemp);
                String serverDoctors = "";
                String serverDoctorJobName = "";
                for (WlyyDoorDoctorDO one : doorDoctorDOs) {
                    serverDoctors += "/" + one.getDoctorName();
                    serverDoctorJobName += "/" + one.getDoctorJobName();
                }
                sheet.addCell(new Label(10, b + 1, serverDoctors.startsWith("/") ? serverDoctors.substring(1) : serverDoctors,cellFormat));//服务医生
                sheet.addCell(new Label(11, b + 1, serverDoctorJobName.startsWith("/") ? serverDoctorJobName.substring(1) : serverDoctorJobName,cellFormat));//医生职称
                sheet.addCell(new Label(12, b + 1, list.get(i).get("total_fee")!=null?list.get(i).get("total_fee")+"":""));//医生职称
                for (int d = 0; d < feeDetailDOs.size(); d++) {
                    sheet.addCell(new Label(13, b + 1 + d, feeDetailDOs.get(d).getName(),cellFormat));//服务内容
                    sheet.addCell(new Label(14, b + 1 + d, feeDetailDOs.get(d).getFee().toString(),cellFormat));//服务项价格
                }
                b = b + a;
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if(book!=null){
                book.write();
                book.close();
            }
            if(os!=null){
                os.flush();
                os.close();
            }
        }
    }
    /**
     * 居民拍照确认
     * @param orderId
     * @param finishWay
     * @param finishImg
     * @param level
     * @return
     */
    public WlyyDoorServiceOrderDO savePatientSignOrCertificate(String orderId, Integer finishWay, String finishImg, Integer level) throws Exception {
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
        one.setPatientConfirmFinishWay(finishWay);
        one.setPatientConfirmFinishImg(finishImg);
        one.setStatus(WlyyDoorServiceOrderDO.Status.waitForCommnet.getType());
        one.setPatientConfirmFinishTime(new Date());
        // 更新记录
        this.setUpdateColumnInfo(one);
        // 计算保存服务总的支付费用
        Integer times = wlyyDoorServiceOrderService.countPatientDoorTimes(one.getPatient());
        String jsonData = this.serverPackagePriceByOrderId(orderId);
        doorServiceOrderDao.save(one);
        WlyyDoorServiceOrderDO doorServiceOrderDO = this.getDoorServiceOrderById(orderId, level);
        // 发送微信通知  待付款
        BasePatientDO patient = patientInfoService.findById(one.getPatient());
        // 获取微信模板 smfwdwk-上门服务待付款
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {
/*            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","fwyspf");
            String first = templateConfig.getFirst();
            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
            first = first .replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "服务医生评分");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            json.put("id",orderId);
            //json.put("consult",consult.getCode());
            WlyyDoorCommentDO wlyyDoorCommentDO = this.DoorCommentDao.selectCommentDoctor(patient.getCode(),orderId);
            String finish="";
            if(wlyyDoorCommentDO!=null){
                finish = "0";
                json.put("finish",finish);
            }else {
                finish = "1";
                json.put("finish",finish);
            }
            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 31, patient.getOpenid(), patient.getName(), json);*/
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return doorServiceOrderDO;
    }
    /**
     * 医生补录报告
     * @param orderId
     * @param examPaperWay
     * @param examPaperTime
     * @param examPaperImg
     * @return
     */
    public WlyyDoorServiceOrderDO saveExamPaperInfo(String orderId, Integer examPaperWay, String examPaperTime, String examPaperImg, Integer level) throws Exception {
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
        one.setExamPaperUploadWay(examPaperWay);
        one.setExamPaperUploadTime(DateUtil.strToDate(examPaperTime));
        one.setExamPaperImgs(examPaperImg);
        one.setExamPaperStatus(2);
        // 更新记录
        this.setUpdateColumnInfo(one);
        doorServiceOrderDao.save(one);
        return this.getDoorServiceOrderById(orderId, level);
    }
    /**
     * 医生线下确认收款
     * @param orderId
     * @param level
     */
    public WlyyDoorServiceOrderDO confirmReceipt(String orderId, Integer level) throws Exception {
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
        one.setPayWay(WlyyDoorServiceOrderDO.PayWay.offLine.getType());    // 1-微信支付,2-线下支付(居民自己向医院支付,具体怎么支付由医院来定)
        one.setPayTime(new Date());
        one.setStatus(WlyyDoorServiceOrderDO.Status.waitForCommnet.getType());   // 5-待评价
        // 更新记录
        this.setUpdateColumnInfo(one);
        doorServiceOrderDao.save(one);
        // 更新居民签约服务包服务项次数
        this.reduceServiceItemTimes(serverPackagePriceByOrderId(orderId), one.getPatient());
        // 发送微信消息通知--用户评价
/*        BasePatientDO patient = patientInfoService.findById(one.getPatient());
        // 获取微信模板  fwyspf-服务医生评分
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","fwyspf");
            String first = templateConfig.getFirst();
            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
            first = first .replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
            String keyword1 = templateConfig.getKeyword1();
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "服务医生评分");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            json.put("id",orderId);
            //json.put("consult",consult.getCode());
            WlyyDoorCommentDO wlyyDoorCommentDO = this.DoorCommentDao.selectCommentDoctor(patient.getCode(),orderId);
            String finish="";
            if(wlyyDoorCommentDO!=null){
                finish = "0";
                json.put("finish",finish);
            }else {
                finish = "1";
                json.put("finish",finish);
            }
            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 31, patient.getOpenid(), patient.getName(), json);
        }catch (Exception e){
            logger.error(e.getMessage());
        }*/
        return this.getDoorServiceOrderById(orderId, level);
    }
    /**
     * 设置表修改时间
     * @param one
     * @return
     */
    private void setUpdateColumnInfo(WlyyDoorServiceOrderDO one) {
        one.setUpdateTime(new Date());
        one.setUpdateUser(one.getDoctor());
        one.setUpdateUserName(one.getDoctorName());
    }
    /**
     * 获取该患者本年度服务次数
     * @param patient
     * @return
     */
    public Integer serviceCount(String patient) {
        String sql = "SELECT count(d.id) times FROM wlyy_door_doctor d where d.order_id in(SELECT id from wlyy_door_service_order WHERE DATE_FORMAT(doctor_sign_time, '%Y') = DATE_FORMAT(NOW(), '%Y') AND patient=?)";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, patient);
        return count;
    }
    /**
     * 修改预计到达时间
     * @param orderId
     * @param arrivingTime
     * @return
     */
    public WlyyDoorServiceOrderDO updateArrivingTime(String orderId, String arrivingTime) {
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findOne(orderId);
        one.setDoctorArrivingTime(arrivingTime);
        this.setUpdateColumnInfo(one);
        one = doorServiceOrderDao.save(one);
        // 医生修改预计到达时间保存到日志表中
        WlyyDoorPatientConfirmLogDO confirmLogDO = new WlyyDoorPatientConfirmLogDO();
        confirmLogDO.setOrderId(one.getId());
        confirmLogDO.setPatient(one.getPatient());
        confirmLogDO.setPatientName(one.getPatientName());
        confirmLogDO.setType(2); // 1-确认基础信息无误或变更,2-确认上门医生变更上门信息,3-同意工单转接
        confirmLogDO.setDescription("医生修改预计到达时间");
        confirmLogDO.setCreateTime(new Date());
        confirmLogDO.setCreateUser(one.getDoctor());
        confirmLogDO.setCreateUserName(one.getDoctorName());
        confirmLogDao.save(confirmLogDO);
        return one;
    }
    /**
     * 查看指定医生是否开启分派订单功能
     * @param doctor
     * @return
     */
    public String findDispatchStatusByDoctor(String doctor) {
        WlyyDoorDoctorStatusDO doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        BaseDoctorDO doctorVO = doctorDao.findById(doctor);
        if (null == doctorSwitch) {
            WlyyDoorDoctorStatusDO wlyyDoorDoctorStatusDO =new WlyyDoorDoctorStatusDO();
            wlyyDoorDoctorStatusDO.setDoctor(doctor);
            wlyyDoorDoctorStatusDO.setStatus(5);
            wlyyDoorDoctorStatusDO.setCreateTime(new Date());
            wlyyDoorDoctorStatusDO.setCreateUser(doctor);
            wlyyDoorDoctorStatusDO.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
            doctorStatusDao.save(wlyyDoorDoctorStatusDO);
            return "0";
        }
        return doctorSwitch.getStatus() == 5 ? "0" : "1";
    }
    /**
     * 修改指定医生的分派订单开关,不存在该医生的开关,则创建
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusByDoctor(String doctor, Integer dispatchOrderStatus) {
        WlyyDoorDoctorStatusDO doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        BaseDoctorDO doctorVO = doctorDao.findById(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
            doctorSwitch.setCreateUser(doctor);
            doctorSwitch.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        } else {
            doctorSwitch = new WlyyDoorDoctorStatusDO();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser(doctor);
            doctorSwitch.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        doctorStatusDao.save(doctorSwitch);
    }
    /**
     * 系统更新医生上门服务工单状态
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusBySystem(String doctor, Integer dispatchOrderStatus) {
        WlyyDoorDoctorStatusDO doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        } else {
            doctorSwitch = new WlyyDoorDoctorStatusDO();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        }
        doctorStatusDao.save(doctorSwitch);
    }
    /**
     * 更新调度员响应时间
     * @param orderId
     * @throws Exception
     */
    public void updateDispatcherResponseTime(String orderId)throws Exception{
        int t = doorServiceOrderDao.updateDispatcherResponseTime(orderId,new Date());
        if(t<0){
            throw new Exception("updateDispatcherResponseTime error!");
        }
    }
    /**
     * 更新服务医生响应时间
     * @param orderId
     * @throws Exception
     */
    public void updateServiceResponseTime(String orderId)throws Exception{
        int t = doorServiceOrderDao.updateServiceResponseTime(orderId,new Date());
        if(t<0){
            throw new Exception("updateServiceResponseTime error!");
        }
    }
    /**
     * 根据服务项计算服务费用
     * @param jsonData 格式[{"itemCode":"","fee":"","number":""}]
     * @param patient 居民code
     * @return
     */
    public Map<String, Object> countServerPackagePrice(String jsonData, String patient){
        Map<String, Object> map = new HashMap<>();
        BigDecimal serverPackagePrice = new BigDecimal("0.00");
        BigDecimal cashPrice = new BigDecimal("0.00");
        //获取居民签约服务项及次数
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        String sql = "SELECT ip.service_item_code as itemCode, sum(ip.service_times) as times  FROM wlyy_server_package_patient pp , wlyy_server_package_item_patient ip " +
                "where pp.`code` = ip.server_package_patient_code and  pp.patient = '" + patient + "' and pp.hospital = '" + "" + "' and pp.`status` = 1 " +
//                "where pp.`code` = ip.server_package_patient_code and  pp.patient = '" + patient + "' and pp.hospital = '" + signFamily.getHospital() + "' and pp.`status` = 1 " +
                "GROUP BY ip.service_item_code ";
        List<Map<String, Object>> list =jdbcTemplate.query(sql, new BeanPropertyRowMapper(String.class));
        JSONArray jsonArray = JSONArray.parseArray(jsonData);
        for(Object o : jsonArray){
            Boolean b = false;
            BigDecimal times = null;
            JSONObject jsonObject = (JSONObject) o;
            String itemCode = jsonObject.getString("itemCode");
            BigDecimal fee = jsonObject.getBigDecimal("fee");
            BigDecimal number = jsonObject.getBigDecimal("number");
            //遍历是否是居民签约的服务项,如果是,看还剩多少次数
            for(Map<String, Object> m : list){
                if((m.get(itemCode) + "").equals(itemCode)){
                    b = true;
                    times = (BigDecimal)map.get("times");
                }
            }
            //判断服务包里面的次数是否够抵扣,不够的仍需支付
            if(b){
                if(times.compareTo(number) > -1) {
                    serverPackagePrice = serverPackagePrice.add(fee.multiply(number));
                }else {
                    //还需另外支付次数
                    BigDecimal t = number.subtract(times);
                    cashPrice = cashPrice.add(fee.multiply(t));
                }
            }else {
                cashPrice = cashPrice.add(fee.multiply(number));
            }
        }
        map.put("serverPackagePrice", serverPackagePrice);
        map.put("cashPrice", cashPrice);
        return map;
    }
    /**
     * 更新居民签约服务包服务项次数
     * @param itemInfo 格式[{"itemCode":"","fee":"","number":""}]
     * @param patient 居民code
     */
    public void reduceServiceItemTimes(String itemInfo, String patient){
        Map<String, Object> map = new HashMap<>();
        //获取居民签约服务项及次数
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        String sql = "SELECT ip.`code`,ip.service_item_code as itemCode, ip.service_times as times  FROM wlyy_server_package_patient pp , wlyy_server_package_item_patient ip " +
//                "where pp.`code` = ip.server_package_patient_code and  pp.patient = '" + patient + "' and pp.hospital = '" + signFamily.getHospital() + "' and pp.`status` = 1 " +
                "where pp.`code` = ip.server_package_patient_code and  pp.patient = '" + patient + "' and pp.hospital = '" + "" + "' and pp.`status` = 1 " +
                "order BY pp.end_time ";
        List<Map<String, Object>> list =jdbcTemplate.query(sql, new BeanPropertyRowMapper(String.class));
        JSONArray jsonArray = JSONArray.parseArray(itemInfo);
        for(Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            String itemCode = jsonObject.getString("itemCode");
            Integer number = jsonObject.getInteger("number");
            //遍历是否是居民签约的服务项,如果是,看服务项次数够不够减,不够减的继续遍历其他服务项,够减则跳出循环更新次数
            for (Map<String, Object> m : list) {
                if ((m.get(itemCode) + "").equals(itemCode)) {
                    String itemPatientCode = map.get("code") + "";
                    Integer times = (Integer) map.get("times");
                    if (number <= times) {
//                        serverPackageItemPatientDao.updateTimesByCode(itemPatientCode, times - number);
                        break;
                    } else {
//                        serverPackageItemPatientDao.updateTimesByCode(itemPatientCode, 0);
                        number -= times;
                    }
                }
            }
        }
    }
    /**
     * 获取订单下服务包数量、单价
     * @param orderId
     * @return
     * @throws Exception
     */
    public String serverPackagePriceByOrderId(String orderId) throws Exception {
        String sql = "SELECT d.code itemCode,sum(d.number) number,fee from wlyy_door_fee_detail d where order_id=? and d.status in(1,2) and type=1 GROUP BY code";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, orderId);
        return objectMapper.writeValueAsString(mapList);
    }
    /**
     * 待支付总费用
     * @param cashPrice
     * @param orderId
     * @param level
     * @return
     */
    public BigDecimal calculateCash(String cashPrice, String orderId, Integer level, Integer times) {
        BigDecimal price = new BigDecimal(cashPrice);
        List<WlyyDoorDoctorDO> doorDoctorDOList = doorDoctorDao.findByOrderId(orderId);
        if (doorDoctorDOList != null && doorDoctorDOList.size() > 0) {
            List<String> jobCodeList = doorDoctorDOList.stream().map(WlyyDoorDoctorDO::getDoctorJobCode).collect(Collectors.toList());
//            Double jobFeeCost = dmJobService.getJobFeeCost(jobCodeList, level, times);
            Double jobFeeCost = 120d;
            if(null != jobFeeCost){
                price = price.add(BigDecimal.valueOf(jobFeeCost));
            }
        }
        return price;
    }
    /**
     * 出诊费用详情
     * @param orderId
     * @param level
     * @return
     */
    public List<WlyyDoorDoctorDO> djDetailList(String orderId, Integer level, Integer times) {
        List<WlyyDoorDoctorDO> djDetailList = new ArrayList<>();
        List<WlyyDoorDoctorDO> doorDoctorDOList = doorDoctorDao.findByOrderId(orderId);
        if (doorDoctorDOList != null && doorDoctorDOList.size() > 0) {
            for(WlyyDoorDoctorDO wlyyDoorDoctorDO:doorDoctorDOList){
//                Double jobFeeCost = dmJobService.getJobFee(wlyyDoorDoctorDO.getDoctorJobCode(), level, times);
                Double jobFeeCost = 120d;
                wlyyDoorDoctorDO.setJobFeeCost(jobFeeCost);
                doorDoctorDao.save(wlyyDoorDoctorDO);
                djDetailList.add(wlyyDoorDoctorDO);
            }
        }
        return djDetailList;
    }
    /**
     * 获取用户人群类型名称
     * @param patientCode
     * @return
     */
    public String getTypeValueByPatientCode(String patientCode) {
        List<String> typeValueList = doorServiceVoucherDao.findTypeValueByPatientCode(patientCode);
        String typeValues = "";
        if (typeValueList != null && typeValueList.size() > 0) {
            typeValues = StringUtils.join(typeValueList, ",");
        }
        return typeValues;
    }
    /**
     * 修改保存服务项
     * @param jsonData
     */
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public void updatePackageItemInfo(String jsonData) {
        JSONObject jsonObjectParam = JSONObject.parseObject(jsonData);
        String orderId = String.valueOf(jsonObjectParam.get("orderId"));
        WlyyDoorServiceOrderDO order = doorServiceOrderDao.findOne(orderId);
        // 删除出诊医生或服务项
        wlyyDoorServiceOrderService.orderWithFeeDelete(jsonObjectParam,order);
        // 更新服务包信息
        wlyyDoorServiceOrderService.orderWithPackageItemFeeAdd(new JSONObject(), jsonObjectParam, order);
        // 发送微信模板消息,通知居民服务项目已经变更(smyyyjjd-服务项目变更通知)
/*        BasePatientDO patient = patientInfoService.findById(order.getProxyPatient());
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        Integer status = 0;
        try{
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","fwxmbgtz");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(patient.getName()==null?"":patient.getName()));
            first = first .replace("key2", null != order.getDoctorName() ? order.getDoctorName() : "");
            String keyword1 = templateConfig.getKeyword1();
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "服务项目变更确认");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            json.put("consult",consult.getCode());
            json.put("status",status);
//            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 32, patient.getOpenid(), patient.getName(), json);
        }catch (Exception e) {
            logger.error(e.getMessage());
        }*/
    }
    /**
     * 获取管理员端上门服务菜单分类
     * @param hospital
     * @return
     */
    public Map<String,String> getAdministratorStatusBarNum(String hospital) {
        String sql = " select o.`status`,count(o.id) as num  from wlyy_door_service_order o  LEFT JOIN wlyy_sign_family f ON f.patient = o.patient " +
                "AND f. STATUS = 1 AND f.expenses_status = 1  LEFT JOIN dm_hospital h on h.code=o.hospital and h.del=1  ";
        if(!"350200%".equals(hospital)){
            sql += " where  (f.hospital like '" + hospital + "' or o.transed_org_code like '" + hospital + "') GROUP BY o.`status` ";
        }else{
            sql += " GROUP BY o.`status` ";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Map<String, String> map = new HashMap<>();
        list.stream().forEach(one -> {
            map.put(exchangeKeyName(String.valueOf(one.get("status"))), String.valueOf(one.get("num")));
        });
        if (!map.containsKey("cancelOrder")) {
            map.put("cancelOrder", "0");
        }
        if (!map.containsKey("sendOrder")) {
            map.put("sendOrder", "0");
        }
        if (!map.containsKey("waitingOrder")) {
            map.put("waitingOrder", "0");
        }
        if (!map.containsKey("serviceOrder")) {
            map.put("serviceOrder", "0");
        }
        if (!map.containsKey("payment")) {
            map.put("payment", "0");
        }
        if (!map.containsKey("supplement")) {
            map.put("supplement", "0");
        }
        if (!map.containsKey("completed")) {
            map.put("completed", "0");
        }
        return map;
    }
    public WlyyDoorServiceOrderDO findById(String orderId) {
        return doorServiceOrderDao.findOne(orderId);
    }
    /**
     * 对mht模板文件的变量赋值
     * @param doc
     * @param orderId
     * @return
     */
    public String handleData(Document doc, String orderId) {
        WlyyDoorServiceOrderDO orderDO = doorServiceOrderDao.findOne(orderId);
        WlyyDoorConclusionDO conclusionDO = doorConclusionDao.findByOrderId(orderId);//808080f66e5efb24016e62838d77000a
        String html = doc.toString();
        //对各个字段赋值
        html = html.replace("${name}", orderDO.getPatientName());
        html = html.replace("${sex}",conclusionDO.getSex() == null ? "" : conclusionDO.getSex());
        html = html.replace("${age}",conclusionDO.getAge() + "");
        html = html.replace("${marriage}",conclusionDO.getMarriage() == null ? "" : conclusionDO.getMarriage());
        html = html.replace("${profession}",conclusionDO.getProfession() == null ? "" : conclusionDO.getProfession());
        html = html.replace("${nationa}", conclusionDO.getNationa() == null ? "" : conclusionDO.getNationa());
        html = html.replace("${birthplace}",conclusionDO.getBirthPlace() == null ? "" : conclusionDO.getBirthPlace());
        html = html.replace("${idcard}",conclusionDO.getIdcard() == null ? "" : conclusionDO.getIdcard());
        html = html.replace("${company}",conclusionDO.getCompany()  == null ? "" : conclusionDO.getCompany());
        html = html.replace("${address}",conclusionDO.getAddress()  == null ? "" : conclusionDO.getAddress());
        html = html.replace("${phone}", conclusionDO.getPatientPhone() == null ? "" : conclusionDO.getPatientPhone());
        html = html.replace("${count}", StringUtils.isBlank(conclusionDO.getServiceCount() + "") ? "" : conclusionDO.getServiceCount() + "");
        html = html.replace("${proxypatientname}", conclusionDO.getProxyPatientName() == null ? "" : conclusionDO.getProxyPatientName());
        html = html.replace("${proxypatientrelation}", conclusionDO.getProxyPatientRelation() == null ? "" : conclusionDO.getProxyPatientRelation());
        html = html.replace("${proxypatientphone}", conclusionDO.getProxyPatientPhone() == null ? "" : conclusionDO.getProxyPatientPhone());
        html = html.replace("${beforerecord}", conclusionDO.getBeforeRecord() == null ? "" : conclusionDO.getBeforeRecord());
        html = html.replace("${presenillness}", conclusionDO.getPresenIllness() == null ? "" : conclusionDO.getPresenIllness());
        html = html.replace("${familyillhistory}", conclusionDO.getFamilyIllHistory() == null ? "" : conclusionDO.getFamilyIllHistory());
        html = html.replace("${physicalrecord}", conclusionDO.getPhysicalRecord() == null ? "" : conclusionDO.getPhysicalRecord());
        html = html.replace("${assistantexamrecord}", conclusionDO.getAssistantExamRecord() == null ? "" : conclusionDO.getAssistantExamRecord());
        html = html.replace("${diagnosticrecord}", conclusionDO.getDiagnosticRecord() == null ? "" : conclusionDO.getDiagnosticRecord());
        html = html.replace("${examresult}",conclusionDO.getExamResult() == null ? "" : conclusionDO.getExamResult());
        String imgsString = "";
        if(StringUtils.isNotBlank(conclusionDO.getImgs())) {
            String imgs = conclusionDO.getImgs();
            String[] imgsArray;
            if (imgs.contains(",")) {
                imgsArray = imgs.split(",");
            } else {
                imgsArray = new String[]{imgs};
            }
            for (String img : imgsArray) {
                imgsString += "<img width=80 height=100 src=" + imgUrlDomain + img + " >&nbsp;";
            }
        }
        html = html.replace("${imgs}", imgsString);
        if(orderDO.getPatientConfirmFinishImg() != null) {
            html = html.replace("${patientconfirmfinishimg}", "<img width=100 height=100 src=" + imgUrlDomain + orderDO.getPatientConfirmFinishImg() + " >");
        }else {
            html = html.replace("${patientconfirmfinishimg}","");
        }
        if(orderDO.getPatientConfirmFinishTime() != null) {
            html = html.replace("${patientconfirmtime}", DateUtil.dateToStr(orderDO.getPatientConfirmFinishTime(), "yyyy年MM月dd日"));
        }else {
            html = html.replace("${patientconfirmtime}","");
        }
        html = html.replace("${updatetime}",DateUtil.dateToStr(conclusionDO.getUpdateTime(), "yyyy年MM月dd日"));
        return html;
    }
    public int sendInformedConsent(String orderId , String serveDesc,String doctor) {
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        String sql1 = "select fd.name name from wlyy_door_fee_detail fd LEFT JOIN wlyy_door_doctor dd ON fd.order_id = dd.order_id where fd.order_id = \""+ orderId +"\" AND fd.type = 1 group by code";
        List<Map<String , Object>> list = jdbcTemplate.queryForList(sql1);
        Object object = null;
        JSONObject orderInfoContent = new JSONObject();
        if(list.size()>0){
            for (int i=0;i<list.size();i++) {
                Map map=(Map)list.get(i);
                Iterator iterator = map.keySet().iterator();
                while (iterator.hasNext())
                {
                    String key = (String) iterator.next();
                    object = map.get(key);
                }
            }
            String str = object.toString();
            String noticeContent = str;
            orderInfoContent.put("noticeContent", noticeContent);//服务项目
            orderInfoContent.put("orderId", orderId);
            orderInfoContent.put("contentSize", list.size());
        }else {
            orderInfoContent.put("noticeContent", "居民未选择");//服务项目
            orderInfoContent.put("orderId", orderId);
            orderInfoContent.put("contentSize", list.size());
        }
        int success = this.qucikSendIM(doorServiceOrderDO.getId(), doctor, "智能助手","2105", orderInfoContent.toString());
        String sql = "UPDATE `wlyy_door_service_order` SET order_info =1 WHERE id = \""+orderId+"\";";
        jdbcTemplate.execute(sql);
        return  success;
    }
    public int updateServiceStatus(String orderId) {
        String sql = "UPDATE `wlyy_door_service_order` SET service_status =2 WHERE id = ?";
        Object [] params = new Object[]{orderId};
        int a = jdbcTemplate.update(sql , params);
        return  a;
    }
    /**
     * 【调度员,医生】快速发送IM消息
     * @param orderId
     * @param sendId
     * @param sendName
     * @param content
     * @return
     */
    public int qucikSendIM(String orderId,String sendId,String sendName,String contentType,String content) {
        int result = -1;
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        if (null == consult) {
            logger.error("当前工单未关联咨询,工单id:" + orderId);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = null;
        String response = null;
        if(org.apache.commons.lang3.StringUtils.isBlank(sendId)){
            wlyyDoorServiceOrder  = wlyyDoorServiceOrderDao.findOne(orderId);
            response = imUtill.sendTopicIM(wlyyDoorServiceOrder.getDispatcher(), "智能助手", consult.getId(), contentType, content, null);
        }else{
            response = imUtill.sendTopicIM(sendId, sendName, consult.getId(), contentType, content, null);
        }
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getIntValue("status") == -1) {
            logger.error("知情同意书消息发送失败:" + resObj.getString("message"));
            return result;
        }
        result = 1;
        return result;
    }
    public File writeWordFile(List<String> orderId,HttpServletResponse response) throws Exception {
        String zipFileName = "服务小结";
        long time = System.currentTimeMillis();
        String exportConclusionList = time+"exportList";
        String path = this.getClass().getResource("/").getPath() + exportConclusionList;
        File file = new File(path);
        // 删除文件夹、文件
        if (file.exists()) {
            if (file != null){
                deleteFolder(file);
                file.mkdir();
            }else {
                file.delete();
                file.mkdir();
            }
        }else {
            file.mkdir();
        }
        int j =1;
        for (int i = 0; i < orderId.size(); i++) {
            WlyyDoorServiceOrderDO orderDO = this.findById(orderId.get(i));
            // 文件名
            WlyyDoorConclusionDO conclusionDO = doorConclusionDao.findByOrderId(orderId.get(i));
            if (conclusionDO == null){
                continue;
            }
            String fileName = orderDO.getPatientName()+ j + "服务小结.doc";;
            j = j + 1;
            fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
            fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            String pathName = this.getClass().getResource("/").getPath() + "conclusion.mht";
            System.out.println("路径pathName:" + pathName);
            Document doc = Jsoup.parse(new File(pathName), "UTF-8");
            String html = this.handleData(doc, orderId.get(i));//16
            BufferedWriter bw = new BufferedWriter(new FileWriter(path+"/"+fileName));//创建的文件
            bw.write(html);
            bw.close();
            File zipFile = new File(path.replace(exportConclusionList, "") + zipFileName + ".zip");
            if (zipFile.exists()) {
                zipFile.delete();
            }
        }
        // 打包文件夹
        if (fileToZip(path, path.replace(exportConclusionList, ""), zipFileName)) {
            return new File(path.replace(exportConclusionList, "") + zipFileName + ".zip");
        } else {
            return null;
        }
    }
    /**
     * 打包文件夹
     *
     * @param sourcePath
     * @param zipPath
     * @param zipName
     * @return
     * @throws Exception
     */
    public boolean fileToZip(String sourcePath, String zipPath, String zipName) throws Exception {
        File sourceFile = new File(sourcePath);
        File zipFile = new File(zipPath + File.separator + zipName + ".zip");
        File[] files = sourceFile.listFiles();
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        if (files != null) {
            byte[] bufs = new byte[1024 * 10];
            for (int i = 0; i < files.length; i++) {
                // 创建ZIP实体,并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(files[i].getName());
                zos.putNextEntry(zipEntry);
                // 读取待压缩的文件并写进压缩包里
                FileInputStream fis = new FileInputStream(files[i]);
                BufferedInputStream bis = new BufferedInputStream(fis, 1024 * 10);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                    zos.write(bufs, 0, read);
                }
                bis.close();
                fis.close();
            }
            deleteFolder(sourceFile);
        }
        zos.close();
        fos.close();
        return true;
    }
    /**
     * 把is写入到对应的word输出流os中
     * 不考虑异常的捕获,直接抛出
     * @param is
     * @param os
     * @throws IOException
     */
    private void inputStreamToWord(InputStream is, OutputStream os) throws IOException {
        POIFSFileSystem fs = new POIFSFileSystem();
        //对应于org.apache.poi.hdf.extractor.WordDocument
        fs.createDocument(is, "WordDocument");
        fs.writeFilesystem(os);
        os.close();
        is.close();
    }
    /**
     * 把输入流里面的内容以UTF-8编码当文本取出。
     * 不考虑异常,直接抛出
     * @param ises
     * @return
     * @throws IOException
     */
    private String getContent(InputStream... ises) throws IOException {
        if (ises != null) {
            StringBuilder result = new StringBuilder();
            BufferedReader br;
            String line;
            for (InputStream is : ises) {
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line=br.readLine()) != null) {
                    result.append(line);
                }
            }
            return result.toString();
        }
        return null;
    }
   public static void deleteFolder(File folder){
        File[] files  = folder.listFiles();
        if (files != null){
            for(File f: files){
                if (f.isDirectory()){
                    deleteFolder(f);
                }else {
                    f.delete();
                }
            }
        }
        folder.delete();
   }
   public List<Map<String,Object>> getOrderIdList(Integer status,String doctorCode){
       String sqlList = "select DISTINCT o.id as orderId";
       String sql = " from wlyy_door_service_order o " +
               " LEFT JOIN wlyy_sign_family f ON f.patient = o.patient AND f. STATUS = 1 AND f.expenses_status = 1 " +
               " LEFT JOIN dm_hospital h on h.code=o.hospital and h.del=1 "
               +" LEFT JOIN wlyy_door_doctor d on d.order_id = o.id ";
       sql+= " where 1=1 ";
       if(status == 6){//已完成状态
           sql+=" and o.status ='"+status+"'";
       }else {//5是待补录状态
           sql+=" and o.conclusion_status =1 ";
       }
       if(!StringUtils.isEmpty(doctorCode)){
           sql+=" and (d.doctor='"+doctorCode+"' or o.doctor='"+doctorCode+"')";
       }
       sql+=" order by o.create_time desc ";
       List<Map<String,Object>> list = jdbcTemplate.queryForList(sqlList+sql);
        return list;
   }
}

+ 639 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorServiceApplicationService.java

@ -0,0 +1,639 @@
package com.yihu.jw.door.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.door.dao.DoorServiceApplicationDao;
import com.yihu.jw.door.dao.DoorServiceVoucherDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceApplicationDo;
import com.yihu.jw.entity.door.WlyyDoorServiceVoucherDo;
import com.yihu.jw.entity.hospital.family.WlyyPatientFamilyMemberDO;
import com.yihu.jw.hospital.family.dao.WlyyPatientFamilyMemberDao;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.util.*;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务
 */
@Service
@Transactional
public class DoorServiceApplicationService {
    @Autowired
    private DoorServiceApplicationDao doorServiceApplicationDao;
    @Autowired
    private DoorServiceVoucherDao doorServiceVoucherDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    Map<Integer, String> relations = new HashMap<>();
    @Autowired
    BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorInfoService;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private WlyyPatientFamilyMemberDao patientFamilyMemberDao;
/*    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;*/
    @Autowired
    private WlyyDoorServiceOrderService doorServiceOrderService;
    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
        relations.put(8, "免疫关联");
    }
    /**
     * 获取当前登录居民开通服务情况及取消订单情况
     * @param patientCode
     * @return
     */
    public JSONObject findPatientOnsiteService(String patientCode) throws Exception {
        JSONObject jsonObject = new JSONObject();
        ObjectMapper objectMapper = new ObjectMapper();
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = findOnsiteServiceByPatient(patientCode);
        jsonObject.put("onsiteFlag", false);
        jsonObject.put("wlyyDoorServiceApplicationDo", "");
        if (null != wlyyDoorServiceApplicationDo.getId()) {
            jsonObject.put("wlyyDoorServiceApplicationDo", objectMapper.writeValueAsString(wlyyDoorServiceApplicationDo));
            jsonObject.put("onsiteFlag", true);
        }
        int cancellation_times = wlyyDoorServiceOrderService.countPtientCancelTimesOneMonth(patientCode);
        jsonObject.put("cancellation_times", cancellation_times);
        return jsonObject;
    }
    /**
     * 获取居民服务申请信息
     * @param patientCode 居民code
     * @return
     */
    public WlyyDoorServiceApplicationDo findOnsiteServiceByPatient(String patientCode) throws Exception{
        //根据居民获取所有申请信息
        List<WlyyDoorServiceApplicationDo> wlyyDoorServiceApplicationDos=doorServiceApplicationDao.findByPatientOrderByCreateTimeDesc(patientCode);
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo=new WlyyDoorServiceApplicationDo();
        if(null!=wlyyDoorServiceApplicationDos&&wlyyDoorServiceApplicationDos.size()>0){
            //获取最新的记录展示
            wlyyDoorServiceApplicationDo=wlyyDoorServiceApplicationDos.get(0);
            List<WlyyDoorServiceVoucherDo> wlyyDoorServiceVoucherDos= doorServiceVoucherDao.findByServiceIdAndStatusOrderBySortAsc(wlyyDoorServiceApplicationDo.getId(),1);
            wlyyDoorServiceApplicationDo.setWlyyDoorServiceVoucherDos(wlyyDoorServiceVoucherDos);
        }
        return wlyyDoorServiceApplicationDo;
    }
    /**
     * 获取居民服务申请状态: -1删除,0审核中,1未通过,2审核通过,3已过期
     * @param patientCode 居民code
     * @return
     */
    public Integer findOnsiteServiceStatusByPatient(String patientCode) throws Exception{
        Integer status=-1;
        //根据居民获取所有申请信息
        List<WlyyDoorServiceApplicationDo> wlyyDoorServiceApplicationDos=doorServiceApplicationDao.findByPatientOrderByCreateTimeDesc(patientCode);
        if(null!=wlyyDoorServiceApplicationDos&&wlyyDoorServiceApplicationDos.size()>0){
            //获取最新的记录展示
            status=wlyyDoorServiceApplicationDos.get(0).getStatus();
        }
        return status;
    }
    /**
     * 获取居民的家庭成员及授权信息
     *
     * @param patient 居民
     * @return
     */
    public JSONArray getPatientFamilyMembers(String patient) throws Exception{
        JSONArray resultArray = new JSONArray();
        //获取当前居民自己的信息
        JSONObject objPatient=findPatientByCode(patient);
        resultArray.put(objPatient);
        //根据居民获取家庭成员基本信息,不包含自己
        String sql = "select t1.family_relation,t1.is_authorize,t2.code,t2.name,t2.sex,t2.birthday,t2.idcard,t2.photo,t2.mobile,t2.address   " +
                " from " +
                "    wlyy_patient_family_member t1, " +
                "    wlyy_patient t2 " +
                " where " +
                "    t2.code in (select family_member from wlyy_patient_family_member where patient = ? ) " +
                "    and t1.patient = ? " +
                "    and t1.family_member = t2.code ";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, new Object[]{patient, patient});
        if (result != null && result.size() > 0) {
            for (Map<String, Object> map : result) {
                JSONObject obj = new JSONObject();
                //根据家庭成员及当前登录人获取授权信息
                WlyyPatientFamilyMemberDO patientFamilyMember=patientFamilyMemberDao.findByPatientAndFamilyMember( map.get("code").toString(),patient);
                Integer isAuthorize = null==patientFamilyMember?0:patientFamilyMember.getIsAuthorize();
                obj.put("code", map.get("code"));
                obj.put("name", map.get("name"));
                obj.put("sex", map.get("sex"));
                //0:未授权,1:已授权
                obj.put("isAuthorize", map.get("is_authorize"));
                obj.put("birthday", map.get("birthday"));
                obj.put("idcard", StringUtils.isEmpty(String.valueOf(map.get("idcard"))) ? "" : map.get("idcard").toString());
                obj.put("photo", map.get("photo"));
                obj.put("mobile", map.get("mobile"));
                obj.put("address", StringUtils.isEmpty(String.valueOf(map.get("address"))) ? "" : map.get("address"));
                obj.put("familyRelation", map.get("family_relation"));
                obj.put("familyRelationName", relations.get(map.get("family_relation")));
                resultArray.put(obj);
            }
        }
        return resultArray;
    }
    /**
     * 根据居民的code获取居民的基本信息
     * @param patient
     * @return
     * @throws Exception
     */
    public JSONObject findPatientByCode(String patient) throws Exception{
        //获取当前居民自己的信息
        BasePatientDO p = patientDao.findById(patient);
        JSONObject obj = new JSONObject();
        //获取家签信息
        obj.put("code", p.getId());
        obj.put("name",p.getName());
        obj.put("age",  IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(),p.getBirthday()));
        obj.put("sex", p.getSex());
        //0:未授权,1:已授权
        obj.put("isAuthorize", 1);
        obj.put("birthday",p.getBirthday());
        obj.put("idcard", p.getIdcard());
        obj.put("photo", p.getPhoto());
        obj.put("mobile", p.getMobile());
        obj.put("address", p.getAddress());
        obj.put("familyRelation", -1);
        obj.put("familyRelationName","本人");
        return obj;
    }
    /**
     * 获取上门服务的机构或区县
     *
     * @param type 类型:1区、2机构
     * @return
     */
    public Set<String> getConfigure(String type) throws Exception{
        String sql = "SELECT c.hospital from wlyy_door_service_configure c WHERE c.content_type='1' AND c.type='" + type + "'  and c.status=1 ";
        List<String> stringSet = jdbcTemplate.queryForList(sql, String.class);
        Set<String> simpleSet = new HashSet<>(stringSet);
        return simpleSet;
    }
    /**
     * 开通上门服务资质评审
     * @param jsonData 资质相关信息
     * @param patient 当前操作的人,可能是医生,可能是居民
     * @param doctorFlag 居民端创建1,医生端创建2
     * @return
     * @throws Exception
     */
    public WlyyDoorServiceApplicationDo create(String doctorFlag,String jsonData, String patient)throws Exception{
        ObjectMapper objectMapper=new ObjectMapper();
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo =objectMapper.readValue(jsonData,WlyyDoorServiceApplicationDo.class);
        BasePatientDO p =patientDao.findById(wlyyDoorServiceApplicationDo.getPatient());
        //判断该居民是否存在未审核的资质申请,若存在则不允许再申请
        List<WlyyDoorServiceApplicationDo> wlyyDoorServiceApplicationDos=doorServiceApplicationDao.findByPatientAndStatus(wlyyDoorServiceApplicationDo.getPatient(),0);
        if(null!=wlyyDoorServiceApplicationDos&&wlyyDoorServiceApplicationDos.size()>0){
            throw new Exception("该居民尚有未审核的上门服务资质申请!");
        }
        //判断该居民是否有权限开通服务
/*        SignFamily signFamilies= signFamilyDao.findSignFamilyByPatient(wlyyDoorServiceApplicationDo.getPatient());
        if(!(null!=signFamilies)){
            throw new Exception("该居民未签约家庭医生!");
        }*/
        //默认先给调度员评审
        if("2".equals(doctorFlag)){
            if(StringUtils.isNotBlank(wlyyDoorServiceApplicationDo.getStatus().toString())&&2==(wlyyDoorServiceApplicationDo.getStatus())){
                if(null==wlyyDoorServiceApplicationDo.getStartTime()||null==wlyyDoorServiceApplicationDo.getEndTime()){
                    throw new Exception("资质有效开始和结束时间不能为空!");
                }
            }
            //代理医生
            BaseDoctorDO doctor=doctorInfoService.findById(patient);
            wlyyDoorServiceApplicationDo.setAuditorType(2);
            wlyyDoorServiceApplicationDo.setAuditTime(new Date());
            wlyyDoorServiceApplicationDo.setProxyPatient(patient);
            wlyyDoorServiceApplicationDo.setProxyPatientName(doctor.getName());
        } else {
            wlyyDoorServiceApplicationDo.setAuditorType(1);
            wlyyDoorServiceApplicationDo.setStatus(0);
            wlyyDoorServiceApplicationDo.setProxyPatient(patient);
            wlyyDoorServiceApplicationDo.setProxyPatientName(p.getName());
        }
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo1 = doorServiceApplicationDao.save(wlyyDoorServiceApplicationDo);
        if(!"2".equals(doctorFlag)){
            //居民申请给调度员发系统消息
/*            List<Map<String, Object>> mapList = findDispatcherByPatient(patient);
            Message message=null;
            for(Map<String,Object> map:mapList){
                if(null!=map.get("code")){
                    message=new Message();
                    message.setCzrq(new Date());
                    message.setCreateTime(new Date());
                    message.setRead(1);
                    message.setState(1);
                    message.setRelationCode(wlyyDoorServiceApplicationDo1.getId().toString());
                    message.setOver("1");
                    //调度员
                    message.setReceiver(map.get("code").toString());
                    message.setSender(wlyyDoorServiceApplicationDo1.getPatient());
                    message.setCode(getCode());
                    message.setTitle("居民资质审核");
                    message.setContent(p.getName()+"提交了资质申请,请及时处理");
                    //消息类型:401为资质申请审核-调度员
                    message.setType(401);
                    message.setDel("1");
                    messageDao.save(message);
                    //发送医生助手模板消息
                    doorServiceOrderService.sendWeixinMessage(1,map.get("code").toString(),wlyyDoorServiceApplicationDo1.getPatient());
                }
            }*/
        }
        wlyyDoorServiceApplicationDo1.setWlyyDoorServiceVoucherDos(wlyyDoorServiceApplicationDo.getWlyyDoorServiceVoucherDos());
        wlyyDoorServiceApplicationDo1 = updateDtoAndSaveVoucher(wlyyDoorServiceApplicationDo1, p);
        return wlyyDoorServiceApplicationDo1;
    }
    /**
     * 根据居民获取签约机构的调度员
     * @param patient 当前资质申请居民  roleCode=dispatcher为调度员的角色
     * @return
     */
    public List<Map<String,Object>> findDispatcherByPatient(String patient)throws Exception{
        String sql="SELECT d.code,d.name FROM " +
                " manage_role_user ru LEFT JOIN " +
                " manage_roles r  ON ru.role_id=r.id " +
                " LEFT JOIN (select d.code,d.name from wlyy.wlyy_doctor d LEFT JOIN wlyy.wlyy_sign_family a ON d.hospital=a.hospital  " +
                "                 where a.patient = '"+patient+"' and a.status > 0  " +
                "                 AND d.status=1 and d.del=1) d ON ru.user_code=d.code " +
                " WHERE r.code='dispatcher' AND d.`code` IS NOT NULL";
        List<Map<String,Object>> mapList=jdbcTemplate.queryForList(sql);
        return  mapList;
    }
    /**
     * 将申请信息中的资质信息保存
     * @param wlyyDoorServiceApplicationDo 资质信息
     * @param p 居民信息
     * @return
     */
    public WlyyDoorServiceApplicationDo updateDtoAndSaveVoucher(WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo,BasePatientDO p)throws Exception{
        List<WlyyDoorServiceVoucherDo> wlyyDoorServiceVoucherDos =new ArrayList<>();
        if(null!= wlyyDoorServiceApplicationDo){
            if(StringUtils.isNotBlank(wlyyDoorServiceApplicationDo.getPatientAddr())){
                p.setAddress(wlyyDoorServiceApplicationDo.getPatientAddr());
                patientDao.save(p);
            }
            //将旧的人群类型失效
            if(null!=wlyyDoorServiceApplicationDo.getId()){
                doorServiceVoucherDao.deleteByPatientCode(wlyyDoorServiceApplicationDo.getId());
            }
            //保存新的凭证
            for (WlyyDoorServiceVoucherDo vo: wlyyDoorServiceApplicationDo.getWlyyDoorServiceVoucherDos()){
                vo.setStatus(1);
                vo.setServiceId(wlyyDoorServiceApplicationDo.getId());
                vo.setPatientCode(wlyyDoorServiceApplicationDo.getPatient());
                vo.setPatientName(wlyyDoorServiceApplicationDo.getPatientName());
                vo= doorServiceVoucherDao.save(vo);
                wlyyDoorServiceVoucherDos.add(vo);
            }
            wlyyDoorServiceApplicationDo.setWlyyDoorServiceVoucherDos(wlyyDoorServiceVoucherDos);
        }
        return wlyyDoorServiceApplicationDo;
    }
    /**
     * 开通上门服务资质评审
     * @param jsonData 资质相关信息
     * @param patient 居民
     * @return
     * @throws Exception
     */
    public WlyyDoorServiceApplicationDo update(String jsonData, String patient)throws Exception{
        ObjectMapper objectMapper=new ObjectMapper();
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo =objectMapper.readValue(jsonData,WlyyDoorServiceApplicationDo.class);
        if(null== wlyyDoorServiceApplicationDo.getId()){
            throw new Exception("资质申请id不能为空!");
        }
        BasePatientDO p = patientDao.findById(patient);
        wlyyDoorServiceApplicationDo.setProxyPatient(patient);
        wlyyDoorServiceApplicationDo.setProxyPatientName(p.getName());
        //默认先给调度员评审
        wlyyDoorServiceApplicationDo.setAuditorType(1);
        wlyyDoorServiceApplicationDo.setStatus(0);
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo1 = doorServiceApplicationDao.save(wlyyDoorServiceApplicationDo);
        wlyyDoorServiceApplicationDo1.setWlyyDoorServiceVoucherDos(wlyyDoorServiceApplicationDo.getWlyyDoorServiceVoucherDos());
        wlyyDoorServiceApplicationDo1 = updateDtoAndSaveVoucher(wlyyDoorServiceApplicationDo1, p);
        return wlyyDoorServiceApplicationDo1;
    }
    //-------------------------------------------------------------------医生端--------------------------------------------------------------------------------
    /**
     * 按照医生类型及查询条件获取资质审核信息
     * @param doctorCode
     * @param auditorType 医生角色:1调度员、2家医
     * @param patientName 居民姓名
     * @param mobile 居民电话
     * @param crowdType 人群类型:1失能老人,2半失能老人,3残疾人,4计生特殊家庭,5其他
     * @param status 资质状态:为空默认查找审核过的申请,0审核中,1未通过,2审核通过,3已过期
     * @param page
     * @param pageSize
     * @return
     */
    public JSONObject getPOnsiteServiceByDoctor(String doctorCode, String auditorType, String patientName, String mobile, String crowdType, String status, Integer page, Integer pageSize) throws Exception{
        JSONObject jsonObject = new JSONObject();
        if (page == null) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 15;
        }
        StringBuilder filters = new StringBuilder();
        StringBuilder crowdTypeStr = new StringBuilder();
        //根据医生角色获取可查看居民范围
        StringBuilder doctorShowStr = new StringBuilder();
        //居民姓名
        if (StringUtils.isNotBlank(patientName)) {
            filters.append(" AND temp2.patient_name LIKE '%" + patientName + "%' ");
        }
        //居民电话
        if (StringUtils.isNotBlank(mobile)) {
            filters.append(" AND temp2.patient_phone LIKE '%" + mobile + "%' ");
        }
        //审核人类型
        if (StringUtils.isNotBlank(auditorType)) {
//            filters.append(" AND temp2.auditor_type ='" + auditorType + "' ");
            if("1".equals(auditorType)){
                //1调度员:可查看调度员所在机构的居民
                doctorShowStr.append(" and sf.hospital=(SELECT d.hospital from wlyy_doctor d WHERE d.code='"+doctorCode+"' and d.status=1 AND d.del=1) ");
            }else if("2".equals(auditorType)){
                //2家医:可查看已签约居民
                doctorShowStr.append(" and (sf.doctor='"+doctorCode+"' or sf.doctor_health='"+doctorCode+"' )");
            }else {
                //不为调度员,不为家医,不可看
                doctorShowStr.append(" and sf.patient='"+doctorCode+"'  ");
            }
        }
        //审核状态
        if (StringUtils.isNotBlank(status)) {
            filters.append(" AND temp2.status='" + status + "' ");
        } else {
            filters.append(" AND temp2.status>0");
        }
        //人群类型
        if (StringUtils.isNotBlank(crowdType)) {
            crowdTypeStr.append(" AND type='" + crowdType + "' ");
        }
        StringBuilder sql=new StringBuilder();
        StringBuilder sqlCenter=new StringBuilder();
        sql.append(" SELECT temp2.*,GROUP_CONCAT(osv.type) as type,GROUP_CONCAT(osv.type_value) as type_value,GROUP_CONCAT(osv.image) as image,COUNT(1) as ImageCount FROM ");
        //查询居民申请+人群分类+统计人群分类凭证
        sqlCenter.append(" ( SELECT temp1.*,sf.hospital_name  FROM  " +
                //根据人群类型,获取居民申请
                " (SELECT wos.id,wos.patient,wos.patient_name,wos.patient_idcard,wos.patient_phone,wos.patient_addr,wos.application_describe,wos.start_time,wos.end_time,wos.status,wos.create_time,wos.auditor_type " +
                " FROM  (SELECT DISTINCT(patient_code) code,service_id FROM wlyy_door_service_voucher  WHERE status=1"+crowdTypeStr.toString()+") pc LEFT JOIN wlyy_door_service_application wos  ON wos.patient=pc.code AND wos.id=pc.service_id ) temp1 " +
                //根据当前医生所在医院再次筛选申请(属于他们机构可看的申请)
                " LEFT JOIN wlyy_sign_family sf ON temp1.patient=sf.patient AND sf.status>0 " +
                " WHERE 1=1"+doctorShowStr.toString()+" ) temp2 " +
                " LEFT JOIN wlyy_door_service_voucher osv ON temp2.id=osv.service_id  AND osv.status=1 " +
                " WHERE 1=1 " +filters.toString() +
                "  GROUP BY temp2.id ORDER BY temp2.create_time desc, osv.sort ASC ");
        String countSql = "SELECT COUNT(1)  FROM " +
                " ( SELECT  temp1.*, sf.hospital_name  FROM " +
                //根据人群类型筛选申请
                " (  SELECT wos.id, wos.patient, wos.patient_name, wos.patient_phone, wos.STATUS, wos.create_time, wos.auditor_type " +
                " FROM " +
                " ( SELECT DISTINCT (patient_code) CODE, service_id FROM  wlyy_door_service_voucher WHERE STATUS = 1 "+crowdTypeStr.toString()+ ") pc LEFT JOIN wlyy_door_service_application wos ON wos.patient = pc. CODE AND wos.id = pc.service_id ) temp1 " +
               //根据当前登录人筛选居民
                " LEFT JOIN wlyy_sign_family sf ON temp1.patient = sf.patient  AND sf.status > 0 " +
                " WHERE 1=1" +doctorShowStr.toString()+") temp2 " +
                " WHERE 1 = 1 " +filters.toString() ;
        Long count = jdbcTemplate.queryForObject(countSql, Long.class);
        List<Map<String,Object>> mapList=jdbcTemplate.queryForList(sql.toString()+sqlCenter.toString()+" limit " + (page - 1) * pageSize + "," + pageSize);
        for(Map<String,Object> m:mapList){
            m.put("age",IdCardUtil.getAgeForIdcard(m.get("patient_idcard")+""));
            m.put("sex",IdCardUtil.getSexForIdcard_new(m.get("patient_idcard")+""));
            //图片使用逗号隔开,用逗号分离计算图片数量
            if(m.get("image")!=null){
                String arry[]= m.get("image").toString().split(",");
                m.put("ImageCount",null==arry?0:arry.length);
            }else{
                m.put("ImageCount",0);
            }
        }
        jsonObject.put("list",mapList);
        jsonObject.put("count",count);
        return jsonObject;
    }
    /**
     * 调度或审核
     * @param id 申请id
     * @param doctorCode 当前医生
     * @param status 审核状态:1未通过,2审核通过
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param operationType 操作类型:1审核,2调度
     * @param failureReasons 拒绝的原因
     * @return
     */
    public WlyyDoorServiceApplicationDo auditing(Long id,String doctorCode,String status,String startDate,String endDate, String operationType, String failureReasons)throws Exception{
        BaseDoctorDO doctor = doctorInfoService.findById(doctorCode);
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo=doorServiceApplicationDao.findOne(id);
        String scene="zzbtg";
        if("2".equals(operationType)){
            //转给家医审核:1调度员、2家医
            wlyyDoorServiceApplicationDo.setAuditorType(2);
            wlyyDoorServiceApplicationDo.setUpdateUser(doctor.getId());
            wlyyDoorServiceApplicationDo.setUpdateUserName(doctor.getName());
            //将所有调度员的消息处理为结束
/*            List<Message> messages=messageDao.findMessageByRelationCode(String.valueOf(id));
            messages.forEach(item->{
                item.setOver("0");
            });
            messageDao.save(messages);
            //在转给家医的时候需要给家医发消息
            List<SignFamily> signFamilies= signFamilyDao.getSignFamilyByPatient(wlyyDoorServiceApplicationDo.getPatient());
            if(null!=signFamilies&&signFamilies.size()>0){
                SignFamily signFamily=signFamilies.get(0);
                Message message=new Message();
                message.setCzrq(new Date());
                message.setCreateTime(new Date());
                message.setRead(1);
                message.setState(1);
                message.setRelationCode(wlyyDoorServiceApplicationDo.getId().toString());
                message.setOver("1");
                //家医
                message.setReceiver(signFamily.getDoctor());
                //调度员
                message.setSender(doctor.getCode());
                message.setCode(getCode());
                message.setTitle("居民资质审核");
                message.setContent(signFamily.getName()+"提交了资质申请,请及时处理");
                //消息类型:408为资质申请审核-家医
                message.setType(408);
                message.setDel("1");
                messageDao.save(message);
                //调度员转接给家庭医生审核
                doorServiceOrderService.sendWeixinMessage(2,signFamily.getDoctor(),wlyyDoorServiceApplicationDo.getPatient());
            }*/
        }else {
            //处理消息
/*            List<Message> messages=messageDao.findMessageByRelationCode(String.valueOf(id));
            messages.forEach(item->{
                item.setOver("0");
            });
            messageDao.save(messages);*/
            wlyyDoorServiceApplicationDo.setStatus(Integer.valueOf(status));
            //审核状态:1未通过,2审核通过
            if("2".equals(status)){
                scene="zztg";
                Date start= DateUtil.strToDate(startDate + "", "yyyy-MM-dd HH:mm:ss");
                if(null==start){
                    throw new Exception("有效起始日期格式不正确");
                }
                Date end=DateUtil.strToDate(endDate + "", "yyyy-MM-dd HH:mm:ss");
                if(null==end){
                    throw new Exception("有效截止日期格式不正确");
                }
                wlyyDoorServiceApplicationDo.setStartTime(start);
                wlyyDoorServiceApplicationDo.setEndTime(end);
            }else {
                if(StringUtils.isNotBlank(failureReasons)&&failureReasons.length()>150){
                    throw new Exception("审核不通过原因不能超过150字!");
                }else if(StringUtils.isBlank(failureReasons)){
                    throw new Exception("审核不通过原因不能为空!");
                }
            }
            wlyyDoorServiceApplicationDo.setFailureReasons(failureReasons);
            wlyyDoorServiceApplicationDo.setAuditTime(new Date());
            wlyyDoorServiceApplicationDo.setAuditorCode(doctor.getId());
            wlyyDoorServiceApplicationDo.setAuditorName(doctor.getName());
        }
        WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo1=doorServiceApplicationDao.save(wlyyDoorServiceApplicationDo);
        if(null!=wlyyDoorServiceApplicationDo1){
            //给代理申请资质的居民发送微信模板消息-审核结果
/*            Patient patient = patientDao.findByCode(wlyyDoorServiceApplicationDo1.getProxyPatient());
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_audit",scene);
            if(null==templateConfig){
                throw new Exception("微信模板不存在!请确认");
            }
            String first = templateConfig.getFirst();
            first = first.replace("key1",(patient.getName()==null?"":patient.getName()));
            first = first.replace("key2", (wlyyDoorServiceApplicationDo1.getPatientName() == null ? "" : wlyyDoorServiceApplicationDo1.getPatientName()));
            String remark = templateConfig.getRemark();
            String keyword1 = templateConfig.getKeyword1();
            JSONObject sendJson = new JSONObject();
            sendJson.put("keyword1", keyword1);
            sendJson.put("keyword2", wlyyDoorServiceApplicationDo1.getAuditorName());
            sendJson.put("first", first);
            sendJson.put("remark", remark);
            //带参数的模板跳转链接
            sendJson.put("url", templateConfig.getUrl());
            pushMsgTask.sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 19, patient.getOpenid(), wlyyDoorServiceApplicationDo1.getProxyPatientName(), sendJson);*/
        }
        return wlyyDoorServiceApplicationDo1;
    }
    /**
     * 获取资质审核状态
     * @param patient
     */
    public Map<String,Object> getDoorSericeApplicationStatus(String patient){
        String sql = "SELECT p.`name`,p.code,p.address,p.mobile,h.town_name townName, " +
                "(SELECT COUNT(*) from wlyy_door_service_application a WHERE a.patient = '"+patient+"' and a.`status` = 2 and " +
                "NOW()>=a.start_time and NOW()<a.end_time ) status " +
                " from wlyy_patient p,wlyy_sign_family s,dm_hospital h " +
                "WHERE p.`code` = s.patient and s.`status`>=0 and s.hospital = h.`code` " +
                "and s.patient = '"+patient+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }
    /**
     *根据资质申请id获取详情
     * @param id 资质申请id
     * @return
     */
    public JSONObject getPOnsiteServiceById( Long id) throws Exception{
        JSONObject jsonObject = new JSONObject();
        StringBuilder sql=new StringBuilder();
        sql.append(" SELECT temp2.*, GROUP_CONCAT(osv.type) AS type, GROUP_CONCAT(osv.type_value) AS type_value, GROUP_CONCAT(osv.image) AS image, COUNT(1) AS ImageCount " +
                " FROM ( SELECT wos.id, wos.patient, wos.patient_name, wos.patient_idcard, wos.patient_phone, wos.patient_addr," +
                " wos.application_describe, wos.start_time,wos.end_time, wos.status, wos.create_time, wos.failure_reasons, wos.auditor_type, sf.hospital_name FROM wlyy_door_service_application wos " +
                " LEFT JOIN wlyy_sign_family sf ON wos.patient = sf.patient AND sf. STATUS > 0 WHERE wos.id='"+id+"' " +
                " ) temp2  LEFT JOIN wlyy_door_service_voucher osv ON temp2.id = osv.service_id AND osv. STATUS = 1 ");
        List<Map<String,Object>> mapList=jdbcTemplate.queryForList(sql.toString());
        for(Map<String,Object> m:mapList){
            m.put("age",IdCardUtil.getAgeForIdcard(m.get("patient_idcard")+""));
            m.put("sex",IdCardUtil.getSexForIdcard_new(m.get("patient_idcard")+""));
            m.put("application_describe",null==m.get("application_describe")?"":m.get("application_describe").toString());
            m.put("patient_addr",null==m.get("patient_addr")?"":m.get("patient_addr").toString());
            m.put("patient_phone",null==m.get("patient_phone")?"":m.get("patient_phone").toString());
            m.put("failure_reasons",null==m.get("failure_reasons")?"":m.get("failure_reasons").toString());
            //图片使用逗号隔开,用逗号分离计算图片数量
            if(m.get("image")!=null){
                String arry[]= m.get("image").toString().split(",");
                m.put("ImageCount",null==arry?0:arry.length);
            }else{
                m.put("ImageCount",0);
            }
            BasePatientDO patient= patientDao.findById(m.get("patient").toString());
            m.put("photo",null==patient?"":patient.getPhoto());
        }
        jsonObject.put("list",mapList);
        return jsonObject;
    }
}

+ 14 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/DoorServiceVoucherService.java

@ -0,0 +1,14 @@
package com.yihu.jw.door.service;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
/**
 * Created by zdm on 2019/3/13.
 * 上门服务凭证
 */
@Service
@Transactional
public class DoorServiceVoucherService{
}

+ 163 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCancelLogService.java

@ -0,0 +1,163 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorCancelLogDao;
import com.yihu.jw.entity.door.WlyyDoorCancelLogDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 工单取消记录服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月26日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorCancelLogService extends BaseJpaService<WlyyDoorCancelLogDO, WlyyDoorCancelLogDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorCancelLogService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //工单取消记录服务基本信息
    private WlyyDoorCancelLogDO jsonToWlyyDoorCancelLog(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
        WlyyDoorCancelLogDO wlyyDoorCancelLog;
        try {
            wlyyDoorCancelLog = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorCancelLog").toString(),WlyyDoorCancelLogDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "工单取消记录服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorCancelLogDO();
        }
        this.save(wlyyDoorCancelLog);
        return wlyyDoorCancelLog;
    }
     /**
     * 创建工单取消记录
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCancelLogDO wlyyDoorCancelLog = new WlyyDoorCancelLogDO();
        wlyyDoorCancelLog = jsonToWlyyDoorCancelLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorCancelLog);
        return result;
    }
    /**
     * 工单取消记录(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCancelLogDO wlyyDoorCancelLog = new WlyyDoorCancelLogDO();
        wlyyDoorCancelLog = jsonToWlyyDoorCancelLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorCancelLog);
        return result;
    }
   /**
     * 查询工单取消记录列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorCancelLogDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorCancelLogDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库工单取消记录列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计工单取消记录数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 163 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCommentDoctorService.java

@ -0,0 +1,163 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorCommentDoctorDao;
import com.yihu.jw.entity.door.WlyyDoorCommentDoctorDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 服务工单中的医生评价服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorCommentDoctorService extends BaseJpaService<WlyyDoorCommentDoctorDO, WlyyDoorCommentDoctorDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorCommentDoctorService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //服务工单中的医生评价服务基本信息
    private WlyyDoorCommentDoctorDO jsonToWlyyDoorCommentDoctor(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorCommentDoctorDO wlyyDoorCommentDoctor;
        try {
            wlyyDoorCommentDoctor = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorCommentDoctor").toString(),WlyyDoorCommentDoctorDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "服务工单中的医生评价服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorCommentDoctorDO();
        }
        this.save(wlyyDoorCommentDoctor);
        return wlyyDoorCommentDoctor;
    }
     /**
     * 创建服务工单中的医生评价
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCommentDoctorDO wlyyDoorCommentDoctor = new WlyyDoorCommentDoctorDO();
        wlyyDoorCommentDoctor = jsonToWlyyDoorCommentDoctor(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorCommentDoctor);
        return result;
    }
    /**
     * 服务工单中的医生评价(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCommentDoctorDO wlyyDoorCommentDoctor = new WlyyDoorCommentDoctorDO();
        wlyyDoorCommentDoctor = jsonToWlyyDoorCommentDoctor(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorCommentDoctor);
        return result;
    }
   /**
     * 查询服务工单中的医生评价列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorCommentDoctorDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorCommentDoctorDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库服务工单中的医生评价列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计服务工单中的医生评价数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 163 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorCommentService.java

@ -0,0 +1,163 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorCommentDao;
import com.yihu.jw.entity.door.WlyyDoorCommentDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 服务工单评价服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorCommentService extends BaseJpaService<WlyyDoorCommentDO, WlyyDoorCommentDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorCommentService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //服务工单评价服务基本信息
    private WlyyDoorCommentDO jsonToWlyyDoorComment(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorCommentDO wlyyDoorComment;
        try {
            wlyyDoorComment = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorComment").toString(),WlyyDoorCommentDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "服务工单评价服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorCommentDO();
        }
        this.save(wlyyDoorComment);
        return wlyyDoorComment;
    }
     /**
     * 创建服务工单评价
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCommentDO wlyyDoorComment = new WlyyDoorCommentDO();
        wlyyDoorComment = jsonToWlyyDoorComment(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorComment);
        return result;
    }
    /**
     * 服务工单评价(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorCommentDO wlyyDoorComment = new WlyyDoorCommentDO();
        wlyyDoorComment = jsonToWlyyDoorComment(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorComment);
        return result;
    }
   /**
     * 查询服务工单评价列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorCommentDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorCommentDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库服务工单评价列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计服务工单评价数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 163 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorConclusionService.java

@ -0,0 +1,163 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorConclusionDao;
import com.yihu.jw.entity.door.WlyyDoorConclusionDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 工单服务小结服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorConclusionService extends BaseJpaService<WlyyDoorConclusionDO, WlyyDoorConclusionDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorConclusionService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //工单服务小结服务基本信息
    private WlyyDoorConclusionDO jsonToWlyyDoorConclusion(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
        WlyyDoorConclusionDO wlyyDoorConclusion;
        try {
            wlyyDoorConclusion = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorConclusion").toString(),WlyyDoorConclusionDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "工单服务小结服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorConclusionDO();
        }
        this.save(wlyyDoorConclusion);
        return wlyyDoorConclusion;
    }
     /**
     * 创建工单服务小结
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorConclusionDO wlyyDoorConclusion = new WlyyDoorConclusionDO();
        wlyyDoorConclusion = jsonToWlyyDoorConclusion(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorConclusion);
        return result;
    }
    /**
     * 工单服务小结(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorConclusionDO wlyyDoorConclusion = new WlyyDoorConclusionDO();
        wlyyDoorConclusion = jsonToWlyyDoorConclusion(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorConclusion);
        return result;
    }
   /**
     * 查询工单服务小结列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorConclusionDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorConclusionDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库工单服务小结列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计工单服务小结数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 163 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorFeeDictService.java

@ -0,0 +1,163 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorDoctorFeeDictDao;
import com.yihu.jw.entity.door.WlyyDoorDoctorFeeDictDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 医生出诊费用字典服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorDoctorFeeDictService extends BaseJpaService<WlyyDoorDoctorFeeDictDO, WlyyDoorDoctorFeeDictDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorDoctorFeeDictService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //医生出诊费用字典服务基本信息
    private WlyyDoorDoctorFeeDictDO jsonToWlyyDoorDoctorFee(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorDoctorFeeDictDO wlyyDoorDoctorFee;
        try {
            wlyyDoorDoctorFee = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorDoctorFee").toString(), WlyyDoorDoctorFeeDictDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "医生出诊费用字典服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorDoctorFeeDictDO();
        }
        this.save(wlyyDoorDoctorFee);
        return wlyyDoorDoctorFee;
    }
     /**
     * 创建医生出诊费用字典
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorFeeDictDO wlyyDoorDoctorFee = new WlyyDoorDoctorFeeDictDO();
        wlyyDoorDoctorFee = jsonToWlyyDoorDoctorFee(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorDoctorFee);
        return result;
    }
    /**
     * 医生出诊费用字典(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorFeeDictDO wlyyDoorDoctorFee = new WlyyDoorDoctorFeeDictDO();
        wlyyDoorDoctorFee = jsonToWlyyDoorDoctorFee(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorDoctorFee);
        return result;
    }
   /**
     * 查询医生出诊费用字典列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorDoctorFeeDictDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorDoctorFeeDictDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库医生出诊费用字典列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计医生出诊费用字典数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 195 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorService.java

@ -0,0 +1,195 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorDoctorDao;
import com.yihu.jw.entity.door.WlyyDoorDoctorDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 服务工单关联的医护人员服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorDoctorService extends BaseJpaService<WlyyDoorDoctorDO, WlyyDoorDoctorDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorDoctorService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //服务工单关联的医护人员服务基本信息
    private WlyyDoorDoctorDO jsonToWlyyDoorDoctor(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
        WlyyDoorDoctorDO wlyyDoorDoctor;
        try {
            wlyyDoorDoctor = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorDoctor").toString(),WlyyDoorDoctorDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "服务工单关联的医护人员服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorDoctorDO();
        }
        this.save(wlyyDoorDoctor);
        return wlyyDoorDoctor;
    }
     /**
     * 创建服务工单关联的医护人员
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorDO wlyyDoorDoctor = new WlyyDoorDoctorDO();
        wlyyDoorDoctor = jsonToWlyyDoorDoctor(result, jsonObjectParam,jsonData);
         /*
        //新增#######关联关系
        if (roleWithMenu(result, jsonObjectParam, wlyyDoorDoctor)) return result;
        //新增#######关联关系
        if (roleWithFunction(result, jsonObjectParam, wlyyDoorDoctor)) return result;
        */
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorDoctor);
        return result;
    }
    /**
     * 服务工单关联的医护人员(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorDO wlyyDoorDoctor = new WlyyDoorDoctorDO();
        wlyyDoorDoctor = jsonToWlyyDoorDoctor(result, jsonObjectParam,jsonData);
        /*
        //修改时有更改到关联关系,则先删除原有关联关系,再新增关联关系
        //删除#######关联关系
        List relatedList1 = new ArrayList();
        roleMenuList = baseRoleMenuService.findByField("roleId",wlyyDoorDoctor.getId());
        Set roleMenuIdSet = new HashSet();
        if(!CollectionUtils.isEmpty(roleMenuList)){
            roleMenuList.forEach(one ->{roleMenuIdSet.add(one);});
        }
        baseRoleMenuService.delete(roleMenuIdSet);
        //新增#######关联关系
        if (roleWithMenu(result, jsonObjectParam, wlyyDoorDoctor)) return result;
        //删除#######关联关系
        List relatedList2 = new ArrayList();
        roleFunctionList = baseRoleMenuFunctionService.findByField("roleId",wlyyDoorDoctor.getId());
        Set roleFunctionIdSet = new HashSet();
        if(!CollectionUtils.isEmpty(roleFunctionList)){
            roleFunctionList.forEach(one ->{roleFunctionIdSet.add(one);});
        }
        baseRoleMenuFunctionService.delete(roleFunctionIdSet);
        //新增#######关联关系
        if (roleWithFunction(result, jsonObjectParam, wlyyDoorDoctor)) return result;
        */
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorDoctor);
        return result;
    }
   /**
     * 查询服务工单关联的医护人员列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorDoctorDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorDoctorDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库服务工单关联的医护人员列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计服务工单关联的医护人员数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 24 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorDoctorStatusService.java

@ -0,0 +1,24 @@
package com.yihu.jw.door.service;
import com.yihu.jw.door.dao.WlyyDoorDoctorStatusDao;
import com.yihu.jw.entity.door.WlyyDoorDoctorStatusDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.stereotype.Service;
/**
 * 
 * 医生上门服务工单状态情况service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorDoctorStatusService extends BaseJpaService<WlyyDoorDoctorStatusDO, WlyyDoorDoctorStatusDao> {
}

+ 184 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorFeeDetailService.java

@ -0,0 +1,184 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorFeeDetailDao;
import com.yihu.jw.entity.door.WlyyDoorFeeDetailDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 服务工单价格明细(服务项价格,医生出诊费用)服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorFeeDetailService extends BaseJpaService<WlyyDoorFeeDetailDO, WlyyDoorFeeDetailDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorFeeDetailService.class);
    @Autowired
    private WlyyDoorFeeDetailDao wlyyDoorFeeDetailDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
      /**
     * 判断某个服务项数量是否大于2
     * @param id
     * @return
     */
    public boolean numberGrateThan2(String id){
        if(StringUtils.isEmpty(id)){
            return false;
        }
        WlyyDoorFeeDetailDO feeDetailDO = wlyyDoorFeeDetailDao.findOne(id);
        if(null == feeDetailDO){
            return false;
        }
        return feeDetailDO.getNumber() > 1 ? true : false;
    }
    //服务工单价格明细(服务项价格,医生出诊费用)服务基本信息
    private WlyyDoorFeeDetailDO jsonToWlyyDoorFeeDetail(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorFeeDetailDO wlyyDoorFeeDetail;
        try {
            wlyyDoorFeeDetail = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorFeeDetail").toString(),WlyyDoorFeeDetailDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "服务工单价格明细(服务项价格,医生出诊费用)服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorFeeDetailDO();
        }
        this.save(wlyyDoorFeeDetail);
        return wlyyDoorFeeDetail;
    }
     /**
     * 创建服务工单价格明细(服务项价格,医生出诊费用)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorFeeDetailDO wlyyDoorFeeDetail = new WlyyDoorFeeDetailDO();
        wlyyDoorFeeDetail = jsonToWlyyDoorFeeDetail(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorFeeDetail);
        return result;
    }
    /**
     * 服务工单价格明细(服务项价格,医生出诊费用)(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorFeeDetailDO wlyyDoorFeeDetail = new WlyyDoorFeeDetailDO();
        wlyyDoorFeeDetail = jsonToWlyyDoorFeeDetail(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorFeeDetail);
        return result;
    }
   /**
     * 查询服务工单价格明细(服务项价格,医生出诊费用)列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorFeeDetailDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorFeeDetailDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库服务工单价格明细(服务项价格,医生出诊费用)列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计服务工单价格明细(服务项价格,医生出诊费用)数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 161 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorPatientConfirmLogService.java

@ -0,0 +1,161 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorPatientConfirmLogDao;
import com.yihu.jw.entity.door.WlyyDoorPatientConfirmLogDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 服务工单居民确认操作日志记录服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorPatientConfirmLogService extends BaseJpaService<WlyyDoorPatientConfirmLogDO, WlyyDoorPatientConfirmLogDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorPatientConfirmLogService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //服务工单居民确认操作日志记录服务基本信息
    private WlyyDoorPatientConfirmLogDO jsonToWlyyDoorPatientConfirmLog(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
        WlyyDoorPatientConfirmLogDO wlyyDoorPatientConfirmLog;
        try {
            wlyyDoorPatientConfirmLog = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorPatientConfirmLog").toString(),WlyyDoorPatientConfirmLogDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "服务工单居民确认操作日志记录服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorPatientConfirmLogDO();
        }
        this.save(wlyyDoorPatientConfirmLog);
        return wlyyDoorPatientConfirmLog;
    }
     /**
     * 创建服务工单居民确认操作日志记录
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorPatientConfirmLogDO wlyyDoorPatientConfirmLog = new WlyyDoorPatientConfirmLogDO();
        wlyyDoorPatientConfirmLog = jsonToWlyyDoorPatientConfirmLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorPatientConfirmLog);
        return result;
    }
    /**
     * 服务工单居民确认操作日志记录(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorPatientConfirmLogDO wlyyDoorPatientConfirmLog = new WlyyDoorPatientConfirmLogDO();
        wlyyDoorPatientConfirmLog = jsonToWlyyDoorPatientConfirmLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorPatientConfirmLog);
        return result;
    }
   /**
     * 查询服务工单居民确认操作日志记录列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorPatientConfirmLogDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorPatientConfirmLogDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库服务工单居民确认操作日志记录列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计服务工单居民确认操作日志记录数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 631 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorPrescriptionService.java

@ -0,0 +1,631 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.door.dao.DoorServiceOrderDao;
import com.yihu.jw.door.dao.WlyyDoorPrescriptionDao;
import com.yihu.jw.door.dao.WlyyDoorPrescriptionDetailDao;
import com.yihu.jw.door.dao.WlyyDoorPrescriptionDrugDao;
import com.yihu.jw.door.service.prescription.JwDoorPrescriptionService;
import com.yihu.jw.door.service.prescription.PresModeAdapter;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDO;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDrugDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.*;
/**
 * 上门服务开方相关业务
 * create by hmf on 2019/7/25
 */
@Service
public class WlyyDoorPrescriptionService  extends BaseJpaService<WlyyDoorPrescriptionDO, WlyyDoorPrescriptionDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorPrescriptionService.class);
    @Autowired
    private WlyyDoorPrescriptionDao doorPrescriptionDao;
    @Autowired
    private WlyyDoorPrescriptionDetailDao doorPrescriptionDetailDao;
    @Autowired
    private DoorServiceOrderDao doorServiceOrderDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    ObjectMapper objectMapper;
/*    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PushMsgTask pushMsgTask;
        @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;*/
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private WlyyDoorPrescriptionDrugDao doorPrescriptionDrugDao;
    @Autowired
    private JwDoorPrescriptionService jwDoorPrescriptionService;
    @Autowired
    private PresModeAdapter presModeAdapter;
/*    @Autowired
    private ZyDictService zyDictService;
    @Autowired
    private ZyIvDeptDictDao zyIvDeptDictDao;*/
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${server.server_url}")
    private String server_url;
    /**
     * 造长处方开方数据
     *
     * @param doctor
     * @param patient
     * @param visitDept
     * @param visitTimeFrom
     * @param visitTimeEnd
     * @return
     */
    public JSONArray getPrescription(String doctor, String patient, String visitDept, String visitTimeFrom, String visitTimeEnd) throws Exception {
        JSONArray array = new JSONArray();
        if (StringUtils.isEmpty(visitTimeFrom)) {
            visitTimeEnd = DateUtil.getStringDateShort();
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, -2);
            c.add(Calendar.DATE, 1);
            visitTimeFrom = DateUtil.dateToStrShort(c.getTime());
        }
        String re = jwDoorPrescriptionService.getVisitRecordListUnion(doctor, patient, visitDept, visitTimeFrom, visitTimeEnd);
        array = JSONObject.parseObject(re).getJSONArray("returnData");
        if(array.size() > 0) {
            array.getJSONArray(0).sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("VISIT_NO")).reversed());
        }
//        String jsonString = "[]";
        /*String jsonString = "[{\"RECIPE_NO\": \"123456\",\"DIAGNOSE_NAME\": \"高血压\",\"DIAGNOSE_CODE\":\"1\",\"TOTAL_FEE\":\"125\",\"APPLY_TIME\": \"2019-04-24 09:15:00\", \"RECIPE_DETAIL\":[{\"ITEM_CODE\": \"12\",\"ITEM_NAME\": \"尿液分析\",\"ITEM_PRICE\": \"25.00\",\"ITEM_QUANTITY\": \"1\",\"COST\": \"25\"}," +
                "{\"ITEM_CODE\": \"13\",\"ITEM_NAME\": \"出诊费\",\"ITEM_PRICE\": \"50\",\"ITEM_QUANTITY\": \"2\",\"COST\": \"100\"}]},{\"RECIPE_NO\": \"23333\",\"DIAGNOSE_NAME\": \"高血压,糖尿病\",\"DIAGNOSE_CODE\":\"2\",\"TOTAL_FEE\":\"125\",\"APPLY_TIME\": \"2019-04-23 09:15:00\", " +
                "\"RECIPE_DETAIL\":[{\"ITEM_CODE\": \"21\",\"ITEM_NAME\": \"饮血试验\",\"ITEM_PRICE\": \"25.00\",\"ITEM_QUANTITY\": \"1\",\"COST\": \"25.00\"}," +
                "{\"ITEM_CODE\": \"22\",\"ITEM_NAME\": \"出诊费\",\"ITEM_PRICE\": \"50.00\",\"ITEM_QUANTITY\": \"2\",\"COST\": \"100.00\"}]}]";*/
//        JSONArray array = JSONArray.parseArray(jsonString);
        return array;
    }
    /**
     * 保存上门服务开方记录
     *
     * @param orderId
     * @param jsonData
     * @param doctor
     */
    public JSONObject createDoorPrescription(String orderId, String jsonData, String doctor) throws Exception {
        JSONObject re = new JSONObject();
        List<WlyyDoorPrescriptionDO> prescriptionDOList = new ArrayList<>();
        WlyyDoorPrescriptionDO prescriptionDO = new WlyyDoorPrescriptionDO();
        WlyyDoorServiceOrderDO orderDO = doorServiceOrderDao.findOne(orderId);
        BaseDoctorDO d = doctorDao.findById(doctor);
        //判断是上门前开方,或者是上门后开方
        if(orderDO.getStatus() < WlyyDoorServiceOrderDO.Status.waitForServe.getType()){
            JSONObject jsonObject = saveDoorPrescriptionBefore(jsonData, d, orderDO.getPatient(), orderId);
            if(jsonObject.getInteger("status") == 200) {
                prescriptionDOList = (List<WlyyDoorPrescriptionDO>) jsonObject.get("data");
                orderDO.setPrescriptionStatus(1);
                //更新工单信息
                orderDO.setPrescriptionTime(new Date());
                orderDO.setStatus(4);
                doorServiceOrderDao.save(orderDO);
                //发送 预约卡片信息(2101类型)
                JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
                orderInfoContent.put("re_msg_type", 2);//开方完成消息
                this.qucikSendIM(orderDO.getId(), orderDO.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
            }else {
                re.put("status", -1);
                re.put("msg", jsonObject.getString("msg"));
                return re;
            }
        }else {
            JSONObject object = saveDoorPrescriptionAfter(jsonData, d, orderDO.getPatient(), orderId);
            if(object.getInteger("status") == 200){
                prescriptionDO = (WlyyDoorPrescriptionDO) object.get("data");
                prescriptionDOList.add(prescriptionDO);
            }else {
                re.put("status", -1);
                re.put("msg", object.getString("msg"));
                return re;
            }
        }
        re.put("status", 200);
        re.put("data", prescriptionDOList);
        return re;
    }
    private String getRandomIntStr() {
        Random rand = new Random();
        int i = rand.nextInt(); //int范围类的随机数
        i = rand.nextInt(100); //生成0-100以内的随机数
        i = (int) (Math.random() * 100000000); //0-100以内的随机数,用Matn.random()方式
        return String.valueOf(i);
    }
    /**
     * 查询预约简要卡片信息
     * <p>
     * 服务时间:2019-01-01   12:30
     * 服务对象:张三
     * 联系电话:13125256565(儿子)
     * 上门地址:福建省厦门市思明区望海路55号
     *
     * @param orderDO
     * @return
     */
    public JSONObject queryOrderCardInfo(WlyyDoorServiceOrderDO orderDO) {
        JSONObject result = new JSONObject();
        BasePatientDO patientDO = patientDao.findById(orderDO.getPatient());
        result.put("title", "预约服务信息如下:");
        result.put("orderId", orderDO.getId());
        result.put("status", orderDO.getStatus());
        result.put("number", orderDO.getNumber());
        result.put("serveDesc", orderDO.getServeDesc());
        result.put("expectedDoctor", orderDO.getExpectedDoctorName());
        if (StringUtils.isNotBlank(orderDO.getDoctorArrivingTime())) {
            result.put("time", orderDO.getDoctorArrivingTime());
        } else {
            result.put("time", "工作时间");
        }
        result.put("patientName", patientDO.getName());
        result.put("patientSex", IdCardUtil.getSexNameForIdcard_new(patientDO.getIdcard()));
        result.put("patientAge", IdCardUtil.getAgeForIdcard(patientDO.getIdcard()));
        result.put("phone", orderDO.getPatientPhone());
        if (StringUtils.equalsIgnoreCase(orderDO.getPatient(), orderDO.getProxyPatient())) {
            result.put("relation", "");
        } else {
            result.put("relation", orderDO.getPatientRelation());
        }
        result.put("serveTown", orderDO.getServeTown());
        result.put("serveAddress", orderDO.getServeAddress());
        result.put("type", 11);
        return result;
    }
    /**
     * 【调度员,医生】快速发送IM消息
     *
     * @param orderId
     * @param sendId
     * @param sendName
     * @param content
     * @return
     */
    public int qucikSendIM(String orderId, String sendId, String sendName, String contentType, String content) {
        int result = -1;
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        if (null == consult) {
            logger.error("当前工单未关联咨询,工单id:" + orderId);
            return result;
        }
        String response = imUtill.sendTopicIM(sendId, sendName, consult.getId(), contentType, content, null);
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getIntValue("status") == -1) {
            logger.error("上门服务工单消息发送失败:" + resObj.getString("message"));
            return result;
        }
        result = 1;
        return result;
    }
    /**
     * 保存授权图片并发送模板消息
     *
     * @param orderId
     * @param authorizeImage
     */
    public void saveAuthorizeImage(String orderId, String authorizeImage) {
        WlyyDoorServiceOrderDO orderDO = doorServiceOrderDao.findOne(orderId);
//        orderDO.setAuthorizeImage(authorizeImage);
        orderDO.setAuthorizeImage(server_url+"/images/healthCardQRcode.png");
        doorServiceOrderDao.save(orderDO);
/*        Patient patient = patientDao.findByCode(orderDO.getPatient());
        //发送微信模板消息
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "authorize");
        String first = templateConfig.getFirst();
        first = first.replace("key1", orderDO.getPatientName());
        String keyword2 = templateConfig.getKeyword2();
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", first);
        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
        json.put("keyword2", keyword2);
        json.put("url", templateConfig.getUrl());
        json.put("remark", templateConfig.getRemark());
        json.put("orderId", orderDO.getId());
        json.put("authorizeImage", orderDO.getAuthorizeImage());
        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 34, patient.getOpenid(), orderDO.getPatientName(), json);*/
    }
    /**
     * 根据处方表code查处方信息
     *
     * @param recipeNo
     * @return
     * @throws Exception
     */
    public JSONObject getPrescriptionByCode(String recipeNo, String patientCode) throws Exception {
        JSONObject json = new JSONObject();
        //获取智业处方详细
        String response = "";
                //获取居民签约信息
//        SignFamily signFamily = signFamilyDao.findSignFamilyByPatient(patientCode);
        WlyyDoorPrescriptionDO prescriptionDO = doorPrescriptionDao.findByRecipeNo(recipeNo);
        //说明是非手动开方,手动开方库里只有处方号
        if (prescriptionDO != null) {
            json.put("prescription", prescriptionDO);
//            response = jwDoorPrescriptionService.getVisitRecipeDetailUnion(prescriptionDO.getVisitNo(), recipeNo, signFamily.getHospital());
//            throw new Exception("该处方不存在!");
        }else {
//            response = jwDoorPrescriptionService.getVisitRecipeDetailUnion(null, recipeNo, signFamily.getHospital());
        }
        JSONObject jsonObject = presModeAdapter.modelToSinglePrescription(response);
        json.put("prescriptionDrugList", jsonObject);
        BasePatientDO patient = patientDao.findById(patientCode);
        if (patient != null) {
            //居民基本信息
            JSONObject patientInfo = new JSONObject();
            String sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
            String birthday = IdCardUtil.getBirthdayForIdcardStr(patient.getIdcard());
            patientInfo.put("sex", sex);
            patientInfo.put("name", patient.getName());
            patientInfo.put("birthday", birthday);
            json.put("patientInfo", patientInfo);
        }
        return json;
    }
    /**
     * 取消处方
     *
     * @param prescriptionCode
     * @param reason
     */
    public void cancelPrescriptionByCode(String prescriptionCode, String reason) {
        WlyyDoorPrescriptionDO prescriptionDO = doorPrescriptionDao.findByCode(prescriptionCode);
        prescriptionDO.setStatus(-1);
        prescriptionDO.setReason(reason);
        prescriptionDO.setUpdateTime(new Date());
        doorPrescriptionDao.save(prescriptionDO);
        doorPrescriptionDetailDao.updateStatusByPrescriptionCode(prescriptionDO.getCode());
        doorPrescriptionDrugDao.updateDelByPrescriptionCode(prescriptionDO.getCode());
    }
    /**
     * 跳过开处方更新工单状态跟处方状态
     *
     * @param orderId
     */
    @Transactional
    public void skipPrescriptionByOrderId(String orderId) {
        doorServiceOrderDao.updatePrescriptionStatusAndStatusById(orderId);
    }
    /**
     * 上门前关联处方开方
     *
     * @param jsonData
     * @param doctor
     * @param patientCode
     * @param orderId
     * @return
     */
    public JSONObject saveDoorPrescriptionBefore(String jsonData, BaseDoctorDO doctor, String patientCode, String orderId) throws Exception {
        JSONObject res = new JSONObject();
        List<WlyyDoorPrescriptionDO> doorPrescriptionDOList = new ArrayList<>();
        JSONObject json = JSONObject.parseObject(jsonData);
        JSONArray jsonArray = json.getJSONArray("prescription");
        for(Object o : jsonArray) {
            JSONObject prescriptionJson = (JSONObject)o;
            String visitNo = prescriptionJson.getString("visitNo");
            List<WlyyDoorPrescriptionDO> lastPrescription = doorPrescriptionDao.findByVisitNoAndOrderIdNot(visitNo);
            if(lastPrescription.size() > 0 ){
                res.put("status", -1);
                res.put("msg", "该就诊记录已被关联");
                return res;
            }
            WlyyDoorPrescriptionDO prescription = new WlyyDoorPrescriptionDO();
            prescription = objectMapper.readValue(prescriptionJson.toString(), WlyyDoorPrescriptionDO.class);
            //获取居民签约信息
//            SignFamily signFamily = signFamilyDao.findSignFamilyByPatient(patientCode);
            //获取智业处方详细
            String response = jwDoorPrescriptionService.getVisitRecipeDetailUnion(visitNo, null, "");
//            String response = jwDoorPrescriptionService.getVisitRecipeDetailUnion(visitNo, null, signFamily.getHospital());
            JSONObject oldJson = JSONObject.parseObject(response);
            JSONObject data = JSONObject.parseObject(oldJson.getString("data"));
            String code = data.getString("CODE");
            if(oldJson.getInteger("status")!=200 || StringUtils.isBlank(code) || !code.equals("1")){
                res.put("status", -1);
                res.put("msg", "智业接口失败:"+oldJson.getString("msg"));
                return res;
            }
            JSONArray array = presModeAdapter.modelToDoorPrescription(response);
            for(Object object : array) {
                JSONObject jsonObject = (JSONObject) object;
                //保存处方信息
                prescription.setCode(getCode());
                prescription.setOrderId(orderId);
                prescription.setRecipeNo(jsonObject.getString("code"));
                prescription.setIsAfterDoor(1);//上门前开方
/*                prescription.setHospitalName(doctor.getHospitalName());
                prescription.setHospital(doctor.getHospital());
                prescription.setAdminTeamId(signFamily.getAdminTeamId());
                prescription.setVisitDept(doctor.getDept());
                //获取基卫科室明称
                if(StringUtils.isNotBlank(prescription.getJwDeptCode())) {
                    ZyIvDeptDict deptDict = zyIvDeptDictDao.findByDeptCode(prescription.getJwDeptCode());
                    if(deptDict != null) {
                        prescription.setVisitDeptName(deptDict.getDeptName());
                    }
                }
//                prescription.setVisitDeptName(doctor.getDeptName());
                prescription.setDoctorCode(doctor.getCode());
                prescription.setDoctorName(doctor.getName());
                prescription.setPatient(signFamily.getPatient());
                prescription.setPatientName(signFamily.getName());
                prescription.setSsc(signFamily.getSsc());*/
                prescription.setStatus(50);
                prescription.setJwHospital(jsonObject.getString("jwHospital"));
                prescription.setVisitTime(DateUtil.strToDate(jsonObject.getString("createTime")));
                //保存续方药品(处方)信息
                JSONArray infos = jsonObject.getJSONArray("prescriptionInfo");
                int day = 0;
                if (infos != null && infos.size() > 0 && infos.getJSONObject(0).get("dayCount") != null) {
                    day = infos.getJSONObject(0).getInteger("dayCount");
                }
                for (int i = 0; i < infos.size(); i++) {
                    JSONObject info = infos.getJSONObject(i);
                    WlyyDoorPrescriptionDrugDO prescriptionInfo = new WlyyDoorPrescriptionDrugDO();
                    prescriptionInfo.setPrescriptionCode(prescription.getCode());
                    prescriptionInfo.setCode(getCode());
                    prescriptionInfo.setDel(1);
                    prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
                    prescriptionInfo.setDrugCode(info.getString("drugCode"));//药品code
                    prescriptionInfo.setDrugName(info.getString("drugName"));//药品名称
                    prescriptionInfo.setDrugRate(info.getString("drugRate"));//吃药频率
                    prescriptionInfo.setDrugRateName(getZyCommonDictName(info.getString("drugRate")));
                    prescriptionInfo.setDrugFormat(info.getString("drugFormat"));//药品规格
                    prescriptionInfo.setNum(info.getInteger("num"));//药品数目
                    prescriptionInfo.setPrice(info.getBigDecimal("price"));//药品单价
//            prescriptionInfo.setIsRefrigerate(0);//是否冷藏 1是 0否
                    prescriptionInfo.setJwSubCode(info.getString("jwSubCode"));//智业子处方号
                    prescriptionInfo.setDrugNumUnit(info.getString("drugNumUnit"));//数量单位编码
                    prescriptionInfo.setDrugNumUnitName(info.getString("drugNumUnitName"));//数量单位名称
                    prescriptionInfo.setCost(info.getBigDecimal("cost"));//金额
                    prescriptionInfo.setCharge(info.getBigDecimal("charge"));//自付
                    prescriptionInfo.setBindFlag(info.getString("bindFlag"));//成组标志, 0.非成组,1.成组
                    prescriptionInfo.setDayCount(info.getInteger("dayCount"));//用药天数
                    //设置最小用药天数
                    if (day != 0 && prescriptionInfo.getDayCount() < day) {
                        day = prescriptionInfo.getDayCount();
                    }
                    prescriptionInfo.setDrugUsage(info.getString("drugUsage"));//用药方法编码
                    prescriptionInfo.setUsageName(info.getString("usageName"));//用药方法名称
                    prescriptionInfo.setPhysicDose(info.getString("physicDose"));//用药剂量
                    prescriptionInfo.setPhysicDoseUnit(info.getString("physicDoseUnit"));//剂量单位编码
                    prescriptionInfo.setPhysicDoseUnitName(info.getString("physicDoseUnitName"));//剂量单位名称
                    prescriptionInfo.setPhysicInjectPlace(info.getString("physicInjectPlace"));//注射地点编码
                    prescriptionInfo.setPhysicInjectPlaceName(info.getString("physicInjectPlaceName"));//注射地点名称
                    prescriptionInfo.setPhysicSkinTest(info.getString("physicSkinTest"));//注射地点名称
                    prescriptionInfo.setPhysicSkinTestName(info.getString("physicSkinTestName"));//皮试类型名称
                    prescriptionInfo.setRemark(info.getString("Remark"));//备注
                    //需要特殊处理的字段
/*                    ZyIvPhysicDict physicDict = zyDictService.findByPhysicCode(prescriptionInfo.getDrugCode());
                    String subjectClass = info.getString("subjectClass");//科目类型
                    String physicAmount = info.getString("physicAmount");//用药总量
                    String physicAmountUnit = info.getString("physicAmountUnit");//总量单位编码
                    String physicAmountUnitName = info.getString("physicAmountUnitName");//总量单位名称
                    Integer isRefrigerate = 0;
                    if (physicDict != null) {
                        subjectClass = physicDict.getSubjectClass();
                        isRefrigerate = "2".equals(physicDict.getStorageConditions()) ? 1 : isRefrigerate;
                        physicAmount = null;
                        physicAmountUnit = physicDict.getPackUnit();
                        physicAmountUnitName = zyDictService.findByDictNameAndCode("IV_MEASURE_UNIT_DICT", physicAmountUnit);
                    }
                    prescriptionInfo.setPhysicAmount(physicAmount);
                    prescriptionInfo.setPhysicAmountUnit(physicAmountUnit);
                    prescriptionInfo.setPhysicAmountUnitName(physicAmountUnitName);
                    prescriptionInfo.setIsRefrigerate(isRefrigerate);
                    prescriptionInfo.setSubjectClass(subjectClass);//科目编码*/
                    prescriptionInfo.setCreateTime(new Date());
                    doorPrescriptionDrugDao.save(prescriptionInfo);
                }
                prescription.setCreateTime(new Date());
                prescription.setUpdateTime(new Date());
                //保存续方记录
                doorPrescriptionDao.save(prescription);
                doorPrescriptionDOList.add(prescription);
            }
        }
        res.put("status", 200);
        res.put("data", doorPrescriptionDOList);
        //添加保存日志
//        prescriptionLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.create.getValue(), 1, 1);
        return res;
    }
    public JSONObject saveDoorPrescriptionAfter(String jsonData, BaseDoctorDO doctor, String patientCode, String orderId) {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject re = new JSONObject();
        WlyyDoorPrescriptionDO prescription = EntityUtils.jsonToEntity(jsonObject.getString("prescription"), WlyyDoorPrescriptionDO.class);
        //获取居民签约信息
//        SignFamily signFamily = signFamilyDao.findSignFamilyByPatient(patientCode);
        //医生映射信息
//        DoctorMapping doctorMapping = doctorMappingDao.findListByDoctorCode(doctor.getCode()).get(0);
        //判断这个工单上门后是否开过方,如果开过方且该就诊号没有作废过,就用同一个就诊号
        List<WlyyDoorPrescriptionDO> lastPrescriptionList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(orderId, 2);
        if(lastPrescriptionList.size() > 0){
            for(WlyyDoorPrescriptionDO prescriptionDO : lastPrescriptionList) {
                //判断该就诊号是否作废过
                List<WlyyDoorPrescriptionDO> fadePrescriptionList = doorPrescriptionDao.findByVisitNoAndStatus(prescriptionDO.getVisitNo(), -1);
                if (fadePrescriptionList.size() == 0) {
                    prescription.setVisitNo(prescriptionDO.getVisitNo());
                    break;
                }
            }
        }
        //保存开方字段
        String code = getCode();
        prescription.setCode(code);
        prescription.setOrderId(orderId);
        prescription.setIsAfterDoor(2);//上门后开方
/*        prescription.setHospitalName(doctor.getHospitalName());
        prescription.setHospital(doctor.getHospital());
        prescription.setAdminTeamId(signFamily.getAdminTeamId());
        prescription.setDoctorCode(doctor.getCode());
        prescription.setDoctorName(doctor.getName());
        prescription.setVisitDept(doctor.getDept());
//        prescription.setVisitDeptName(doctor.getDeptName());
        //获取基卫科室明称
        if(StringUtils.isNotBlank(prescription.getJwDeptCode())) {
            ZyIvDeptDict deptDict = zyIvDeptDictDao.findByDeptCode(prescription.getJwDeptCode());
            if(deptDict != null) {
                prescription.setVisitDeptName(deptDict.getDeptName());
            }
        }
        prescription.setJwDoctorCode(doctorMapping.getJwDoctor());
        //设置费别类型
        prescription.setRateType(zyDictService.getRateType());
        prescription.setRateTypeName("市医保");
        prescription.setPatient(signFamily.getPatient());
        prescription.setPatientName(signFamily.getName());
        prescription.setSsc(signFamily.getSsc());*/
        prescription.setVisitTime(new Date());
        prescription.setCreateTime(new Date());
        prescription.setUpdateTime(new Date());
        prescription.setStatus(30);
        doorPrescriptionDao.save(prescription);
        //保存开单记录
        List<WlyyDoorPrescriptionDrugDO> prescriptionDrugDOList = new ArrayList<>();
        List<WlyyDoorPrescriptionDrugDO> prescriptionDrugDOS = new ArrayList<>();
        try {
            if(jsonObject.containsKey("prescriptionDetailList")) {
                prescriptionDrugDOS = objectMapper.readValue(jsonObject.getString("prescriptionDetailList"), new TypeReference<List<WlyyDoorPrescriptionDrugDO>>() {
                });
            }
            if(jsonObject.containsKey("prescriptionDrugList")) {
                prescriptionDrugDOS.addAll(objectMapper.readValue(jsonObject.getString("prescriptionDrugList"), new TypeReference<List<WlyyDoorPrescriptionDrugDO>>() {
                }));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //保存上门服务开药记录
        for (WlyyDoorPrescriptionDrugDO prescriptionDrugDO : prescriptionDrugDOS) {
            prescriptionDrugDO.setCode(getCode());
            prescriptionDrugDO.setPrescriptionCode(code);
            prescriptionDrugDO.setCreateTime(new Date());
            prescriptionDrugDO.setDel(1);
            prescriptionDrugDOList.add(prescriptionDrugDO);
        }
        doorPrescriptionDrugDao.save(prescriptionDrugDOList);
        prescription.setRecipeDetailList(prescriptionDrugDOList);
        //保存上门后开方
        String response = jwDoorPrescriptionService.saveRecipeUnion(code, "", prescription.getJwDeptCode());
//        String response = jwDoorPrescriptionService.saveRecipeUnion(code, doctorMapping.getJwDoctor(), prescription.getJwDeptCode());
        JSONObject json = JSONObject.parseObject(response);
        if (json.getInteger("status") == 200) {
            JSONObject data = JSONObject.parseObject(json.getString("data"));
            String zyCode = data.getString("CODE");
            if ("1".equals(zyCode)) {
                JSONArray returnData = data.getJSONArray("returnData");
                if (returnData.size() > 0) {
                    JSONObject pre = returnData.getJSONArray(0).getJSONObject(0);
                    String visitNo = pre.getString("VISIT_NO");
                    String recipeNo = pre.getString("RECIPE_NO");
                    prescription.setVisitNo(visitNo);
                    prescription.setRecipeNo(recipeNo);
                    doorPrescriptionDao.save(prescription);
                    re.put("status", 200);
                    re.put("data", prescription);
                } else {
                    //请求失败
                    doorPrescriptionDao.delete(prescription.getId());
                    doorPrescriptionDrugDao.updateDelByPrescriptionCode(prescription.getCode());
                    JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                    re.put("status", -1);
                    re.put("msg", byRefParaData.getJSONObject(0).getString("errorMsg"));
                }
            } else {
                //调整请求失败
                doorPrescriptionDao.delete(prescription.getId());
                doorPrescriptionDrugDao.updateDelByPrescriptionCode(prescription.getCode());
                re.put("status", -1);
                re.put("msg", data.getString("MESSAGE"));
            }
        } else {
            //请求报错
            doorPrescriptionDao.delete(prescription.getId());
            doorPrescriptionDrugDao.updateDelByPrescriptionCode(prescription.getCode());
            re.put("status", -1);
            re.put("msg", json.getString("msg"));
        }
        return re;
    }
    public String getZyCommonDictName(String code) {
        try {
            String sql = "SELECT t.name FROM zy_common_dict t WHERE t.code=? AND t.dict_name='IV_RECIPE_FREQUENCY_DICT'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{code});
            if (list != null && list.size() > 0) {
                return (String) (list.get(0).get("name"));
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }
    public org.json.JSONArray getIcd10Info(String nameKey, Integer page, Integer pageSize) {
        StringBuffer stringBuffer = new StringBuffer(" SELECT t.code,t.name FROM icd10_dict t WHERE t.name LIKE ?  limit " + (page-1)*pageSize + "," + pageSize);
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(stringBuffer.toString(), new Object[]{"%" + nameKey + "%"});
        return new org.json.JSONArray(rs);
    }
}

+ 161 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorProcessLogService.java

@ -0,0 +1,161 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorProcessLogDao;
import com.yihu.jw.entity.door.WlyyDoorProcessLogDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * 工单状态变更记录(调度员操作记录)服务service
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年04月09日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorProcessLogService extends BaseJpaService<WlyyDoorProcessLogDO, WlyyDoorProcessLogDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorProcessLogService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //工单状态变更记录(调度员操作记录)服务基本信息
    private WlyyDoorProcessLogDO jsonToWlyyDoorProcessLog(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
        WlyyDoorProcessLogDO wlyyDoorProcessLog;
        try {
            wlyyDoorProcessLog = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorProcessLog").toString(),WlyyDoorProcessLogDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "工单状态变更记录(调度员操作记录)服务基本信息:"  + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return new WlyyDoorProcessLogDO();
        }
        this.save(wlyyDoorProcessLog);
        return wlyyDoorProcessLog;
    }
     /**
     * 创建工单状态变更记录(调度员操作记录)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorProcessLogDO wlyyDoorProcessLog = new WlyyDoorProcessLogDO();
        wlyyDoorProcessLog = jsonToWlyyDoorProcessLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorProcessLog);
        return result;
    }
    /**
     * 工单状态变更记录(调度员操作记录)(包括角色分配的菜单,模块等)
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam ;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg,failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorProcessLogDO wlyyDoorProcessLog = new WlyyDoorProcessLogDO();
        wlyyDoorProcessLog = jsonToWlyyDoorProcessLog(result, jsonObjectParam,jsonData);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,wlyyDoorProcessLog);
        return result;
    }
   /**
     * 查询工单状态变更记录(调度员操作记录)列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorProcessLogDO> sqlResultlist = new ArrayList<>();
    try {
        sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorProcessLogDO.class));
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库工单状态变更记录(调度员操作记录)列表信息失败:" + e.getMessage());
        return result;
    }
    Integer count = 0;
    try {
        count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
    } catch (Exception e) {
        result.put(ResponseContant.resultFlag, ResponseContant.fail);
        result.put(ResponseContant.resultMsg, "从数据库统计工单状态变更记录(调度员操作记录)数量失败:" + e.getMessage());
        return result;
    }
    result.put(ResponseContant.resultFlag, ResponseContant.success);
    result.put(ResponseContant.resultMsg, sqlResultlist);
    JSONObject countItem = new JSONObject();
    countItem.put("count", count);
    result.putAll(countItem);
    return result;
    }
}

+ 2912 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorServiceOrderService.java

@ -0,0 +1,2912 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.door.dao.*;
import com.yihu.jw.door.service.consult.ConsultTeamService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.*;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
/**
 * 上门服务工单服务service--居民端
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1
 */
@Service
public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceOrderDO, WlyyDoorServiceOrderDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorServiceOrderService.class);
/*    @Value("${server.server_url}")
    private String wxServerUrl;
    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;*/
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyDoorFeeDetailService wlyyDoorFeeDetailService;
    @Autowired
    private WlyyDoorFeeDetailDao wlyyDoorFeeDetailDao;
    @Autowired
    private WlyyDoorDoctorDao wlyyDoorDoctorDao;
    @Autowired
    private WlyyDoorDoctorService wlyyDoorDoctorService;
    @Autowired
    private WlyyDoorConclusionDao wlyyDoorConclusionDao;
    @Autowired
    private WlyyDoorPatientConfirmLogDao wlyyDoorPatientConfirmLogDao;
    @Autowired
    private WlyyDoorDoctorStatusDao wlyyDoorDoctorStatusDao;
    @Autowired
    private WlyyDoorCancelLogDao wlyyDoorCancelLogDao;
    @Autowired
    private WlyyDoorTransRecordDao wlyyDoorTransRecordDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private ConsultTeamService consultTeamService;
/*    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
    @Autowired
    private DmJobService dmJobService;*/
    @Autowired
    private WlyyDoorProcessLogDao wlyyDoorProcessLogDao;
/*    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private SignFamilyDao signFamilyDao;*/
    @Autowired
    private DoorOrderService doorOrderService;
    @Autowired
    private DoorServiceVoucherDao doorServiceVoucherDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private BaseOrgDao hospitalDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private WlyyDoorPrescriptionDao doorPrescriptionDao;
    @Value("${neiwang.enable}")
    private Boolean isneiwang;  //如果不是内网项目要转到到内网wlyy在上传
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Value("${neiwang.wlyy}")
    private String neiwangWlyy;  //内网的项目地址
    @Autowired
    private WlyyDoorOrderItemDao doorOrderItemDao;
    @Autowired
    private DoorServiceApplicationService doorServiceApplicationService;
    /**
     * 上门服务工单服务基本信息
     *
     * @param result
     * @param jsonObjectParam
     * @param jsonData
     * @return
     */
    public WlyyDoorServiceOrderDO jsonToWlyyDoorServiceOrder(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder;
        try {
            wlyyDoorServiceOrder = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return new WlyyDoorServiceOrderDO();
        }
        wlyyDoorServiceOrder.setNumber(getRandomIntStr());
        return wlyyDoorServiceOrder;
    }
    private String getRandomIntStr(){
        Random rand = new Random();
        int i = rand.nextInt(); //int范围类的随机数
        i = rand.nextInt(100); //生成0-100以内的随机数
        i = (int)(Math.random() * 100000000); //0-100以内的随机数,用Matn.random()方式
        return String.valueOf(i);
    }
    /**
     * 工单与服务项费用关联关系(新增)
     *
     * @param result
     * @param jsonObjectParam
     * @param order
     * {
     *     "packageItemArr":[
     *     {
     *    "type": null,
     *    "code": null,
     *    "name": null,
     *    "fee": null,
     *    "feeDiscount": null,
     *    "number": null,
     *    "status": null
     *  },
     *     ],
     *     "orderId": null,
     *     "status":""
     * }
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithPackageItemFeeAdd(JSONObject result, JSONObject jsonObjectParam, WlyyDoorServiceOrderDO order ) {
        List<WlyyDoorFeeDetailDO> feeDetailDOList = new ArrayList<>();
        List<WlyyDoorOrderItemDO> orderItemDOList = new ArrayList<>();
        BigDecimal totalFee = order.getTotalFee();
        if(null == totalFee){
            totalFee = new BigDecimal(0);
        }
        //服务项费用
        JSONArray packageItemArray = jsonObjectParam.getJSONArray("packageItemArr");
        if (!CollectionUtils.isEmpty(packageItemArray)) {
            for (Object one : packageItemArray) {
                WlyyDoorFeeDetailDO feeDetailDO = null;
                JSONObject oneJson = (JSONObject)one;
                try {
                    feeDetailDO = EntityUtils.jsonToEntity(one.toString(), WlyyDoorFeeDetailDO.class);
                    WlyyDoorOrderItemDO orderItemDO = new WlyyDoorOrderItemDO();
                    orderItemDO.setDoctor(order.getDoctor());
                    orderItemDO.setCode(feeDetailDO.getCode());
                    orderItemDO.setCreateTime(new Date());
                    orderItemDO.setPatient(orderItemDO.getPatient());
                    orderItemDOList.add(orderItemDO);
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单与服务费用关联关系时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                try {
                    //工单主表中记录总费用
                    totalFee = totalFee.add(feeDetailDO.getFee().multiply(BigDecimal.valueOf(feeDetailDO.getNumber())));
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单主表中记录总费用时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                // 服务项可能一开始由居民预约,后期由医生新增或医生删除
                Integer status = jsonObjectParam.getInteger("status");
                if(null == status || status == 1){
                    feeDetailDO.setStatus(WlyyDoorFeeDetailDO.Status.patient.getType());
                }else{
                    feeDetailDO.setStatus(status);
                }
//                feeDetailDO.setNumber(1);
                feeDetailDO.setOrderId(order.getId());
                if(StringUtils.isBlank(feeDetailDO.getId())) {
                    feeDetailDO.setCreateTime(new Date());
                }else {
                    feeDetailDO.setUpdateTime(new Date());
                }
                feeDetailDOList.add(feeDetailDO);
            }
//            order.setTotalFee(totalFee);
//            this.save(order);
            try {
                wlyyDoorFeeDetailDao.save(feeDetailDOList);
                doorOrderItemDao.save(orderItemDOList);
//                wlyyDoorFeeDetailService.batchInsert(feeDetailDOList);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "保存服务费用到数据库异常:," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
        }/*else{
            // 未添加服务项时,费用默认为0
            order.setTotalFee(new BigDecimal(0));
            this.save(order);
        }*/
        return false;
    }
    /**
     * 删除出诊医生或服务项
     * @param jsonObjectParam
     * {
     *     "deleteItemArr":[
     *        {
     *           "id":""
     *       },
     *        {
     *           "id":""
     *      }
     *     ],
     *     "deleteDoctorArr":[
     *     {
     *         "id":""
     *     },
     *      {
     *         "id":""
     *     }
     *     ]
     * }
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithFeeDelete(JSONObject jsonObjectParam,WlyyDoorServiceOrderDO orderDO) {
        BigDecimal totalFee = orderDO.getTotalFee();
        //删除的服务项
        JSONArray itemArray = jsonObjectParam.getJSONArray("deleteItemArr");
        if (!CollectionUtils.isEmpty(itemArray)) {
            List<WlyyDoorFeeDetailDO> list = new ArrayList<>();
            //删除的服务项要减去服务项费用
            BigDecimal itemFee = new BigDecimal(0);
            for(Object oneId : itemArray) {
                JSONObject oneIdJson = (JSONObject) oneId;
                WlyyDoorFeeDetailDO doorFeeDetail = wlyyDoorFeeDetailDao.findOne(String.valueOf(oneIdJson.get("id")));
                doorFeeDetail.setStatus(3);
                doorFeeDetail.setUpdateTime(new Date());
                list.add(doorFeeDetail);
                itemFee = itemFee.add(doorFeeDetail.getFee().multiply(BigDecimal.valueOf(doorFeeDetail.getNumber())));
            }
            wlyyDoorFeeDetailDao.save(list);
//            orderDO.setTotalFee(totalFee.subtract(itemFee));
        }
        //出诊的医生
        JSONArray doctorArray = jsonObjectParam.getJSONArray("deleteDoctorArr");
        if (!CollectionUtils.isEmpty(doctorArray)) {
            Set idStrSet = new HashSet();
            StringBuffer idStrBuffer = new StringBuffer();
            doctorArray.forEach(
                    oneId -> {
                        JSONObject idJson = (JSONObject)oneId;
                        idStrSet.add(idJson.getString("id"));
                        idStrBuffer.append(idJson.getString("id")).append(" ");
                    });
            // 根据id查询医生code集合
            List<String> doctors = wlyyDoorDoctorDao.findDoctorByIds(idStrSet);
            if(org.springframework.util.CollectionUtils.isEmpty(doctors)){
                logger.error("修改医生时,根据工单医生表id获取医生列表为空! id: " + idStrBuffer.toString() );
            }else{
                // 费用表里也有医生出诊费用,需要一起删除,获取工单服务项id(type=2 医生出诊费用)
                List<Map<String,Object>> doctorFees = wlyyDoorFeeDetailDao.findIdByCodeAndType(doctors, 2);
                if(!CollectionUtils.isEmpty(doctorFees)){
                    //删除的医生要减去出诊费用
                    BigDecimal totalSubFee = new BigDecimal(0);
                    for(Map<String,Object> rowMap : doctorFees){
                        String id = rowMap.get("id").toString();
                        idStrSet.add(id);
                        BigDecimal fee = BigDecimal.valueOf(Double.parseDouble(rowMap.get("fee").toString()));
                        totalSubFee = totalSubFee.add(fee);
                    }
                    wlyyDoorFeeDetailService.delete(idStrSet.toArray());
                    totalFee = orderDO.getTotalFee().subtract(totalSubFee);
//                    orderDO.setTotalFee(totalFee);
                }
            }
            wlyyDoorDoctorService.delete(idStrSet.toArray());
        }
        return false;
    }
    /**
     * 统计居民已经服务的次数
     * @param patient
     * @return
     */
    public Integer countPatientDoorTimes(String patient){
        Integer count = 0;
        String sql = "SELECT count(d.id) as count FROM wlyy_door_service_order o, wlyy_door_doctor d  where o.id = d.order_id and o.patient = '" + patient + "'";
        count = jdbcTemplate.queryForObject(sql,Integer.class);
        return count;
    }
    /**
     * 工单关联的出诊医生人员
     *
     * @param result
     * @param jsonObjectParam
     * @param orderDO
     * {
     *      "doctorArr":[
     *          {
     *               "doctor":"",
     *               "doctorName":"",
     *               "doctorLevel":"",
     *               "doctorJobCode":"",
     *               "doctorJobName":"",
     *          }
     *      ]
     *  }
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithDoctorAdd(JSONObject result, JSONObject jsonObjectParam, WlyyDoorServiceOrderDO orderDO) {
        List<WlyyDoorDoctorDO> doorDoctorDOList = new ArrayList<>();
        List<WlyyDoorFeeDetailDO> feeDetailDOList = new ArrayList<>();
        BigDecimal totalFee = orderDO.getTotalFee();
        if(null == totalFee){
            totalFee = new BigDecimal(0);
        }
        //出诊人员
        JSONArray doctorArray = jsonObjectParam.getJSONArray("doctorArr");
        if (!CollectionUtils.isEmpty(doctorArray)) {
            ConsultDo consult = consultDao.queryByRelationCode(orderDO.getId());
            String sessionId = null;
            if(consult!=null){
                sessionId = orderDO.getPatient() + "_" + consult.getId() + "_" + orderDO.getNumber() + "_" + consult.getType();
            }
            for (Object one : doctorArray) {
                WlyyDoorDoctorDO doorDoctorDO = null;
                try {
                    doorDoctorDO = EntityUtils.jsonToEntity(one.toString(), WlyyDoorDoctorDO.class);
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单关联出诊医生人员时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                // 医生不可重复添加
                if(wlyyDoorDoctorDao.existsByOrderIdAndDoctor(orderDO.getId(),doorDoctorDO.getDoctor())){
                    continue;
                }
                doorDoctorDO.setOrderId(orderDO.getId());
                doorDoctorDOList.add(doorDoctorDO);
                //出诊人员费用
                WlyyDoorFeeDetailDO feeDetailDO = new WlyyDoorFeeDetailDO();
                feeDetailDO.setOrderId(orderDO.getId());
                feeDetailDO.setCode(doorDoctorDO.getDoctor());
                feeDetailDO.setName(doorDoctorDO.getDoctorName());
                feeDetailDO.setNumber(1);
                feeDetailDO.setStatus(2);
                feeDetailDO.setType(2);
                feeDetailDO.setCreateTime(new Date());
                // 被服务的居民的次数(非代理居民)
                Integer tiems = countPatientDoorTimes(orderDO.getPatient());
//                BigDecimal fee = BigDecimal.valueOf(dmJobService.getJobFee(doorDoctorDO.getDoctorJobCode(),doorDoctorDO.getHospitalLevel(),tiems));
                BigDecimal fee = BigDecimal.valueOf(120);
                feeDetailDO.setFee(fee);
                totalFee = totalFee.add(fee);
                feeDetailDOList.add(feeDetailDO);
                // 把医生拉入会话,作为其中一个成员
                if(StringUtils.isNoneBlank(sessionId)){
                    imUtill.updateParticipant(sessionId,doorDoctorDO.getDoctor(),null);
                }
            }
            try {
                wlyyDoorDoctorDao.save(doorDoctorDOList);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "保存工单关联的出诊医生人员时:," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
            try {
                wlyyDoorFeeDetailDao.save(feeDetailDOList);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "保存工单关联的出诊医生人员费用详情时:," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
//            orderDO.setTotalFee(totalFee);
            this.save(orderDO);
        }
        return false;
    }
    /**
     * 获取居民所签约的机构的调度员(一个机构可以有多个调度员)
     * wlyy_doctor中,level -- 11-- 调度员
     * @param hospitalCode
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject queryDispatcherInfoByPatient(String hospitalCode) {
        JSONObject result = new JSONObject();
        List dispatcherInfoList = queryDispatcherInfoByHospital(hospitalCode);
        if(CollectionUtils.isEmpty(dispatcherInfoList)){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前居民所签约机构【" + hospitalCode + "】没有调度员,请联系管理员分配!";
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, dispatcherInfoList);
        return result;
    }
    public List<Map<String,Object>> queryDispatcherInfoByHospital(String hospital){
        String sql ="SELECT " +
                " d.`code`, " +
                " d.`name`, " +
                " d.`hospital_name` as hospitalName " +
                " FROM " +
                " manage_role_user m " +
                " JOIN manage_roles r ON m.role_id = r.id " +
                " JOIN (select code,name,hospital_name from wlyy_doctor where hospital = '"+ hospital +"') as d ON m.user_code = d.code" +
                " WHERE " +
                " r.code = 'dispatcher'";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 创建上门服务工单
     *
     * @param jsonData
     * @return
     */
    public JSONObject create(String jsonData) {
        logger.info("创建上门服务jsonData参数:" + jsonData);
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setNumber(getRandomIntStr());
        orderDO.setCreateTime(new Date());
        orderDO.setCreateUser(orderDO.getProxyPatient());
        orderDO.setCreateUserName(orderDO.getProxyPatientName());
        orderDO.setOrderInfo("0");
//        orderDO.setConclusionStatus(1);
        if(StringUtils.isEmpty(orderDO.getPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getProxyPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前代理对象code为空,请联系管理员检查参数!proxyPatient = " + orderDO.getProxyPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
/*        SignFamily signFamily = signFamilyDao.findSignFamilyByPatient(orderDO.getPatient());
        if (signFamily == null) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象未完成家庭医生签约,请完成签约后再预约上门服务!";
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }*/
        //已取消的订单也可以申请
        boolean bool = wlyyDoorServiceOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                new Integer[]{WlyyDoorServiceOrderDO.Status.waitForSend.getType(),
                        WlyyDoorServiceOrderDO.Status.waitForAccept.getType(),
                        WlyyDoorServiceOrderDO.Status.waitForServe.getType(),
                        WlyyDoorServiceOrderDO.Status.accept.getType(),
                });
        if(bool){
            String failMsg = "当前服务对象存在未完成的上门服务,请先完成该服务!";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setHospital(jsonObjectParam.getJSONObject("hospital").get("code").toString());
        orderDO.setCreateTime(new Date());
        //判断创建上门服务类型,发起类型(1本人发起 2家人待预约 3医生代预约)
        if(orderDO.getProxyPatient().equals(orderDO.getPatient())){
            orderDO.setType(1);
        }else if(!orderDO.getProxyPatient().equals(orderDO.getPatient())){
            orderDO.setType(2);
        }
        orderDO.setServiceStatus("1");
        this.save(orderDO);
        //创建咨询
        JSONObject successOrNot = null;
        try {
            successOrNot = consultTeamService.addDoorServiceConsult(orderDO.getId());
        } catch (Exception e) {
            String failMsg = "创建咨询时异常: " + e.getMessage();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if (Integer.parseInt(successOrNot.get(ResponseContant.resultFlag).toString()) == ResponseContant.fail) {
            return JSONObject.parseObject(successOrNot.toString());
        }
        ConsultTeamDo consultTeam = (ConsultTeamDo)successOrNot.get(ResponseContant.resultMsg);
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO)) {return result;}
        JSONObject dispatcherJson = queryDispatcherInfoByPatient(jsonObjectParam.getJSONObject("hospital").get("code").toString());
        if (dispatcherJson.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return dispatcherJson;
        }
        List<Map<String,Object>> dispatcherInfoList = (List)dispatcherJson.get(ResponseContant.resultMsg);
        for(Map<String,Object> map: dispatcherInfoList){
            String dispatcher = map.get("code").toString();
            // 派单消息-首页
            this.createMessage(orderDO.getId(),"system",dispatcher,402,"新增居民预约服务申请",orderDO.getPatientName() + "提交了服务预约申请,请您前往处理");
            // 派单-实时工单消息  430 居民提交工单申请-- 张三提交了服务工单12345678申请
            this.createMessage(orderDO.getId(),"system",dispatcher,430,"居民提交工单申请",orderDO.getPatientName() + "提交了服务工单"+orderDO.getNumber()+"申请");
        }
        //给机构调度员发送医生助手消息
        String  dispatcherSql = "SELECT u.user_code FROM `manage_role_user` u ,wlyy_doctor d where u.role_id = 22 and u.user_code = d.`code` and d.hospital = '" +orderDO.getHospital() + "'";
        List<Map<String, Object>> dispatcherList = jdbcTemplate.queryForList(dispatcherSql);
        for(Map<String, Object> map : dispatcherList) {
            sendWeixinMessage(3, map.get("user_code") + "", orderDO.getPatient());
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        //发送 预约卡片信息(2101类型)
        JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
        orderInfoContent.put("re_msg_type",0);//居民预约
        this.qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
        if(StringUtils.isNoneBlank(orderDO.getDoctor())){
            //服务医生修改,直接转派
            BaseDoctorDO transDoctor = doctorDao.findById(orderDO.getDoctor());
            sendOrderToDoctor(orderDO.getId(),null,"system","系统",transDoctor.getId(),transDoctor.getName(),transDoctor.getJobTitleName());
        }
        return result;
    }
    public void sendWeixinMessage(Integer type,String doctorCode,String patient){
        //提交资质审核
        if (type==1){
            try {
/*                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zztj");
                org.json.JSONObject sendJson = new org.json.JSONObject();
                Patient patient1 =patientDao.findByCode(patient);
                Doctor doctor = doctorDao.findByCode(doctorCode);
                String doctorName = doctor.getName();
                SignFamily signFamily = signFamilyDao.findByPatient(patient);
                String first =doctorName+"医生,您好!"+patient1.getName()+"提交了资质申请,请及时登录PC或APP处理";
                String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("type", "15"));
                params.add(new BasicNameValuePair("url", targetUrl));
                params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
                params.add(new BasicNameValuePair("first", first));
                params.add(new BasicNameValuePair("remark", templateConfig.getRemark()));
                params.add(new BasicNameValuePair("keywords", "居民资质申请审核"));
                params.add(new BasicNameValuePair("keywords", signFamily.getHospitalName()));
                params.add(new BasicNameValuePair("keywords", doctorName));
                httpClientUtil.post(url, params, "UTF-8");
                logger.info("sendJson: " + params);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(type==2){
            //调度员转交给家庭医生
            try {
/*                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zztj");
                org.json.JSONObject sendJson = new org.json.JSONObject();
                Patient patient1 =patientDao.findByCode(patient);
                Doctor doctor = doctorDao.findByCode(doctorCode);
                SignFamily signFamily = signFamilyDao.findByPatient(patient);
                String doctorName = doctor.getName();
                String first =doctorName+"医生,您好!"+patient1.getName()+"提交了资质申请,请及时登录PC或APP处理";
                String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("type", "15"));
                params.add(new BasicNameValuePair("url", targetUrl));
                params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
                params.add(new BasicNameValuePair("first", first));
                params.add(new BasicNameValuePair("remark", templateConfig.getRemark()));
                params.add(new BasicNameValuePair("keywords", "居民资质申请审核"));
                params.add(new BasicNameValuePair("keywords", signFamily.getHospitalName()));
                params.add(new BasicNameValuePair("keywords", doctorName));
                httpClientUtil.post(url, params, "UTF-8");
                logger.info("sendJson: " + params);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (type==3){
            //上门预约申请
            try {
/*                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zztj");
                org.json.JSONObject sendJson = new org.json.JSONObject();
                Patient patient1 =patientDao.findByCode(patient);
                Doctor doctor = doctorDao.findByCode(doctorCode);
                SignFamily signFamily = signFamilyDao.findByPatient(patient);
                String doctorName = doctor.getName();
                String first =doctorName+"医生,您好!"+patient1.getName()+"提交了上门出诊服务预约,请及时登录PC处理";
                String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("type", "15"));
                params.add(new BasicNameValuePair("url", targetUrl));
                params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
                params.add(new BasicNameValuePair("first", first));
                params.add(new BasicNameValuePair("remark", templateConfig.getRemark()));
                params.add(new BasicNameValuePair("keywords", "上门服务预约待派单"));
                params.add(new BasicNameValuePair("keywords", signFamily.getHospitalName()));
                params.add(new BasicNameValuePair("keywords", doctorName));
                httpClientUtil.post(url, params, "UTF-8");
                logger.info("sendJson: " + params);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (type==4){
            try {
                //社区调度员指派服务工单给家签医生
/*                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey","zztj");
                org.json.JSONObject sendJson = new org.json.JSONObject();
                Doctor doctor = doctorDao.findByCode(doctorCode);
                SignFamily signFamily = signFamilyDao.findByPatient(patient);
                String doctorName = doctor.getName();
                String first =doctorName+"医生,您好!您有新的服务工单,请及时登录APP或PC处理";
                String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("type", "15"));
                params.add(new BasicNameValuePair("url", targetUrl));
                params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
                params.add(new BasicNameValuePair("first", first));
                params.add(new BasicNameValuePair("remark", templateConfig.getRemark()));
                params.add(new BasicNameValuePair("keywords", "上门服务预约待接单"));
                params.add(new BasicNameValuePair("keywords", signFamily.getHospitalName()));
                params.add(new BasicNameValuePair("keywords", doctorName));
                httpClientUtil.post(url, params, "UTF-8");
                logger.info("sendJson: " + params);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 调度员进入聊天室
     * @param dispatcher
     * @param orderId
     */
    public JSONObject dispatcherIntoTopic(String orderId, String hospitalName, String dispatcher, String dispatcherName) {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if (null == orderDO) {
            String failMsg = "调度员进入聊天室时,找不到对应工单,工单id=" + orderId;
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = orderDO.getPatient() + "_" + consult.getId() + "_"  + orderDO.getNumber() +  "_" +  consult.getType();
        // 把调度员拉入会话,作为其中一个成员,第一个进入会话的调度员,系统发送欢迎语和居民的预约卡片信息
        if (StringUtils.isEmpty(orderDO.getDispatcher())) {
            orderDO.setDispatcher(dispatcher);
            orderDO.setDispatcherName(dispatcherName);
            this.save(orderDO);
            // 先进入会话,再聊天
            imUtill.updateParticipant(sessionId,dispatcher,null);
            String noticeContent = hospitalName + dispatcherName + "为您服务";
            this.qucikSendIM(orderId, dispatcher, "智能助手", "1", noticeContent);
        }
        // 把调度员拉入会话,作为其中一个成员
        imUtill.updateParticipant(sessionId,dispatcher,null);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, "调度员["+dispatcherName+"]进入会话成功");
        return result;
    }
    /**
     * 回写最后一个回复内容的调度员到工单表
     * @param dispatcher
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveLastDispatcher(String orderId, String dispatcher, String dispatcherName) {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if (null == orderDO) {
            String failMsg = "回写最后一个回复内容的调度员到工单表时,找不到对应工单,工单id=" + orderId;
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setDispatcher(dispatcher);
        orderDO.setDispatcherName(dispatcherName);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, dispatcherName);
        this.save(orderDO);
        return result;
    }
    /**
     * 修改上门服务工单(包括医生,费用,居民确认信息等)
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = new WlyyDoorServiceOrderDO();
        wlyyDoorServiceOrder = jsonToWlyyDoorServiceOrder(result, jsonObjectParam, jsonData);
        this.save(wlyyDoorServiceOrder);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        return result;
    }
    /**
     * 查询单个工单预约详情
     * @param id
     * @return
     */
    public JSONObject queryOneDetail(String id) {
        JSONObject orderJson = new JSONObject();
        List<WlyyDoorServiceOrderDO> orderList = this.findByField("id", id);
        if (CollectionUtils.isEmpty(orderList)) {
            orderJson.put(ResponseContant.resultMsg, orderList);
            return orderJson;
        }
        JSONObject orderBriefInfo = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = orderList.get(0);
        // 工单预约简要主体信息
        orderBriefInfo = (JSONObject) JSONObject.toJSON(orderDO);
        // 服务对象名称,
        String serverName = "";
        //获取居民性别跟年龄
        BasePatientDO patient = patientDao.findById(orderDO.getPatient());
        String sexName = IdCardUtil.getSexNameForIdcard_new(patient.getIdcard());
        int age = IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday());
        serverName = orderDO.getPatientName() + "(" + sexName + " " + age + "岁)";
        orderBriefInfo.put("patientName", orderDO.getPatientName());
        orderBriefInfo.put("serverName", serverName);
        orderBriefInfo.put("phone", orderDO.getPatientPhone());
        //处理详情时间节点格式
        orderBriefInfo.put("createTime", DateUtil.dateToStr(orderDO.getCreateTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("updateTime", DateUtil.dateToStr(orderDO.getUpdateTime(), "MM-dd HH:mm"));
        if(orderDO.getDispatcherResponseTime() != null) {
            orderBriefInfo.put("dispatcherResponseTime", DateUtil.dateToStr(orderDO.getDispatcherResponseTime(), "MM-dd HH:mm"));
        }
        orderBriefInfo.put("serviceResponseTime", DateUtil.dateToStr(orderDO.getServiceResponseTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("patientConfirmTime", DateUtil.dateToStr(orderDO.getPatientConfirmTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("payTime", DateUtil.dateToStr(orderDO.getPayTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("doctorSignTime", DateUtil.dateToStr(orderDO.getDoctorSignTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("completeTime", DateUtil.dateToStr(orderDO.getCompleteTime(), "MM-dd HH:mm"));
        orderBriefInfo.put("prescriptionTime", DateUtil.dateToStr(orderDO.getPrescriptionTime(), "MM-dd HH:mm"));
        // 计算服务包支付多少钱
        List<Map<String, Object>> feeDetailDOS = doorOrderService.getDoorFeeDetailGroupByStatus(id);
        String jsonData = null;
        try {
            jsonData = doorOrderService.serverPackagePriceByOrderId(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!CollectionUtils.isEmpty(feeDetailDOS)) {
            Map<String, Object> map = doorOrderService.countServerPackagePrice(jsonData, orderDO.getPatient());
            orderBriefInfo.put("packageFee", map.get("serverPackagePrice"));
        }
        orderJson.put("order", orderBriefInfo);
        //关联服务项
        String sql = "SELECT " +
                " fd.`code`, " +
                " fd.`name`, " +
                " fd.fee, " +
                " fd.type, " +
                " fd.`number`, " +
                " fd.`status`, " +
                " dd.doctor_job_name doctorJobName " +
                " FROM " +
                " wlyy_door_fee_detail fd " +
                " LEFT JOIN wlyy_door_doctor dd ON fd.order_id = dd.order_id " +
                " WHERE " +
                " fd.order_id = '" + id + "'" +
                " GROUP BY  fd.id";
        List<Map<String,Object>> feeDetailList = new ArrayList<>();
        try {
            feeDetailList = jdbcTemplate.queryForList(sql);
        }catch (Exception e){
            logger.error("居民工单详情-查询关联服务项费用异常:" + e.getMessage());
            e.printStackTrace();
            return orderJson;
        }
        JSONArray itemArray = new JSONArray();
        if (!CollectionUtils.isEmpty(feeDetailList)) {
            for (Map<String,Object> feeDetailMap : feeDetailList) {
                JSONObject itemJson = new JSONObject();
                itemJson.put("code",feeDetailMap.get("code"));
                itemJson.put("name",feeDetailMap.get("name"));
                itemJson.put("fee",feeDetailMap.get("fee"));
                itemJson.put("number",feeDetailMap.get("number"));
                itemJson.put("status",feeDetailMap.get("status"));
                itemJson.put("type",feeDetailMap.get("type"));
                itemJson.put("doctorJobName",feeDetailMap.get("doctorJobName"));
                itemArray.add(itemJson);
            }
        }
        orderJson.put("itemArray", itemArray);
        //关联的医生
        List<WlyyDoorDoctorDO> doctorDOList = wlyyDoorDoctorDao.findByOrderId(id);
        JSONArray doctoryArray = new JSONArray();
        if (!CollectionUtils.isEmpty(doctorDOList)) {
            for (WlyyDoorDoctorDO doctorDO : doctorDOList) {
                JSONObject doctorJson = new JSONObject();
                doctorJson.put("doctor",doctorDO.getDoctor());
                doctorJson.put("doctorName",doctorDO.getDoctorName());
                doctorJson.put("doctorJobName",doctorDO.getDoctorJobName());
                doctoryArray.add(doctorJson);
            }
        }
        orderJson.put("doctoryArray", doctoryArray);
        //服务小结登记情况
        JSONObject conclusionJson = new JSONObject();
        WlyyDoorConclusionDO conclusionDO = wlyyDoorConclusionDao.findByOrderId(orderDO.getId());
        if(null != conclusionDO){
            conclusionJson.put("time",conclusionDO.getCreateTime());
            conclusionJson.put("id",conclusionDO.getId());
        }
        orderJson.put("conclusion",conclusionJson);
        //获取上门前后开方详情
        List<WlyyDoorPrescriptionDO> doorBeforePrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 1);
        List<WlyyDoorPrescriptionDO> doorAfterPrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 2);
        orderJson.put("doorBeforePrescription",doorBeforePrescriptionDOList);
        orderJson.put("doorAfterPrescription", doorAfterPrescriptionDOList);
        return orderJson;
    }
    /**
     * 生成二維碼
     * @param id
     * @param token
     * @return
     */
    public String twoDimensionalCode(String id , String token) {
        JSONObject orderJson = new JSONObject();
        List<WlyyDoorServiceOrderDO> orderList = this.findByField("id", id);
        if (orderList.size()>0){
            WlyyDoorServiceOrderDO orderDO = orderList.get(0);
            Map<String, Object> param = new HashedMap();
            String fileUrl = "";
            //生成二维码图片
            String contentJsonStr=orderDO.getNumber();
            InputStream ipt = QrcodeUtil.createQrcode(contentJsonStr, 300, "png");
            if (isneiwang) {
                // 圖片列表
                List<String> tempPaths = new ArrayList<String>();
                try {
                    ObjectNode imgNode = fastDFSUtil.upload(ipt, "png", "plan_service_qrcode" + System.currentTimeMillis());
                    JSONObject json = JSONObject.parseObject(imgNode.toString());
                    tempPaths.add(json.getString("fid"));
                    String urls = "";
                    for (String image : tempPaths) {
                        if (urls.length() == 0) {
                            urls = image;
                        } else {
                            urls += "," + image;
                        }
                    }
                    fileUrl = fastdfs_file_url + urls;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    fileUrl = fastdfs_file_url + PrescriptionQRCodetoNeiWang(ipt);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("服务码-----------1"+fileUrl);
            param.put("number", orderDO.getNumber());
            param.put("imageUrl",fileUrl);
            return fileUrl;
        }else {
            return null;
        }
    }
    /**
     * 长处方生成取药码,生成取药二维码
     * 如果是外网那是发送到内网的服务器
     * @param ipt
     * @return
     */
    public String PrescriptionQRCodetoNeiWang(InputStream ipt) throws FileNotFoundException {
        String filename = "QRCode_"+System.currentTimeMillis();
        String fileUrls = "";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String returnStr = request(request, ipt,filename );
        logger.info("returnStr :" + returnStr);
        logger.info("fileName :" + filename);
        logger.info("result :" + returnStr.toString());
        if (returnStr != null) {
            //1.3.7去掉前缀
            fileUrls += returnStr+",";
        }
        return fileUrls.substring(0,fileUrls.length()-1);
    }
    public String request(HttpServletRequest request, InputStream in, String fileName) {
        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径 http://172.19.103.88/wlyy/upload/chat
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(request.getParameter("type")) ||
                    !org.springframework.util.StringUtils.isEmpty(request.getAttribute("type"))) {
                builder.addTextBody("type",  null != request.getParameter("type") ? request.getParameter("type") : String.valueOf(request.getAttribute("type"))); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = org.apache.http.util.EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 居民端-查询上门服务工单列表(预约咨询记录)
     *
     * @return
     */
    public JSONObject queryInfoList(String patient,Integer status, int page, int size) {
        JSONObject result = new JSONObject();
        status = null == status ? -100 : status;
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : size;
        String sql = "SELECT " +
                "  d.photo AS doctorPhoto, " +
                "  d.`name` AS doctorName, " +
                "  d.`job_name` AS doctorJobName, " +
                "  d.hospital_name AS hospitalName, " +
                "  d.mobile AS doctorPhone, " +
                "  o.id, " +
                "  o.number, " +
                "  o.total_fee as totalFee, " +
                "  o.patient_expected_serve_time AS serveTime, " +
                "  o.serve_desc AS description, " +
                "  o.`status` AS status, " +
                "  o.`pay_way` AS payWay, o.type," +
                "  ifnull(de.order_id,concat(rand(),'_notExist')) AS feeOrderId, " +
                "  dm.phone AS hospitalPhone, " +
                "  count(de.number) as itemCount " +
                " FROM " +
                "  ( wlyy_door_service_order o " +
                " LEFT JOIN wlyy_doctor d ON o.doctor = d.`code`) " +
                " LEFT JOIN wlyy_door_fee_detail de on o.id = de.order_id " +
                " LEFT JOIN dm_hospital dm on o.hospital = dm.code " +
                " WHERE " +
                "  (o.patient = '{patient}' " +
//                "or o.proxy_patient = '{patient}'" +
                ") " +
                " AND (o.`status` = {status} or -100 = {status})" +
                "  group by o.id " +
                " ORDER BY o.create_time desc" +
                " LIMIT {start},{end};";
        String finalSql = sql.replace("{patient}", patient)
                .replace("{status}", String.valueOf(status))
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "SELECT  " +
                "   count(DISTINCT o.id)  " +
                " FROM  " +
                "  ( wlyy_door_service_order o " +
                " LEFT JOIN wlyy_doctor d ON o.doctor = d.`code`) " +
                " LEFT JOIN wlyy_door_fee_detail de on o.id = de.order_id " +
                " LEFT JOIN dm_hospital dm on o.hospital = dm.code " +
                " WHERE  " +
                "  (o.patient = '{patient}' or o.proxy_patient = '{patient}') " +
                " AND (o.`status` = {status} or -100 = {status})";
        String finqlCountSql = countSql.replace("{patient}", patient)
                .replace("{status}", String.valueOf(status));
        List sqlResultlist = new ArrayList<>();
        logger.info("infoList-info: "+finalSql);
        logger.info("infoList-count: "+finqlCountSql);
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库上门服务工单列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计上门服务工单数量失败:" + e.getMessage());
            return result;
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**
     * 居民端-统计上门服务工单各状态下的数量列表(预约咨询记录)
     *
     * @return
     */
    public JSONObject queryInfoStatusCountList(String patient) {
        JSONObject result = new JSONObject();
        String countSql = "SELECT " +
                "  count(o.id) as count, " +
                "  o.status as status " +
                " FROM " +
                "  wlyy_door_service_order o " +
                " WHERE " +
                "  o.patient = '"+ patient + "' " +
//                "or o.proxy_patient = '"+ patient + "'" +
                " GROUP BY o.`status`";
        List<Map<String,Object>> countMapList = new ArrayList();
        try {
            countMapList = jdbcTemplate.queryForList(countSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "统计上门服务工单各状态下的数量列表失败:" + e.getMessage());
            return result;
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, countMapList);
        return result;
    }
    /**
     * 居民端-居民付款
     * @param orderId
     * @param payWay
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(String orderId,int payWay) {
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if(null == doorServiceOrderDO){
            return false;
        }
        doorServiceOrderDO.setPayWay(payWay);
        doorServiceOrderDO.setPayTime(new Date());
        wlyyDoorServiceOrderDao.save(doorServiceOrderDO);
        return true;
    }
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderInfo(String orderId) {
        String sql = "UPDATE `wlyy_door_service_order` SET order_info =2 WHERE id = ?";
        Object [] params = new Object[]{orderId};
        int a = jdbcTemplate.update(sql , params);
        return a;
    }
    /**
     * 服务工单居民确认操作日志记录
     *
     * {
     *     "confirmInfo":{
     *         "patient":"",
     *         "patientName":"",
     *         "type":"",
     *         "description":""
     *     }
     * }
     *
     * @param result
     * @param jsonObjectParam
     * @param orderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithConfirmLogAdd(JSONObject result, JSONObject jsonObjectParam, String orderId) {
        // 确认信息
        JSONObject confirmInfo = jsonObjectParam.getJSONObject("confirmInfo");
        if (null != confirmInfo) {
            WlyyDoorPatientConfirmLogDO confirmLogDO = null;
            try {
                confirmLogDO = EntityUtils.jsonToEntity(confirmInfo.toString(), WlyyDoorPatientConfirmLogDO.class);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "工单关联【居民确认操作日志记录】时," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
            confirmLogDO.setOrderId(orderId);
            confirmLogDO.setCreateTime(new Date());
            try {
                wlyyDoorPatientConfirmLogDao.save(confirmLogDO);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "保存工单关联的【居民确认操作日志记录】时:," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
        }
        return false;
    }
    /**
     * 取消工单
     * @param orderId
     * @param type 取消类型
     * @param reason 取消理由
     */
    public JSONObject cancelOrder(String orderId,int type,String reason,String dispatcher,String dispatcherName){
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if(null == orderDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "【取消工单】该工单不存在:," + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(orderDO.getStatus() > WlyyDoorServiceOrderDO.Status.waitForServe.getType()){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "只有医生服务前的工单才可取消:," + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setCancelType(type);
        orderDO.setCancelTime(new Date());
        orderDO.setCancelReason(reason);
        if(!StringUtils.isEmpty(dispatcher)){
            orderDO.setDispatcher(dispatcher);
            orderDO.setDispatcherName(dispatcherName);
        }
        orderDO.setStatus(WlyyDoorServiceOrderDO.Status.cancel.getType());
        this.save(orderDO);
        //如果是调度员取消,推送IM取消工单json消息,
/*        if(type == WlyyDoorServiceOrderDO.CancelType.dispatcher.getType()){
            JSONObject content = this.queryOrderCardInfo(orderDO);
            content.put("title","工单已取消");
//            this.qucikSendIM(orderId,dispatcher,dispatcherName,"2101",content.toJSONString());
            List<BaseMessageDO> messages = messageDao.queryByRelationCodeAndTypeIn(orderId,new Integer[]{402,403,430});
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有系统消息!!orderId:" + orderId);
            } else {
                // 432 调度员拒单即取消工单-- 李四拒绝了张三的服务工单12345678
                messages.forEach(
                        message -> {
                            if (message.getType() == 430) {
                                message.setTitle("调度员拒单");
                                message.setContent(orderDO.getDispatcherName() + "拒绝了"+ orderDO.getPatientName() +"的服务工单" + orderDO.getNumber());
                                message.setType(432);
                                message.setReceiver(dispatcher);
                                message.setSender(dispatcher);
                                message.setCreateTime(new Date());
                            }else{
                                message.setOver("0");
                            }
                            messageDao.save(message);
                        }
                );
            }
        }
        else if(type == WlyyDoorServiceOrderDO.CancelType.patient.getType()){                   //居民取消,消息列表也应该不显示
            List<Message> messages = messageDao.queryByRelationCodeAndTypeIn(orderId,new Integer[]{402,403});
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有系统消息!!orderId:" + orderId);
            } else {
                messages.forEach(
                        message -> {
                            message.setOver("0");
                            messageDao.save(message);
                        }
                );
            }
        }*/
        //保存取消记录
        WlyyDoorCancelLogDO cancelLogDO = new WlyyDoorCancelLogDO();
        cancelLogDO.setOrderId(orderId);
        cancelLogDO.setPatient(orderDO.getProxyPatient());
        cancelLogDO.setCancelType(type);
        cancelLogDO.setCancelReason(reason);
        cancelLogDO.setTime(orderDO.getCancelTime());
        wlyyDoorCancelLogDao.save(cancelLogDO);
        //保存居民确认取消记录
        JSONObject confirmInfo = new JSONObject();
        confirmInfo.put("orderId",orderId);
        confirmInfo.put("patient",orderDO.getProxyPatient());
        confirmInfo.put("patientName",orderDO.getProxyPatientName());
        confirmInfo.put("type",4);
        confirmInfo.put("description",reason);
        JSONObject confirmInfoJson = new JSONObject();
        confirmInfoJson.put("confirmInfo",confirmInfo);
        this.orderWithConfirmLogAdd(result,confirmInfo,orderId);
/*        Consult consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
        Patient patient = patientInfoService.findByCode(orderDO.getPatient());
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","smyyyqx");
        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", first);
        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
        json.put("keyword2", "上门预约已取消");
        json.put("url", templateConfig.getUrl());
        json.put("remark", templateConfig.getRemark());
        if(consult != null) {
            json.put("consult", consult.getCode());
        }else {
            json.put("id", orderDO.getId());
        }
        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);*/
        // 工单状态变更记录
        WlyyDoorProcessLogDO processLogDO = new WlyyDoorProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(WlyyDoorServiceOrderDO.Status.cancel.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispatcherName);
        wlyyDoorProcessLogDao.save(processLogDO);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, "工单服务已取消!");
        return result;
    }
    public JSONObject orderMsgTask(String orderId){
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
/*        BasePatientDO patient = patientDao.findById(orderDO.getPatient());
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","smyyyqx");
        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", orderDO.getPatientName()+",您好!您的上门服务知情同意书已送达");
        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
        json.put("keyword2", "知情同意书已推送");
//        json.put("url", templateConfig.getUrl());
        json.put("url", "appoint_service/html/appoint-serviceDetail.html?id="+orderId);
//        appoint_service/html/appoint-serviceDetail.html?openid=ojsU-1XJVftkfdbP1F5bi8JVPtOo&consult=e0d17c67ab07477f8e96534bc610e51b
        json.put("remark", templateConfig.getRemark());
        if(consult != null) {
            json.put("consult", consult.getCode());
        }else {
            json.put("id", orderDO.getId());
        }
        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);*/
        return result;
    }
    /**
     * 统计居民一个月内工单取消次数
     * @param patient
     */
    public int countPtientCancelTimesOneMonth(String patient){
        if(StringUtils.isEmpty(patient)){
            return 100;
        }
        Integer count = wlyyDoorCancelLogDao.countCancelTimes(patient);
        return count;
    }
    /**
     * 查询预约简要卡片信息
     *
     * 服务时间:2019-01-01   12:30
     * 服务对象:张三
     * 联系电话:13125256565(儿子)
     * 上门地址:福建省厦门市思明区望海路55号
     *
     * @param orderDO
     * @return
     */
    public JSONObject queryOrderCardInfo(WlyyDoorServiceOrderDO orderDO){
        JSONObject result = new JSONObject();
        result.put("patientCode", orderDO.getPatient());
        BasePatientDO patientDO = patientDao.findById(orderDO.getPatient());
        result.put("title","预约服务信息如下:");
        result.put("orderId",orderDO.getId());
        result.put("status",orderDO.getStatus());
        result.put("number",orderDO.getNumber());
        result.put("serveDesc",orderDO.getServeDesc());
        result.put("expectedDoctor",orderDO.getExpectedDoctorName());
        result.put("serviceStatus",orderDO.getServiceStatus());
        if(orderDO.getStatus() < 4){
            if(StringUtils.isBlank(orderDO.getPatientExpectedServeTime())){
                result.put("time","工作时间");
            }else {
                result.put("time", orderDO.getPatientExpectedServeTime());
            }
        }else {
            if(StringUtils.isBlank(orderDO.getDoctorArrivingTime())){
                result.put("time","工作时间");
            }else{
                result.put("time", orderDO.getDoctorArrivingTime());
            }
        }
        result.put("patientName",patientDO.getName());
        result.put("patientSex",IdCardUtil.getSexNameForIdcard_new(patientDO.getIdcard()));
        result.put("patientAge", IdCardUtil.getAgeByIdcardOrBirthday(patientDO.getIdcard(),patientDO.getBirthday()));
        result.put("phone",orderDO.getPatientPhone());
        result.put("serveDesc",orderDO.getServeDesc());
        if(StringUtils.equalsIgnoreCase(orderDO.getPatient(),orderDO.getProxyPatient())){
            result.put("relation","");
        }else{
            result.put("relation",orderDO.getPatientRelation());
        }
        result.put("serveTown",orderDO.getServeTown());
        result.put("serveAddress",orderDO.getServeAddress());
        result.put("type",11);
        return result;
    }
    /**
     * 修改预约简要卡片信息
     *
     * 服务时间:2019-01-01   12:30
     * 服务对象:张三
     * 联系电话:13125256565(儿子)
     * 上门地址:福建省厦门市思明区望海路55号
     *
     * {
     *     "orderId":"",
     *     "doctorArrivingTime":"",
     *     "patientName":"",
     *     "phone:"",
     *     "serveAddress:"",
     *     "serveLat:"",
     *     "serveLon:"",
     *     "serveTown:"",
     *     "serveAddress:"",
     * }
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateOrderCardInfo(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findOne(jsonObjectParam.getString("orderId"));
        wlyyDoorServiceOrder.setPatientName(jsonObjectParam.getString("patientName"));
//        wlyyDoorServiceOrder.setProxyPatientPhone(jsonObjectParam.getString("phone"));
        // 居民电话
        if(!StringUtils.isEmpty(jsonObjectParam.getString("phone"))){
            wlyyDoorServiceOrder.setPatientPhone(jsonObjectParam.getString("phone"));
        }
        // 医生预计达到时间
        if(!StringUtils.isEmpty(jsonObjectParam.getString("doctorArrivingTime"))){
            wlyyDoorServiceOrder.setDoctorArrivingTime(jsonObjectParam.get("doctorArrivingTime").toString());
        }
        // 居民期望服务时间
//        if(!StringUtils.isEmpty(jsonObjectParam.getString("patientExpectedServeTime"))){
        wlyyDoorServiceOrder.setPatientExpectedServeTime(jsonObjectParam.get("patientExpectedServeTime").toString());
//        }
        // 服务区
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serveTown"))){
            wlyyDoorServiceOrder.setServeTown(jsonObjectParam.getString("serveTown"));
        }
        // 服务地址
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serveAddress"))){
            wlyyDoorServiceOrder.setServeAddress(jsonObjectParam.getString("serveAddress"));
        }
        wlyyDoorServiceOrder.setServeAddress(jsonObjectParam.getString("serveAddress"));
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serveLat"))){
            wlyyDoorServiceOrder.setServeLat(jsonObjectParam.getString("serveLat"));
        }
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serveLon"))){
            wlyyDoorServiceOrder.setServeLon(jsonObjectParam.getString("serveLon"));
        }
        // 服务描述
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serveDesc"))){
            wlyyDoorServiceOrder.setServeDesc(jsonObjectParam.getString("serveDesc"));
        }
        //服务类型    医生端和居民端公用接口
        if(!StringUtils.isEmpty(jsonObjectParam.getString("serviceStatus"))){
            wlyyDoorServiceOrder.setServiceStatus(jsonObjectParam.getString("serviceStatus"));
        }else {
            wlyyDoorServiceOrder.setServiceStatus("1");//默认为1  预约项目
        }
//        wlyyDoorServiceOrder.setIsPatientConfirm(WlyyDoorServiceOrderDO.IsPatientConfirm.yes.getType());
//        wlyyDoorServiceOrder.setPatientConfirmTime(new Date());
        this.save(wlyyDoorServiceOrder);
        //新增工单居民确认操作日志记录
        if (orderWithConfirmLogAdd(result, jsonObjectParam, wlyyDoorServiceOrder.getId())) {return result;}
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        //发送 预约卡片信息(2101类型)
        JSONObject orderInfoContent = this.queryOrderCardInfo(wlyyDoorServiceOrder);
        orderInfoContent.put("re_msg_type",1);//医生修改待确认
        this.qucikSendIM(wlyyDoorServiceOrder.getId(), wlyyDoorServiceOrder.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
        return result;
    }
    /**
     * 医生更新上门信息
     *
     * 预计到达:2019-01-01   09:00
     * 服务医生:张三(全科医生)、王五(健管师)
     *
     * {
     *     "orderId":"",
     *     "doctorArrivingTime":"",
     *     "doctorArr":[
     *         {
     *              "doctor":"",
     *              "doctorName":"",
     *              "doctorLevel":3,
     *              "doctorJobCode":"",
     *              "doctorJobName":"",
     *         }
     *     ],
     *     "deleteDoctorArr":[
     *          {
     *              "id":""
     *          },
     *          {
     *              "id":""
     *          }
     *     ]
     * }
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateDoctorInfo(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findOne(jsonObjectParam.getString("orderId"));
        if(!StringUtils.isEmpty(jsonObjectParam.getString("doctorArrivingTime"))) {
            wlyyDoorServiceOrder.setDoctorArrivingTime(jsonObjectParam.getString("doctorArrivingTime"));
        }
        //添加居民同意状态
        wlyyDoorServiceOrder.setIsPatientConfirm(1);
        wlyyDoorServiceOrder.setPatientConfirmTime(new Date());
        wlyyDoorServiceOrder.setUpdateTime(new Date());
        this.save(wlyyDoorServiceOrder);
        //修改时有更改到关联关系,则先删除原有关联关系,再新增关联关系
        //删除工单原来医生的关联关系
        // 删除出诊医生或服务项
        this.orderWithFeeDelete(jsonObjectParam,wlyyDoorServiceOrder);
        //新增工单医生关联关系
        if (orderWithDoctorAdd(result, jsonObjectParam, wlyyDoorServiceOrder)) {return result;}
        //新增工单居民确认操作日志记录
        if (orderWithConfirmLogAdd(result, jsonObjectParam, wlyyDoorServiceOrder.getId())) {return result;}
        //微信模板消息-反馈处理通知
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(),30,);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        return result;
    }
    public List filterPatientType(List data,String type){
        String[] types = type.split(",");
        Set<String> patientSet = doorServiceVoucherDao.queryByTypeIn(types);
        if(CollectionUtils.isEmpty(patientSet)){
            return data;
        }
//        data.forEach();
        return data;
    }
    /**
     * 调度员-查询-工单列表
     *
     * @return
     */
    public JSONObject queryBriefList(String dispatcher,String hospital,String orderNumber,String patientName,String phone,Integer status, String patientType,int page, int size) {
        JSONObject result = new JSONObject();
        orderNumber = null == orderNumber ? "" : orderNumber;
        patientName = null == patientName ? "" : patientName;
        phone = null == phone ? "" : phone;
        status = null == status ? -100 : status;
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        StringBuffer buffer = new StringBuffer();
        if (StringUtils.isNoneBlank(orderNumber)){
            buffer.append(" AND ( o.`number` like '%"+orderNumber+"%' ) ");
        }else if (StringUtils.isNoneBlank(patientName)){
            buffer.append(" AND o.`patient_name` like '%"+patientName+"%' ");
        }else if (StringUtils.isNoneBlank(phone)){
            buffer.append(" AND o.`proxy_patient_phone` like '%"+phone+"%'");
        }
        String sql = "SELECT " +
                "  p.name AS patientName, " +
                "  p.photo AS photo, " +
                "  case p.sex  " +
                "  when 1 then '男'  " +
                "  when 2 then '女' " +
                "  end AS sex, " +
                "  TIMESTAMPDIFF(year,p.birthday,NOW()) AS age," +
                "  o.id as orderId, " +
                "  o.patient_phone as phone, " +
                "  o.proxy_patient as proxyPatient, " +
                "  o.patient as patient, " +
                "  o.number as number, " +
                "  o.patient_expected_serve_time as serveTime, o.doctor, o.doctor_name as doctorName, " +
                "  o.serve_address as address, " +
                "  o.serve_lon as lon, " +
                "  o.serve_lat as lat, " +
                "  o.`status` as status, " +
                "  o.`dispatcher_name` as dispatcherName, " +
                "  concat( o.patient,'_' ,c.`code`, '_',o.`number`,'_11' ) as sessionId, " +
                "   t1.`type` as patientType " +
                " FROM " +
                " ( wlyy_door_service_order o " +
                "LEFT JOIN wlyy_patient p ON o.patient = p.`code` ) LEFT JOIN wlyy_consult c on o.id = c.relation_code" +
                " JOIN ( " +
                "         select a.patient, group_concat(v.type) as type " +
                "         from wlyy_door_service_voucher v " +
                "                  JOIN (select t.id, t.patient, max(t.create_time) " +
                "                        from wlyy_door_service_application t " +
                "                        where t.status in (2, 3) " +
                "                        group by t.patient) as a " +
                "                       on a.id = v.service_id " +
                "         where v.status = 1 " +
                "         group by a.patient " +
                "        ) as t1 on o.patient = t1.patient" +
                " WHERE " +
                "  o.hospital = '{hospital}' and o.type != 3 " +buffer+
                " AND ( o.`status` = {status} OR -100 = {status} ) " +
                " ORDER BY o.create_time desc " +
                " LIMIT {start},{end};";
        String finalSql = sql.replace("{hospital}", hospital)
                .replace("{status}", String.valueOf(status))
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "SELECT  " +
                "   count(o.id)  " +
                " FROM  " +
                "   wlyy_door_service_order o  " +
                " LEFT JOIN wlyy_patient p ON o.patient = p.`code` " +
                " JOIN  ( " +
                "         select a.patient, group_concat(v.type) as type " +
                "         from wlyy_door_service_voucher v " +
                "                  JOIN (select t.id, t.patient, max(t.create_time) " +
                "                        from wlyy_door_service_application t " +
                "                        where t.status in (2, 3) " +
                "                        group by t.patient) as a " +
                "                       on a.id = v.service_id " +
                "         where v.status = 1 " +
                "         group by a.patient " +
                "        ) as t1 on o.patient = t1.patient" +
                " WHERE  " +
                "  o.hospital = '{hospital}' " +buffer+
                " AND (o.`status` = {status} or -100 = {status})";
        String finqlCountSql = countSql.replace("{hospital}", hospital)
                .replace("{status}", String.valueOf(status));
        List<Map<String,Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            logger.info(finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询【调度员】上门服务工单列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计【调度员】上门服务工单数量失败:" + e.getMessage());
            return result;
        }
        List filteredResult = new ArrayList();
        String[] types = null;
        if(!StringUtils.isEmpty(patientType)){
            types = patientType.split(",");
        }else{
            types = new String[]{"1","2","3","4","5","6"};
        }
        String serviceSql = "SELECT count(d.id) times FROM wlyy_door_doctor d where d.order_id in(SELECT id from wlyy_door_service_order WHERE DATE_FORMAT(doctor_sign_time, '%Y') = DATE_FORMAT(NOW(), '%Y') AND patient=?)";
        sqlResultlist.forEach(
                oneMap -> {
                    // 获取服务次数
                    Integer serviceCount = jdbcTemplate.queryForObject(serviceSql, Integer.class, oneMap.get("patient")+"");
                    oneMap.put("serviceCount", serviceCount);
                    oneMap.put("isInSession",false);
                    String sessionId = String.valueOf(oneMap.get("sessionId"));
                    JSONArray parArray = imUtill.getParticipants(sessionId);
                    parArray.forEach(
                            oneParObj -> {
                                org.json.JSONObject oneParJson = (org.json.JSONObject)oneParObj;
                                if(StringUtils.equalsIgnoreCase(oneParJson.getString("id"),dispatcher)){
                                    oneMap.put("isInSession",true);
                                }
                            }
                    );
                });
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**
     * 调度员-查询-服务人员列表(医生)
     *
     * @return
     */
    public JSONObject queryDoctorList(String patient,String hospital,String doctorName,String status, int page, int size) {
        JSONObject result = new JSONObject();
        doctorName = null == doctorName ? "" : doctorName;
        if(StringUtils.isBlank(status)) {
            status = "-100";
        }
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : size;
        //
        String sql = "SELECT " +
                "  d.code as doctor, " +
                "  d.photo as photo, " +
                "  d.name as name," +
                "  case d.sex  " +
                "  when 0 then '无' " +
                "  when 1 then '男' " +
                "  when 2 then '女' " +
                "  end as sex, " +
                "  d.`job_name` AS jobName, " +
                "  d.mobile as phone, " +
                "  IFNULL(ds.`status`,5) as status," +
                "  1 as sortFlag ,count(o.id) as count" +
                " FROM " +
                " wlyy_doctor d " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor LEFT JOIN wlyy_door_service_order o on o.doctor = d.code and o.`status` in (2,3,4) " +
                " WHERE d.status = 1" +
                " AND d.level <> 11" +
                " AND d.hospital = '{hospital}' " +
                " AND d.`name` like '%{doctorName}%' " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')" +
                " AND d.del=1  " +
                " GROUP BY d.`code` ORDER BY ds.create_time DESC " +
                " LIMIT {start},{end}";
        String finalSql = sql.replace("{hospital}", hospital)
                .replace("{doctorName}", doctorName)
                .replace("{status}", String.valueOf(status))
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "SELECT  " +
                "   count(d.id)  " +
                " FROM  " +
                "   wlyy_doctor d  " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor " +
                " WHERE d.status = 1" +
                " AND d.level <> 4" +
                " AND d.hospital = '{hospital}' "+
                " AND d.`name` like '%{doctorName}%' " +
                " AND d.del=1 and d.status=1 " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')";
        String finalCountSql = countSql.replace("{hospital}", hospital)
                .replace("{doctorName}", doctorName)
                .replace("{status}", String.valueOf(status));
        List<Map<String,Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            if (sqlResultlist!=null&&sqlResultlist.size()!=0){
                for (Map<String,Object> map:sqlResultlist){
/*                    BaseDoctorDO doctor = doctorDao.findById(map.get("doctor").toString());
                    BaseOrgDO hospital1 = hospitalDao.findByCode(doctor.getHospital());
                    if (doctor.getPosition()==null||doctor.getPosition()==""){
                        map.put("position",hospital1.getPosition());
                    }else {
                        map.put("position",doctor.getPosition());
                    }*/
                    map.put("position","117.13,36.18");
                }
            }
            logger.info("服务医生人员sql:"+finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询 服务医生人员 列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finalCountSql, Integer.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计  服务医生人员 数量失败:" + e.getMessage());
            return result;
        }
        //添加未完成服务工单列表
        for(Map<String,Object> map : sqlResultlist){
            String doctor = map.get("doctor") + "";
            Long notFinish = (Long) map.get("count");
            if(notFinish > 0 && StringUtils.isNotBlank(doctor)){
                String notFinishSql ="select o.id,o.number,o.patient,o.patient_name,o.patient_phone,o.patient_expected_serve_time,o.`status`, CASE p.sex when 1 then '男' when 2 THEN '女' END as sex,p.idcard, " +
                        "year(now()) - ((CASE LENGTH(p.idcard) WHEN 18 THEN substring(p.idcard, 7, 4) WHEN 15 THEN CONCAT('19',substring(p.idcard, 7, 2)) END )) as age , p.photo,o.serve_lat AS lat,o.serve_lon AS lon,o.id AS orderId " +
                        "from wlyy_door_service_order o LEFT JOIN wlyy_patient p on o.patient = p.`code` and p.`status`=1 " +
                        "where o.doctor ='"+doctor + "' and o.status in (2,3,4)";
                List<Map<String, Object>> notFinishList = jdbcTemplate.queryForList(notFinishSql);
                map.put("notFinishList", notFinishList);
            }
        }
        // 居民端第一页置顶家庭医生
/*        if(!StringUtils.isEmpty(patient) && page == 1){
            SignFamily signFamily = signFamilyDao.findByPatient(patient);
            if(null != signFamily){
                String signDoctor = signFamily.getDoctor();
                String signDoctorName = signFamily.getDoctorName();
                //判断当前居民是否有家庭医生
                boolean doctorExist = wlyyDoorDoctorStatusDao.existsByDoctorAndStatusIn(signDoctor,new Integer[]{1,2,3,4});
                if(doctorExist){
                    boolean bool = false;
                    Map<String,Object> signDoctorMap = new HashMap<>();
                    for(Map<String,Object> oneDoctorMap : sqlResultlist){
                        bool = oneDoctorMap.containsValue(signDoctor);
                        if(bool){
                            oneDoctorMap.put("sortFlag",0L);
                            oneDoctorMap.put("isSignDoctor",true);
                            break;
                        }
                    }
                    if(!bool){
                        //查出家签医生置顶
                        String signDocSql="SELECT " +
                                " d. CODE AS doctor, " +
                                " d.photo AS photo, " +
                                " d. NAME AS name, " +
                                " CASE d.sex " +
                                "WHEN 0 THEN " +
                                " '无' " +
                                "WHEN 1 THEN " +
                                " '男' " +
                                "WHEN 2 THEN " +
                                " '女' " +
                                "END AS sex, " +
                                " d.`job_name` AS jobName, " +
                                " d.mobile AS phone, " +
                                " IFNULL(ds.`status`, 5) AS STATUS, " +
                                " 0 AS sortFlag, " +
                                " count(o.id) AS count " +
                                "FROM " +
                                " wlyy_doctor d " +
                                "LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor " +
                                "LEFT JOIN wlyy_door_service_order o ON o.doctor = d. CODE " +
                                "AND o.`status` IN (2, 3, 4) " +
                                "WHERE " +
                                " d. STATUS = 1 AND d.hospital = '" + hospital + "'" +
                                " and d.name like '%"+doctorName+"%'" +
                                "AND d.`code` = '" + signDoctor + "'";
                        sqlResultlist.addAll(jdbcTemplate.queryForList(signDocSql));
//                        count += 1;
                    }
                    sqlResultlist.sort(comparing((doctor) -> Integer.parseInt(doctor.get("sortFlag").toString())));
                }
            }
        }*/
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**
     * 调度员-查询-服务人员列表(医生-可接单状态的)
     *
     * @return
     */
    public JSONObject queryDoctorListWithNotStopped(String patient,String hospital,int page, int size) {
        JSONObject result = new JSONObject();
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "select ds.doctor,d.name, d.job_name as jobName, 1 as sortFlag " +
                " from wlyy_door_doctor_status ds " +
                "        JOIN (select * from wlyy_doctor where hospital = '" + hospital + "')  d on ds.doctor = d.code " +
                " where ds.status in (1,2,3,4)" +
                " limit " + start + "," + end ;
        String countSql = "select count(ds.id) " +
                "from wlyy_door_doctor_status ds " +
                "         JOIN (select * from wlyy_doctor where hospital = '" + hospital + "') d on ds.doctor = d.code " +
                "where ds.status in (1,2,3,4)";
        List<Map<String,Object>> doctorList = new ArrayList<>();
        try {
            doctorList = jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
            String failMsg = "从数据库查询 可接单状态的服务医生人员 列表信息失败:" + e.getMessage();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg );
            logger.error(failMsg);
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql,Integer.class);
        } catch (Exception e) {
            String failMsg = "从数据库统计  可接单状态的服务医生人员 数量失败:" + e.getMessage();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
/*        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if(null != signFamily){
            String signDoctor = signFamily.getDoctor();
            String signDoctorName = signFamily.getDoctorName();
            //判断当前居民是否有家庭医生
            boolean doctorExist = wlyyDoorDoctorStatusDao.existsByDoctorAndStatusIn(signDoctor,new Integer[]{1,2,3,4});
            if(doctorExist){
                // 获取签约医生职称
                String querySignJobSql = "select ifnull(job_name,'no_job') from wlyy_doctor where code = '"+ signDoctor + "'";
                String signDoctorJobName = jdbcTemplate.queryForObject(querySignJobSql,String.class);
                if(StringUtils.equalsIgnoreCase("no_job",signDoctorJobName)){
                    String failMsg = "当前居民的签约医生没有职称,signDoctor = " + signDoctor;
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return result;
                }
                Map<String,Object> signDoctorMap = new HashMap<>();
                signDoctorMap.put("doctor",signDoctor);
                signDoctorMap.put("jobName",signDoctorJobName);
                signDoctorMap.put("name",signFamily.getDoctorName());
                signDoctorMap.put("sortFlag",1L);
                int signDoctorIndex = doctorList.indexOf(signDoctorMap);
                if(signDoctorIndex != -1){
                    Map<String,Object> originalSignDoctorMap = doctorList.get(signDoctorIndex);
                    originalSignDoctorMap.put("isSignDoctor",true);
                    originalSignDoctorMap.put("sortFlag",0L);
                }else{
                    // 表示新增了一个
                    signDoctorMap.put("name",signDoctorName);
                    signDoctorMap.put("isSignDoctor",true);
                    signDoctorMap.put("sortFlag",0L);
                    doctorList.add(signDoctorMap);
                    count += 1;
                }
                doctorList.sort(comparing((doctor) -> Integer.parseInt(doctor.get("sortFlag").toString())));
            }
        }*/
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, doctorList);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
    /**
     * 调度员(系统)给医生派单
     *
     * @param orderId
     * @param doctor
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject sendOrderToDoctor(String orderId,String remark,String dispatcher,String dispathcherName,String doctor,String doctorName,String doctorJobName){
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if(null == doorServiceOrderDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单不存在,id:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorStatusDO doorDoctorStatusDO = wlyyDoorDoctorStatusDao.queryByDoctorAndStatusIn(doctor,new Integer[]{WlyyDoorDoctorStatusDO.Status.waitForSend.getType(),
                WlyyDoorDoctorStatusDO.Status.waitForAccept.getType(),
                WlyyDoorDoctorStatusDO.Status.waitForServe.getType(),
                WlyyDoorDoctorStatusDO.Status.serving.getType(),
        });
        if(null == doorDoctorStatusDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前派单的医生不存在或禁止接单,doctor:" + doctor;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        doorServiceOrderDO.setRemark(remark);
        doorServiceOrderDO.setDoctor(doctor);
        doorServiceOrderDO.setDoctorName(doctorName);
        doorServiceOrderDO.setDoctorType(doctorJobName);
        doorServiceOrderDO.setStatus(WlyyDoorDoctorStatusDO.Status.waitForAccept.getType());
        doorServiceOrderDO.setUpdateUser(dispatcher);
        doorServiceOrderDO.setUpdateUserName(dispathcherName);
        doorServiceOrderDO.setDispatcherResponseTime(new Date());
        this.save(doorServiceOrderDO);
        // 给医生发派单消息
        if(WlyyDoorServiceOrderDO.IsTransOtherOrg.yes.getType().equals(doorServiceOrderDO.getIsTransOtherOrg())){
            this.createMessage(orderId,doorServiceOrderDO.getTransedDispatcher(),doctor,407,"服务工单待接单","您有新的服务工单,请前往处理");
        }else{
            this.createMessage(orderId,doorServiceOrderDO.getDispatcher(),doctor,407,"服务工单待接单","您有新的服务工单,请前往处理");
        }
        //发送智能助手消息
        sendWeixinMessage(4,doctor,doorServiceOrderDO.getPatient());
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipant(sessionId,doctor,null);
        // 调度员处理完该单(新增预约的,或者是拒单重新派单的)
/*        List<Message> messages = messageDao.queryByRelationCodeAndTypeIn(orderId,new Integer[]{402,404,430,435});
        if(CollectionUtils.isEmpty(messages)){
            logger.error("当前工单没有 居民新增预约 消息!!orderId:" + orderId);
        }else{
            // 设置消息处理完毕
            messages.forEach(
                    message -> {
                        String title = "调度员派单(派给本社区医生)";
                        if("system".equals(dispatcher)){
                            title = "系统派单(派给服务医生)";
                        }
                        if (message.getType() == 430) {
                            message.setTitle(title);
                            message.setContent(doorServiceOrderDO.getDispatcherName() + "已将服务工单" + doorServiceOrderDO.getNumber() + "指派给" + doctorName + "医生");
                            message.setType(431);
                            message.setReceiver(dispatcher);
                            message.setSender(dispatcher);
                            message.setCreateTime(new Date());
                        }else{
                            message.setOver("0");
                        }
                        messageDao.save(message);
                    }
            );
        }*/
        // 工单状态变更记录
        WlyyDoorProcessLogDO processLogDO = new WlyyDoorProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(WlyyDoorServiceOrderDO.Status.waitForAccept.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispathcherName);
        processLogDO.setCreateTime(new Date());
        wlyyDoorProcessLogDao.save(processLogDO);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, doorServiceOrderDO);
        // 发送IM消息通知患者医生已派单
        String noticeContent = "已分派"+doorServiceOrderDO.getDoctorName()+"医生为您服务,请耐心等待医生接单";
        this.qucikSendIM(doorServiceOrderDO.getId(), doorServiceOrderDO.getDispatcher(), "智能助手","1", noticeContent);
        return result;
    }
    /**
     * 医生给医生派单
     *
     * @param orderId
     * @param doctor
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject transferOrder(String orderId,String remark,String dispatcher,String dispathcherName,String doctor,String doctorName,String doctorJobName){
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if(null == doorServiceOrderDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单不存在,id:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorDoctorStatusDO doorDoctorStatusDO = wlyyDoorDoctorStatusDao.queryByDoctorAndStatusIn(doctor,new Integer[]{WlyyDoorDoctorStatusDO.Status.waitForSend.getType(),
                WlyyDoorDoctorStatusDO.Status.waitForAccept.getType(),
                WlyyDoorDoctorStatusDO.Status.waitForServe.getType(),
                WlyyDoorDoctorStatusDO.Status.serving.getType(),
        });
        if(null == doorDoctorStatusDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前转派单的医生不存在或禁止接单,doctor:" + doctor;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        doorServiceOrderDO.setRemark(remark);
        doorServiceOrderDO.setDoctor(doctor);
        doorServiceOrderDO.setDoctorName(doctorName);
        doorServiceOrderDO.setDoctorType(doctorJobName);
        doorServiceOrderDO.setStatus(WlyyDoorDoctorStatusDO.Status.waitForAccept.getType());
        doorServiceOrderDO.setUpdateUser(dispatcher);
        doorServiceOrderDO.setUpdateUserName(dispathcherName);
        doorServiceOrderDO.setDispatcherResponseTime(new Date());
        this.save(doorServiceOrderDO);
        // 给医生发派单消息
        if(doorServiceOrderDO.getIsTransOtherOrg().equals(WlyyDoorServiceOrderDO.IsTransOtherOrg.yes.getType())){
            this.createMessage(orderId,doorServiceOrderDO.getTransedDispatcher(),doctor,407,"服务工单待接单","您有新的服务工单,请前往处理");
        }else{
            this.createMessage(orderId,doorServiceOrderDO.getDispatcher(),doctor,407,"服务工单待接单","您有新的服务工单,请前往处理");
        }
        //发送智能助手消息
        sendWeixinMessage(4,doctor,doorServiceOrderDO.getPatient());
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipant(sessionId,doctor,null);
        // 调度员处理完该单(新增预约的,或者是拒单重新派单的)
/*        List<Message> messages = messageDao.queryByRelationCodeAndTypeIn(orderId,new Integer[]{402,404,430,435});
        if(CollectionUtils.isEmpty(messages)){
            logger.error("当前工单没有 居民新增预约 消息!!orderId:" + orderId);
        }else{
            // 设置消息处理完毕
            messages.forEach(
                    message -> {
                        if (message.getType() == 430) {
                            message.setTitle("医生转派单(派给本社区医生)");
                            message.setContent(doorServiceOrderDO.getDispatcherName() + "已将服务工单" + doorServiceOrderDO.getNumber() + "转派给" + doctorName + "医生");
                            message.setType(431);
                            message.setReceiver(dispatcher);
                            message.setSender(dispatcher);
                            message.setCreateTime(new Date());
                        }else{
                            message.setOver("0");
                        }
                        messageDao.save(message);
                    }
            );
        }*/
        // 工单状态变更记录
        WlyyDoorProcessLogDO processLogDO = new WlyyDoorProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(WlyyDoorServiceOrderDO.Status.waitForAccept.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispathcherName);
        processLogDO.setCreateTime(new Date());
        wlyyDoorProcessLogDao.save(processLogDO);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, doorServiceOrderDO);
        // 发送IM消息通知患者医生已派单
        String noticeContent = "已转派"+doorServiceOrderDO.getDoctorName()+"医生为您服务,请耐心等待医生接单";
        this.qucikSendIM(doorServiceOrderDO.getId(), dispatcher, "智能助手","1", noticeContent);
        return result;
    }
    /**
     * 调度员将工单转给其他机构
     * 1、工单记录转接机构
     * 2、工单转接日志
     *
     * @param orderId
     * @param hospital
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject transOrderToOtherOrg(String orderId,String hospital){
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        if(null == doorServiceOrderDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单不存在,id:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        String transDispatcherInfoSql = "select code,name,hospital_name from wlyy_doctor where hospital = '" + hospital + "' and `level` = 11";
        List<Map<String,Object>>  transDispatcherInfoList = jdbcTemplate.queryForList(transDispatcherInfoSql);
        if(CollectionUtils.isEmpty(transDispatcherInfoList)){
            String failMsg = "当前转接机构[" + hospital + "]暂无调度员,转接失败!";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        // 工单转接
        Map<String,Object> infoMap = transDispatcherInfoList.get(0);
        String transDispatcher = String.valueOf(infoMap.get("code"));
        String transDispatcherName = String.valueOf(infoMap.get("name"));
        doorServiceOrderDO.setIsTransOtherOrg(WlyyDoorServiceOrderDO.IsTransOtherOrg.yes.getType());
        doorServiceOrderDO.setTransedOrgCode(hospital);
        doorServiceOrderDO.setTransedDispatcher(transDispatcher);
        doorServiceOrderDO.setTransedDispatcherName(transDispatcherName);
        this.save(doorServiceOrderDO);
        // 转接日志
        WlyyDoorTransRecordDO transRecordDO = new WlyyDoorTransRecordDO();
        transRecordDO.setDispatcher(doorServiceOrderDO.getDispatcher());
        transRecordDO.setDispatcherName(doorServiceOrderDO.getDispatcherName());
        transRecordDO.setOrderId(orderId);
        transRecordDO.setTransedOrgCode(hospital);
        transRecordDO.setTransedDispatcher(transDispatcher);
        transRecordDO.setTransedDispatcherName(transDispatcherName);
        wlyyDoorTransRecordDao.save(transRecordDO);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, doorServiceOrderDO);
        return result;
    }
    /**
     * 添加【工单派单,转单】等系统消息
     * @param orderId
     * @param sender
     * @param receiver
     * @param Content
     */
    public void createMessage(String orderId,String sender,String receiver,int type,String title,String Content){
/*        Message message=new Message();
        message.setCzrq(new Date());
        message.setCreateTime(new Date());
        message.setRead(1);
        message.setState(1);
        message.setRelationCode(orderId);
        message.setOver("1");
        message.setReceiver(receiver);
        message.setSender(sender);
        message.setCode(getCode());
        message.setTitle(title);
        message.setContent(Content);
        //消息类型:401为资质申请审核
        message.setType(type);
        message.setDel("1");
        messageDao.save(message);*/
    }
    /**
     * 【调度员,医生】快速发送IM消息
     * @param orderId
     * @param sendId
     * @param sendName
     * @param content
     * @return
     */
    public int qucikSendIM(String orderId,String sendId,String sendName,String contentType,String content) {
        int result = -1;
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        if (null == consult) {
            logger.error("当前工单未关联咨询,工单id:" + orderId);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = null;
        String response = null;
        if(StringUtils.isBlank(sendId)){
            wlyyDoorServiceOrder  = wlyyDoorServiceOrderDao.findOne(orderId);
            String sender = "system";
            if(StringUtils.isNoneBlank(wlyyDoorServiceOrder.getDispatcher())){
                sender = wlyyDoorServiceOrder.getDispatcher();
            }
            response = imUtill.sendTopicIM(sender, "智能助手", consult.getId(), contentType, content, null);
        }else{
            response = imUtill.sendTopicIM(sendId, sendName, consult.getId(), contentType, content, null);
        }
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getIntValue("status") == -1) {
            logger.error("上门服务工单消息发送失败:" + resObj.getString("message"));
            return result;
        }
        result = 1;
        return result;
    }
    /**
     * 判断消息订单是否已被取消
     * @param messageId
     * @return
     */
    public JSONObject orderIsCancel(String messageId) {
        JSONObject result = new JSONObject();
        String sql = "SELECT m.* FROM `wlyy_message` m LEFT JOIN wlyy_door_service_order o on m.relation_code=o.id " +
                "where  o.status = -1 and m.id='" + messageId + "'";
        List<Map<String, Object>> messageList = jdbcTemplate.queryForList(sql);
        if(messageList.size() == 0){
            //订单没有被取消
            result.put(ResponseContant.resultMsg, true);
        }else {
            //订单已经被取消
            result.put(ResponseContant.resultMsg, false);
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
    }
    /**
     * 判断是否跳过登记服务小结
     * @param orderId
     */
    public void cancelConclusion(String orderId) {
        wlyyDoorServiceOrderDao.updateConclusionStatus(orderId);
    }
    /**
     * 更新订单居民确认状态
     * @param orderId
     * @param isPatientConfirm
     */
    public void updateIsPatientConfirm(String orderId, Integer isPatientConfirm) {
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findOne(orderId);
        wlyyDoorServiceOrder.setIsPatientConfirm(isPatientConfirm);
        wlyyDoorServiceOrder.setPatientConfirmTime(new Date());
        this.save(wlyyDoorServiceOrder);
    }
    /**
     * 更新处方状态跟记录
     * @param orderId
     * @param prescriptionCode 手动输入处方code,多个用逗号隔开
     * @param commitPrescriptionCode
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject createPrescription(String orderId, String prescriptionCode, String commitPrescriptionCode) {
        JSONObject res = new JSONObject();
        //上门后在线开方,手动关联处方号的话更新处方单号跟状态
        if(StringUtils.isNotBlank(commitPrescriptionCode)){
            WlyyDoorPrescriptionDO prescription =  doorPrescriptionDao.findByCode(commitPrescriptionCode);
            prescription.setStatus(1);
            prescription.setRecipeNo(prescriptionCode);
            prescription.setUpdateTime(new Date());
            doorPrescriptionDao.save(prescription);
        }else {
            //判断手动输入的处方号是否被关联过
            String[] recipeNoString = prescriptionCode.split(",");
            for (int i = 0; i < recipeNoString.length; i++) {
                //判断是否被工单手工关联过
                List<WlyyDoorServiceOrderDO> orderDOList = wlyyDoorServiceOrderDao.findByPrescriptionCode("%" + recipeNoString[i] + "%");
                WlyyDoorPrescriptionDO prescriptionDO = doorPrescriptionDao.findByRecipeNo(recipeNoString[i]);
                if(orderDOList.size() > 0 || prescriptionDO != null){
                    res.put("status", -1);
                    res.put("msg", "处方号:" + recipeNoString[i] + "已被关联过,请重新输入");
                    return res;
                }
            }
            //上门前手动开方即更新工单的处方号
            wlyyDoorServiceOrderDao.updatePrescriptionById(orderId, prescriptionCode, new Date());
            WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(orderId);
            //非代预约才发送im消息
            if(orderDO.getType() != null && orderDO.getType() != 3) {
                //发送 预约卡片信息(2101类型)
                JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
                orderInfoContent.put("re_msg_type", 2);//开方完成消息
                this.qucikSendIM(orderDO.getId(), orderDO.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
            }
        }
        res.put("status", 200);
        return res;
    }
    /**
     *  更新医生地理位置状态
     *
     * @param doctor
     * @param positionStatus
     * @param position
     */
    public void updateDoctorStatus(String doctor,Integer positionStatus,String position){
/*        Doctor doctor1 = doctorDao.findByCode(doctor);
        Hospital hospital = hospitalDao.findByCode(doctor1.getHospital());
        if (positionStatus == 0){
            doctor1.setPosition(hospital.getPosition());
        }else {
            doctor1.setPosition(position);
        }
        doctorDao.save(doctor1);*/
    }
    /**
     * 获取上门服务代预约对象列表
     * @param teamCode
     * @param doctor
     * @param patientName
     * @param page
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> getDoorPatientList(String teamCode, String doctor, String patientName, Integer page, Integer pageSize) {
        int start = 0 == page ? page++ : (page - 1) * pageSize;
        int end = 0 == pageSize ? 10 : pageSize;
        String sql = "select DISTINCT patient,name,openid,idcard,mobile,town,townName,address from (SELECT s.patient,s.`name`,s.openid,s.idcard, s.mobile,h.town,h.town_name townName, p.address,a.create_time createTime from wlyy_sign_family s, wlyy_door_service_application a ,dm_hospital h,wlyy_patient p " +
                "WHERE s.admin_team_code = " + teamCode + " AND ( s.doctor = '" + doctor + "' OR s.doctor_health = '" + doctor + "') and s.`status`= 1 and s.expenses_status=1 and a.`status` =2 " +
                "and s.patient = a.patient and s.hospital = h.code and s.patient = p.code and p.status = 1 and (p.archive_status is null or p.archive_status != 2) ";
        if(StringUtils.isNotBlank(patientName)){
            sql += "and s.`name` LIKE '%" + patientName + "%' ";
        }
        sql += " union SELECT s.patient,s.`name`,s.openid,s.idcard, s.mobile,h.town,h.town_name townName, p.address,r.create_time createTime from wlyy_sign_family s, wlyy_door_service_order r ,dm_hospital h,wlyy_patient p " +
        "WHERE s.admin_team_code = " + teamCode + " AND ( s.doctor = '" + doctor + "' OR s.doctor_health = '" + doctor + "') and s.`status`= 1 and s.expenses_status=1 and s.doctor = '" + doctor + "' " +
                "and r.patient = s.patient and s.hospital = h.code and s.patient = p.code and p.status = 1 and (p.archive_status is null or p.archive_status != 2) ";
        if(StringUtils.isNotBlank(patientName)){
            sql += "and s.`name` LIKE '%" + patientName + "%' ";
        }
        sql += " ) tmp ";
        sql += "ORDER BY createTime desc limit " + start + ", " + end;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        for(Map<String, Object> map : list){
            //获取年龄跟性别
            String idcard = map.get("idcard") + "";
            //上门服务待预约对象。如果有已完成的服务工单,n那么就取上一次的服务签到地址
            String sql1 = "SELECT * FROM wlyy_door_service_order WHERE patient = '"+map.get("patient")+"' AND status = 6 ORDER BY doctor_sign_time DESC LIMIT 1";
            List<WlyyDoorServiceOrderDO> orderDOList = jdbcTemplate.query(sql1,new BeanPropertyRowMapper<>(WlyyDoorServiceOrderDO.class));
            if (orderDOList.size()>0){
                map.put("address",orderDOList.get(0).getServeAddress());
            }
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
            map.put("sex", IdCardUtil.getSexForIdcard_new(idcard));
        }
        return list;
    }
    @Transactional
    public JSONObject proxyCreate(String jsonData,String doctorCode) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        //资质处理 .医生填写资质信息后,生成一个已通过审核的资质
        try{
            if(jsonObjectParam.get("doorServiceApplication")!=null){
                doorServiceApplicationService.create("2",jsonObjectParam.get("doorServiceApplication").toString(),doctorCode);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        WlyyDoorServiceOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getProxyPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前代理对象code为空,请联系管理员检查参数!proxyPatient = " + orderDO.getProxyPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        //判断工单是否已存在,新建或者编辑
        if(StringUtils.isBlank(orderDO.getId())) {
/*            SignFamily signFamily = signFamilyDao.findSignFamilyByPatient(orderDO.getPatient());
            if (signFamily == null) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "当前服务对象未完成家庭医生签约,请完成签约后再预约上门服务!";
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return result;
            }*/
            //已取消的订单也可以申请
            boolean bool = wlyyDoorServiceOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                    new Integer[]{WlyyDoorServiceOrderDO.Status.waitForAccept.getType(),
                            WlyyDoorServiceOrderDO.Status.waitForServe.getType(),
                            WlyyDoorServiceOrderDO.Status.accept.getType(),
                            WlyyDoorServiceOrderDO.Status.waitForSend.getType()
                    });
            if(bool){
                String failMsg = "当前服务对象存在未完成的上门服务,请先完成该服务!";
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return result;
            }
            orderDO.setNumber(getRandomIntStr());
            orderDO.setHospital(jsonObjectParam.getJSONObject("hospital").get("code").toString());
            orderDO.setCreateTime(new Date());
            orderDO.setCreateUser(orderDO.getProxyPatient());
            orderDO.setCreateUserName(orderDO.getProxyPatientName());
        }else {
            WlyyDoorServiceOrderDO serviceOrderDO = wlyyDoorServiceOrderDao.findOne(orderDO.getId());
            // 删除出诊医生或服务项
            Boolean b = this.orderWithFeeDelete(jsonObjectParam, serviceOrderDO);
            if(b){
                String failMsg = "删除服务项失败!";
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg, failMsg);
                return result;
            }
            //更新重新派单操作状态
//            messageDao.updateByReceiverAndRelationCode(serviceOrderDO.getProxyPatient(), orderDO.getId(), 403);
            orderDO.setNumber(serviceOrderDO.getNumber());
            orderDO.setHospital(serviceOrderDO.getHospital());
            orderDO.setUpdateTime(new Date());
            orderDO.setUpdateUser(orderDO.getProxyPatient());
            orderDO.setUpdateUserName(orderDO.getProxyPatientName());
        }
        orderDO.setStatus(2);
        orderDO.setType(3);
        orderDO.setDispatcherResponseTime(new Date());
        this.save(orderDO);
        result.put("orderId",orderDO.getId());
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO)) {return result;}
        if("1".equals(orderDO.getShortcutType())){
            //快捷的当前医生直接接单
            try{
                String sql = "SELECT d.job_title_code,d.job_title_name,o.org_level from base_doctor d,base_doctor_hospital h,base_org o " +
                        "WHERE d.id = h.doctor_code and h.org_code = o.id";
                sql += " and d.id = '"+orderDO.getDoctor()+"'";
                List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
/*                BaseDoctorDO doctor = doctorDao.findById(orderDO.getDoctor());
                Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
                doorOrderService.acceptOrder1(orderDO.getId(), doctor.getJob(), doctor.getJobName(), hospital.getLevel());*/
                doorOrderService.acceptOrder1(orderDO.getId(), list.get(0).get("job_title_code").toString(),
                        list.get(0).get("job_title_name").toString(), Integer.valueOf(list.get(0).get("org_level").toString()));
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            // 给服务医生发接单消息
            this.createMessage(orderDO.getId(),orderDO.getProxyPatient(),orderDO.getDoctor(),407,"服务工单待接单","您有新的服务工单,请前往处理");
            //发送智能助手消息
            sendWeixinMessage(4,orderDO.getDoctor(),orderDO.getPatient());
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
    }
    @Transactional
    public JSONObject proxyUpdate(String jsonData,String doctorCode) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getId())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象id为空,请联系管理员检查参数!id = " + orderDO.getId();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if(StringUtils.isEmpty(orderDO.getProxyPatient())){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前代理对象code为空,请联系管理员检查参数!proxyPatient = " + orderDO.getProxyPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO serviceOrderDO = wlyyDoorServiceOrderDao.findOne(orderDO.getId());
        // 删除出诊医生或服务项
        Boolean b = this.orderWithFeeDelete(jsonObjectParam, serviceOrderDO);
        if(b){
            String failMsg = "删除服务项失败!";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        //更新重新派单操作状态
//        messageDao.updateByReceiverAndRelationCode(serviceOrderDO.getProxyPatient(), orderDO.getId(), 403);
        orderDO.setNumber(serviceOrderDO.getNumber());
        orderDO.setHospital(serviceOrderDO.getHospital());
        orderDO.setUpdateTime(new Date());
        orderDO.setUpdateUser(orderDO.getProxyPatient());
        orderDO.setUpdateUserName(orderDO.getProxyPatientName());
        orderDO.setStatus(2);
        orderDO.setType(serviceOrderDO.getType());
        orderDO.setDispatcherResponseTime(new Date());
        this.save(orderDO);
        result.put("orderId",orderDO.getId());
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO)){
            return result;
        }
        if(!orderDO.getDoctor().equals(serviceOrderDO.getDoctor())){
            //服务医生修改,直接转派
            BaseDoctorDO doctor = doctorDao.findById(doctorCode);
            BaseDoctorDO transDoctor = doctorDao.findById(orderDO.getDoctor());
            transferOrder(orderDO.getId(),null,doctor.getId(),doctor.getName(),transDoctor.getId(),transDoctor.getName(),transDoctor.getJobTitleName());
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
    }
    public List<Map<String,Object>> getProxyPatientList(String patient) {
        //根据代理人code查代理预约对象
        String sql = "SELECT o.patient,o.patient_name,o.patient_relation,p.photo, IFNULL(m.family_relation, -1) family_relation FROM `wlyy_door_service_order` o LEFT JOIN wlyy_patient_family_member m " +
                "on o.proxy_patient = m.patient and o.patient = m.family_member  JOIN wlyy_patient p on p.`code` = o.patient and p.`status` = 1 " +
                "where o.proxy_patient = '" + patient + "'  and o.type != 3 " +
                " GROUP BY o.patient ORDER BY family_relation ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    public List<WlyyDoorServiceOrderDO> selectRelationCode(String relationCode){
        return wlyyDoorServiceOrderDao.findByRelationCode(relationCode);
    }
    /**
     * 医生更新上门信息
     *
     * 预计到达:2019-01-01   09:00
     * 服务医生:张三(全科医生)、王五(健管师)
     *
     * {
     *     "orderId":"",
     *     "doctorArrivingTime":"",
     *     "doctorArr":[
     *         {
     *              "doctor":"",
     *              "doctorName":"",
     *              "doctorLevel":3,
     *              "doctorJobCode":"",
     *              "doctorJobName":"",
     *         }
     *     ],
     *     "deleteDoctorArr":[
     *          {
     *              "id":""
     *          },
     *          {
     *              "id":""
     *          }
     *     ]
     * }
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateDoctorInfoNoPatient(String jsonData){
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findOne(jsonObjectParam.getString("orderId"));
        if(!StringUtils.isEmpty(jsonObjectParam.getString("doctorArrivingTime"))) {
            wlyyDoorServiceOrder.setDoctorArrivingTime(jsonObjectParam.getString("doctorArrivingTime"));
        }
//        //添加居民同意状态
//        wlyyDoorServiceOrder.setIsPatientConfirm(1);
//        wlyyDoorServiceOrder.setPatientConfirmTime(new Date());
//        wlyyDoorServiceOrder.setUpdateTime(new Date());
//        this.save(wlyyDoorServiceOrder);
//
//        //修改时有更改到关联关系,则先删除原有关联关系,再新增关联关系
//        //删除工单原来医生的关联关系
//        // 删除出诊医生或服务项
//        this.orderWithFeeDelete(jsonObjectParam,wlyyDoorServiceOrder);
        //新增工单医生关联关系
        if (orderWithDoctorAdd(result, jsonObjectParam, wlyyDoorServiceOrder)) {return result;}
//        //新增工单居民确认操作日志记录
//        if (orderWithConfirmLogAdd(result, jsonObjectParam, wlyyDoorServiceOrder.getId())) {return result;}
        //微信模板消息-反馈处理通知
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(),30,);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        return result;
    }
}

+ 165 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/WlyyDoorTransRecordService.java

@ -0,0 +1,165 @@
package com.yihu.jw.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorTransRecordDao;
import com.yihu.jw.entity.door.WlyyDoorTransRecordDO;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
 * 服务工单转接给其他结构的转接记录服务service
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * Administrator    1.0  2019年03月20日 Created
 *
 * </pre>
 * @since 1.
 */
@Service
public class WlyyDoorTransRecordService extends BaseJpaService<WlyyDoorTransRecordDO, WlyyDoorTransRecordDao> {
    private Logger logger = LoggerFactory.getLogger(WlyyDoorTransRecordService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //服务工单转接给其他结构的转接记录服务基本信息
    private WlyyDoorTransRecordDO jsonToWlyyDoorTransRecord(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        WlyyDoorTransRecordDO wlyyDoorTransRecord;
        try {
            wlyyDoorTransRecord = EntityUtils.jsonToEntity(jsonObjectParam.get("wlyyDoorTransRecord").toString(), WlyyDoorTransRecordDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "服务工单转接给其他结构的转接记录服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return new WlyyDoorTransRecordDO();
        }
        this.save(wlyyDoorTransRecord);
        return wlyyDoorTransRecord;
    }
    /**
     * 创建服务工单转接给其他结构的转接记录
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorTransRecordDO wlyyDoorTransRecord = new WlyyDoorTransRecordDO();
        wlyyDoorTransRecord = jsonToWlyyDoorTransRecord(result, jsonObjectParam, jsonData);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorTransRecord);
        return result;
    }
    /**
     * 服务工单转接给其他结构的转接记录(包括角色分配的菜单,模块等)
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(String jsonData) {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorTransRecordDO wlyyDoorTransRecord = new WlyyDoorTransRecordDO();
        wlyyDoorTransRecord = jsonToWlyyDoorTransRecord(result, jsonObjectParam, jsonData);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorTransRecord);
        return result;
    }
    /**
     * 查询服务工单转接给其他结构的转接记录列表
     *
     * @return
     */
    public JSONObject queryInfoList(String fields, String filters, String sorts, Integer status, int page, int size) {
        JSONObject result = new JSONObject();
        status = null == status ? -1 : status;
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : page * size;
        String sql = "";
        String finalSql = sql.replace("{fields}", fields)
                .replace("{status}", status.toString())
                .replace("{start}", String.valueOf(start))
                .replace("{end}", String.valueOf(end));
        String countSql = "";
        String finqlCountSql = countSql.replace("{filters}", filters)
                .replace("{status}", status.toString())
                .replace("{start}", String.valueOf(start));
        List<WlyyDoorTransRecordDO> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.query(finalSql, new BeanPropertyRowMapper<>(WlyyDoorTransRecordDO.class));
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库服务工单转接给其他结构的转接记录列表信息失败:" + e.getMessage());
            return result;
        }
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finqlCountSql, Integer.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计服务工单转接给其他结构的转接记录数量失败:" + e.getMessage());
            return result;
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
        countItem.put("count", count);
        result.putAll(countItem);
        return result;
    }
}

+ 121 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/common/HospitalService.java

@ -0,0 +1,121 @@
package com.yihu.jw.door.service.common;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.org.dao.BaseOrgDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2020/12/25.
 */
@Service
public class HospitalService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseOrgDao baseOrgDao;
    public List<Map<String, Object>> getDoctorsByhospitalNoPage(String hospital, String name, Integer type, Integer times) throws Exception {
        BaseOrgDO h = baseOrgDao.findByCode(hospital);
        Integer level = 1;
        if(h != null && h.getOrgLevel()!=null) {
            level = h.getOrgLevel();
        }else {
            throw new Exception("未获取到机构等级");
        }
        String sql = "";
        //服务次数是否大于12
        if (times != null && times <= 12) {
            sql = "select d.*,j.fee_level_" + level + " - j.subsidy as fee  from wlyy_doctor d LEFT JOIN dm_job j on d.job = j.`code` and j.del = 1 " +
                    "where d.del=1  and d.status=1 ";
        }else {
            sql = "select d.*,j.fee_level_" + level + " as fee  from wlyy_doctor d LEFT JOIN dm_job j on d.job = j.`code` and j.del = 1 " +
                    "where d.del=1  and d.status=1 ";
        }
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNoneEmpty(hospital)) {
            sql += " and hospital =? ";
            params.add(hospital);
        }
        if (StringUtils.isNoneEmpty(name)) {
            sql += " and d.name like ? ";
            params.add("%" + name + "%");
        }
        if (type != null && type > 0) {
            sql += " and level =? ";
            params.add(type);
        }
        return jdbcTemplate.queryForList(sql, params.toArray());
    }
    /**
     * 获取机构上班时间
     * @param code
     * @return
     */
    public List<String> getWorkingTimeByPatient(String code) throws Exception {
        List<String> result = new ArrayList<>();
/*        BaseOrgDO h = baseOrgDao.findByCode(code);
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        int amCount = 0;
        //获取机构早上上班时间
        if(StringUtils.isNotBlank(h.getStartWorkingTimeAm()) && StringUtils.isNotBlank(h.getStopWorkingTimeAm())) {
            String startWorkTime = h.getStartWorkingTimeAm();
            String stopWokingTime = h.getStopWorkingTimeAm();
            Date startWokingTimeAm = DateUtil.strToDate(h.getStartWorkingTimeAm(), "HH:mm");
            Date stopWokingTimeAm = DateUtil.strToDate(h.getStopWorkingTimeAm(), "HH:mm");
            long diff = stopWokingTimeAm.getTime() - startWokingTimeAm.getTime();
            // 计算差多少分钟
            long min = diff / nm;
            amCount = (int) (min % 30 == 0 ? min / 30 : min / 30 + 1);
            for (int i = 0; i < amCount; i++) {
                //判断是否是最后一段时间
                if(amCount - i > 1) {
                    result.add(startWorkTime + "-" + DateUtil.getNextMin(startWorkTime, 30));
//                    map.put(i, startWorkTime + "-" + DateUtil.getNextMin(startWorkTime, 30));
                    startWorkTime = DateUtil.getNextMin(startWorkTime, 30);
                }else {
                    result.add(startWorkTime + "-" + stopWokingTime);
//                            map.put(i, startWorkTime + "-" + stopWokingTime);
                }
            }
        }
        //获取机构下午上班时间
        if(StringUtils.isNotBlank(h.getStartWorkingTimePm()) && StringUtils.isNotBlank(h.getStopWorkingTimePm())) {
            String startWorkTime = h.getStartWorkingTimePm();
            String stopWokingTime = h.getStopWorkingTimePm();
            Date startWokingTimePm = DateUtil.strToDate(h.getStartWorkingTimePm(), "HH:mm");
            Date stopWokingTimePm = DateUtil.strToDate(h.getStopWorkingTimePm(), "HH:mm");
            long diff = stopWokingTimePm.getTime() - startWokingTimePm.getTime();
            // 计算差多少分钟
            long min = diff  / nm;
            int pmCount = (int) (min % 30 == 0 ? min / 30 : min / 30 + 1);
            for (int i = amCount; i < amCount + pmCount; i++) {
                //判断是否是最后一段时间
                if(amCount + pmCount - i > 1) {
                    result.add(startWorkTime + "-" + DateUtil.getNextMin(startWorkTime, 30));
                    startWorkTime = DateUtil.getNextMin(startWorkTime, 30);
                }else {
                    result.add(startWorkTime + "-" + stopWokingTime);
                }
            }
        }*/
        return result;
    }
}

+ 130 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/common/ServerPackageService.java

@ -0,0 +1,130 @@
package com.yihu.jw.door.service.common;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by wzn54 on 2019/3/19.
 */
@Service
@Transactional
public class ServerPackageService  {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ServerPackageService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 根据机构code获取服务项目
     *
     * @param hospital
     * @return
     */
    public List<Map<String,Object>> selectByHospital(String hospital){
        String sql = "SELECT  *  FROM  wlyy.wlyy_server_item si  " +
                "WHERE  si.CODE IN (SELECT service_item_code FROM wlyy.wlyy_hospital_service_item hsi " +
                "WHERE (hsi.hospital IN ( SELECT hp.hospital_partner FROM wlyy.wlyy_hospital_partner hp " +
                "WHERE  hp.hospital ='"+hospital+"' AND hp.del = 1 ) OR hsi.hospital = '"+hospital+"') " +
                "AND hsi.del = 1 )";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    /**
     *
     * 根据机构code获取本机构服务项目
     *
     * @param hospital
     * @return
     */
    public JSONArray selectByHospital1(String hospital){
        String sql = "select * from wlyy.wlyy_server_item si JOIN wlyy.wlyy_hospital_service_item hsi ON hsi.service_item_code = si.`code` AND hsi.del=1\n" +
                "and hsi.hospital = '"+hospital+"'";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        JSONArray  array= new JSONArray();
        JSONObject object = new JSONObject();
        object.put("type","1");
        List<Map<String,Object>> maps = new ArrayList<>();
        JSONObject object1 = new JSONObject();
        object1.put("type","2");
        List<Map<String,Object>> maps1 = new ArrayList<>();
        for (Map<String,Object> map:mapList){
            if (map.get("item_type").toString().equalsIgnoreCase("1")){
                maps.add(map);
            }else if (map.get("item_type").toString().equalsIgnoreCase("2")){
                maps1.add(map);
            }
        }
        object.put("items",maps);
        object1.put("items",maps1);
        array.add(object);
        array.add(object1);
        return array;
    }
    public List<Map<String,Object>> selectServiceByHospital(String hospital,String serverItemName,String type,String patient,String doctor){
        StringBuffer buffer = new StringBuffer();
        if(StringUtils.isNoneBlank(hospital)){
//            HospitalMapping hospitalMapping = hospitalMappingDao.findByCode(hospital);
//            buffer.append(" and ziocad.org_code = '"+hospitalMapping.getMappingCode()+"'");
        }
        String sql ="SELECT " +
                "ziocad.org_code AS hospital," +
                "zicd.clinic_code AS diagnosis_code," +
                "zicd.clinic_code AS code," +
                "zicd.clinic_name AS title," +
                "zicd.clinic_spec AS spec," +
                "zicd.clinic_unit AS unit," +
                "ziccad.allot_quantity AS quantity," +
                "zicd.subject_class AS subjectClass," +
                "ziccad.item_code AS itemCode," +
                " SUBSTR(zicd.subject_class, 1, 4) AS subjectCatagory," +
                " (CASE WHEN ISNULL(ziocd.price) THEN 0 ELSE ziocd.price END) as expense " +
                " FROM zy_iv_org_clinic_allot_dict ziocad " +
                " LEFT JOIN zy_iv_clinic_charge_allot_dict ziccad ON ziccad.clinic_code = ziocad.clinic_code AND ziccad.org_code = ziocad.org_code" +
                " LEFT JOIN zy_iv_clinic_dict zicd ON zicd.clinic_code = ziocad.clinic_code" +
                " LEFT JOIN zy_iv_org_charge_allot_dict ziocd ON ziocd.charge_code = ziccad.item_code and ziocd.org_code = ziccad.org_code  " ;
        if("used".equals(type)){
            sql += " LEFT JOIN wlyy_door_order_item i on i.code = zicd.clinic_code and (i.patient = '"+patient+"' or i.doctor='"+doctor+"') ";
            sql += " WHERE SUBSTR(zicd.subject_class, 1, 4) = '"+type+"' ";
        }else{
            sql += " WHERE SUBSTR(zicd.subject_class, 1, 4) = '"+type+"' ";
        }
        sql += buffer;
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    public List<Map<String,Object>> selectTypes(){
        String sql1 = "SELECT zisc.class_code AS code, zisc.class_name AS type FROM zy_iv_subject_class_dict zisc " +
                "WHERE zisc.class_code IN ( SELECT DISTINCT SUBSTR(zicd.subject_class, 1, 4) AS subjectCatagory " +
                "FROM zy_iv_clinic_dict zicd WHERE LENGTH(zicd.subject_class) > 4 )";
        List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sql1);
        Map<String,Object> map = new HashedMap();
        map.put("code","used");
        map.put("type","常用");
        mapList1.add(map);
        return mapList1;
    }
}

+ 146 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/consult/ConsultTeamService.java

@ -0,0 +1,146 @@
package com.yihu.jw.door.service.consult;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
 * Created by yeshijie on 2020/12/23.
 */
@Service
public class ConsultTeamService {
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    /**
     * 添加一条咨询记录
     * @param patient 患者信息
     * @param title 咨询标题
     * @param type 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,9在线复诊,11上门服务
     * @return
     */
    public ConsultDo addConsult(String patient, String title, String symptoms, String images, int type) {
        ConsultDo consult = new ConsultDo();
//        consult.setCode(getCode());
        consult.setCzrq(new Date());
        consult.setDel("1");
        consult.setPatient(patient);
        consult.setTitle(title);
        consult.setSymptoms(symptoms);
        consult.setImages(images);
        consult.setType(type);
/*        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if(signFamily!=null){
            consult.setSignCode(signFamily.getCode());
        }*/
        return consultDao.save(consult);
    }
    /**
     * 添加上门服务咨询
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    public JSONObject addDoorServiceConsult(String orderId) throws Exception {
        JSONObject result = new JSONObject();
        //上门服务关联的工单
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findOne(orderId);
        String patient = doorServiceOrderDO.getPatient();
        String doctor =  doorServiceOrderDO.getDispatcher();
        String doctorName = doorServiceOrderDO.getDispatcherName();
        int orderStatus = doorServiceOrderDO.getStatus();
        // 判断居民是否已经签约
/*        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if (signFamily == null) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前居民未签约,无法进行上门服务咨询!";
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }*/
        // 添加咨询记录
        BasePatientDO patientDO = patientDao.findById(patient);
        if(null == patientDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前咨询的居民不存在!";
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        //咨询记录
        String title = patientDO.getName() + "-发起了服务咨询";
        ConsultDo consult = addConsult(patient,title,doorServiceOrderDO.getServeDesc(),patientDO.getPhone(),11);
        //咨询详细信息
        ConsultTeamDo consultTeam = new ConsultTeamDo();
        consultTeam.setType(11);  //上门服务咨询
//        consultTeam.setAdminTeamId(signFamily.getAdminTeamId());
        consultTeam.setRelationCode(doorServiceOrderDO.getId()); //关联业务code
        consultTeam.setSymptoms(doorServiceOrderDO.getServeDesc());
        consultTeam.setPatient(patient);
        consultTeam.setName(patientDO.getName());
        consultTeam.setBirthday(patientDO.getBirthday());
        consultTeam.setSex(patientDO.getSex());
        consultTeam.setPhoto(patientDO.getPhoto());
        consultTeam.setCzrq(new Date());
        consultTeam.setDel("1");
        consultTeam.setStatus(0);
        consultTeam.setEvaluate(0);
        consultTeam.setDoctorRead(1); // 医生未读数量为1
        consult.setRelationCode(doorServiceOrderDO.getId());//关联业务code
        consultTeam.setConsult(consult.getId()); // 设置咨询标识
        //(im创建咨询) 上门服务咨询的sessionid为居民code+咨询code+工单编号+咨询类型
        String sessionId = patient + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() +  "_" + consultTeam.getType();
        //4、 上门服务咨询-参与者
        JSONObject participants = new JSONObject();
        participants.put(patient, 0);
//        participants.put(doctor, 0);
        String content = patientDO.getName() + "-上门服务咨询";
//        String content = signFamily.getHospitalName() + "为您服务";
        JSONObject messages = imUtill.getCreateTopicMessage(patient, patientDO.getName(), consult.getTitle(), content, consult.getImages(), "");
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getId(), content, participants, messages, ImUtil.SESSION_TYPE_ONDOOR_NURSING);
        if (imResponseJson == null || imResponseJson.getInteger("status") == -1) {
            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
}

+ 281 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/prescription/JwDoorPrescriptionService.java

@ -0,0 +1,281 @@
package com.yihu.jw.door.service.prescription;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.door.dao.WlyyDoorPrescriptionDao;
import com.yihu.jw.door.service.WlyyDoorPrescriptionService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDO;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.security.MD5;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 基位思明上门服务开方接口
 * Created by hmf on 2019/9/19.
 */
@Service
public class JwDoorPrescriptionService {
    private static final Logger logger = LoggerFactory.getLogger(JwDoorPrescriptionService.class);
    //基卫服务地址
    private String jwUrl="";
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private WlyyDoorPrescriptionDao doorPrescriptionDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private WlyyDoorPrescriptionService doorPrescriptionService;
    /**
     * 获取历史就诊记录
     * @param doctor 开方医生
     * @param patient 居民
     * @param visitDept 开方科室
     * @param visitTimeFrom
     * @param visitTimeEnd
     * @return
     */
    public String getVisitRecordListUnion(String doctor, String patient, String visitDept, String visitTimeFrom, String visitTimeEnd) throws Exception {
        String re = "";
        //获取居民社保卡号和签约机构
        BasePatientDO p = patientDao.findById(patient);
//        DoctorMappingDO doctorMapping = doctorMappingDao.findListByDoctorCode(doctor).get(0);
        String url = jwUrl + "/third/doorPrescription/getVisitRecordListUnion";
        List<NameValuePair> params = new ArrayList<>();
//        params.add(new BasicNameValuePair("cardNo", p.getSsc()));
//        params.add(new BasicNameValuePair("visitOperator", doctorMapping.getMappingCode()));
        params.add(new BasicNameValuePair("visitDept", visitDept));
        params.add(new BasicNameValuePair("visitTimeFrom", visitTimeFrom));
        params.add(new BasicNameValuePair("visitTimeEnd", visitTimeEnd));
        String response = httpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)) {
            org.json.JSONObject jsonObject = new org.json.JSONObject(response);
            int status = jsonObject.getInt("status");
            if (status == 200) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data) && (data.startsWith("error")||data.startsWith("System-Error"))) {
                    throw new Exception(data);
                } else {
                    re = data;
                }
            } else {
                throw new Exception(jsonObject.getString("msg"));
            }
        } else {
            throw new Exception("null response.");
        }
        return re;
    }
    /**
     * 获取处方明细
     * @param visitNo
     * @param hospital
     * @return
     */
    public String getVisitRecipeDetailUnion(String visitNo, String recipeNo, String hospital){
        String url = jwUrl + "/third/doorPrescription/getVisitRecipeDetailUnion";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("visitNo", visitNo));
        params.add(new BasicNameValuePair("recipeNo", recipeNo));
        params.add(new BasicNameValuePair("hospital", hospital));
        String response = httpClientUtil.post(url, params, "UTF-8");
        return response;
    }
    /**
     * 处方开方接口
     * @param prescriptionCode 处方code
     * @return
     * @throws Exception
     */
    public String saveRecipeUnion(String prescriptionCode,String visitOperator,String visitDept){
        String response = null;
        try {
            String url = jwUrl + "/third/doorPrescription/saveRecipeUnion";
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("prescriptionCode", prescriptionCode));
            params.add(new BasicNameValuePair("visitDept", visitDept));
            params.add(new BasicNameValuePair("visitOperator", visitOperator));
            response = httpClientUtil.post(url, params, "UTF-8");
            return response;
        }catch (Exception e){
            logger.info("处方开方接口saveRecipeUnion:"+response);
            throw e;
        }
    }
    /**
     * 取消处方接口
     * @param prescriptionCode 处方code
     * @return
     * @throws Exception
     */
    public JSONObject fadeRecipeUnion(String prescriptionCode, String doctor){
        JSONObject result = new JSONObject();
        WlyyDoorPrescriptionDO prescription = doorPrescriptionDao.findByCode(prescriptionCode);
        BaseDoctorDO d = doctorDao.findById(doctor);
//        DoctorMapping doctorMapping = doctorMappingDao.findByDoctorCode(doctor);
        try {
            if (StringUtils.isNotBlank(prescription.getVisitNo())) {
                String url = jwUrl + "/third/doorPrescription/fadeRecipeUnion";
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("visitNo", prescription.getVisitNo()));//挂号号
                params.add(new BasicNameValuePair("fadeDept", prescription.getJwDeptCode()));//作废科室编码
//                params.add(new BasicNameValuePair("fadeOperator", doctorMapping.getJwDoctor()));//作废人员编码
//                params.add(new BasicNameValuePair("hospital", d.getHospital()));//机构编码
                String response = httpClientUtil.post(url, params, "UTF-8");
                if (StringUtils.isNotBlank(response)) {
                    JSONObject reobj = JSON.parseObject(response);
                    Integer status = reobj.getInteger("status");
                    String errmsg = reobj.getString("msg");
                    if (200 != status) {
                        result.put("status", -1);
                        result.put("msg", "基卫接口(挂号作废)请求失败," + errmsg);
                        return result;
                    }
                    result.put("status", 200);
                    result.put("msg", "基卫接口(挂号作废)请求成功!");
                    prescription.setStatus(-1);
                    prescription.setUpdateTime(new Date());
                    doorPrescriptionDao.save(prescription);
                } else {
                    result.put("status", -1);
                    result.put("msg", "基卫接口(挂号作废)请求失败,无数据返回!");
                    return result;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * CA认证通过接口
     *
     * @return
     */
    public org.json.JSONObject requestRealNameSoftCertAndSign(String doctorCode, String strRealNameSoftCertCalledPasswd, String strOriginalData, String prescriptionCode) throws Exception {
        WlyyDoorPrescriptionDO prescription = doorPrescriptionDao.findByCode(prescriptionCode);
        //处方详情
        JSONObject res = new JSONObject();
        BaseDoctorDO doctor = doctorDao.findById(doctorCode);
        String url = jwUrl + "/third/prescription/RequestRealNameSoftCertAndSign";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("strUserIdcardNum", doctor.getIdcard()));
        params.add(new BasicNameValuePair("strRealNameSoftCertCalledPasswd", strRealNameSoftCertCalledPasswd));
        if(StringUtils.isBlank(strOriginalData)){
            res = doorPrescriptionService.getPrescriptionByCode(prescription.getRecipeNo(), prescription.getPatient());
            strOriginalData = res.toString();
        }
        String originalDataAbstract = MD5.GetMD5Code(strOriginalData);
        params.add(new BasicNameValuePair("strOriginalData", originalDataAbstract));
        params.add(new BasicNameValuePair("prescriptionCode", prescriptionCode));
//        params.add(new BasicNameValuePair("srcBusinessStreamNO",srcBusinessStreamNO));
        String response = httpClientUtil.post(url, params, "UTF-8");
        if (!StringUtils.isEmpty(response)) {
            org.json.JSONObject responseObject = new org.json.JSONObject(response);
            int status = responseObject.getInt("status");
            String msg = responseObject.getString("msg");
            if (status == 200) {
                String data = responseObject.getString("data");
                if (StringUtils.isEmpty(data)) {
                    throw new Exception("null data");
                } else {
                    String[] str = data.split("\\|\\|");
//                    String strSignData = str[0];
//                    String strCertData = str[1];
                    org.json.JSONObject jsonObject = new org.json.JSONObject();
                    jsonObject.put("strSignData", str[0]);
                    jsonObject.put("strCertData", str[1]);
                    jsonObject.put("srcBusinessStreamNO", str[2]);
                    jsonObject.put("data", res);
                    prescription.setCaMessage(str[0]);
                    prescription.setCaCertData(str[1]);
                    prescription.setDigitalSignNo(str[2]);
                    prescription.setStrOriginalData(res.getJSONObject("prescriptionDrugList").toString());
                    prescription.setOriginalDataAbstract(originalDataAbstract);
                    doorPrescriptionDao.save(prescription);
                    //更新ca认证系统消息
//                    messageDao.updateMessageByRelationCode(prescriptionCode, 409);
                    this.uploadCaDigital(prescriptionCode);
                    return jsonObject;
                }
            } else {
                String error = msg.split("\\|\\|")[0].split(":")[2];
                throw new Exception(error);
            }
        } else {
            throw new Exception("null response.");
        }
    }
    //上传基位ca认证信息
    public JSONObject uploadCaDigital(String prescriptionCode) {
        JSONObject re = new JSONObject();
        WlyyDoorPrescriptionDO prescription = doorPrescriptionDao.findByCode(prescriptionCode);
        String url = jwUrl + "/third/doorPrescription/affirmCARecipe";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("code", prescriptionCode));//续方code
        String response = httpClientUtil.post(url, params, "UTF-8");
        JSONObject json = JSONObject.parseObject(response);
        if (json.getInteger("status") == 200) {
            JSONObject data = JSONObject.parseObject(json.getString("data"));
            String zyCode = data.getString("CODE");
            if ("1".equals(zyCode)) {
                JSONArray returnData = data.getJSONArray("returnData");
                if (returnData.size() > 0) {
                    //{"status":200,"msg":"CA认证通过接口!","data":"{\"CODE\":\"1\",\"returnData\":[{\"result\":\"True\"}],\"byRefParaData\":[{ \"errorMsg\": \"\" }]}"}
                    JSONObject pre = returnData.getJSONObject(0);
                    if ("True".equals(pre.getString("result"))) {
                        //认证成功-审核完成
                        re.put("status", 200);
                    } else {
                        JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                        re.put("status", -1);
                        re.put("msg", byRefParaData.getJSONObject(0).getString("errorMsg"));
                    }
                } else {
                    JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                    re.put("status", -1);
                    re.put("msg", byRefParaData.getJSONObject(0).getString("errorMsg"));
                }
            } else {
                re.put("status", -1);
                re.put("msg", data.getString("MESSAGE"));
            }
        } else {
            re.put("status", -1);
            re.put("msg", "上传ca认证信息失败");
        }
        return re;
    }
}

+ 272 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/prescription/PresModeAdapter.java

@ -0,0 +1,272 @@
package com.yihu.jw.door.service.prescription;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Iterator;
/**
 * Created by Trick on 2017/8/10.
 */
@Component
public class PresModeAdapter {
    private static Logger logger = LoggerFactory.getLogger(PresModeAdapter.class);
/*    @Autowired
    private ZyDictService zyDictService;
    @Autowired
    private DictIcd10Se icd10DictServcie;*/
    /**
     * 处方详情转换
     * @param json
     * @return
     */
    public JSONObject modelToSinglePrescription(String json){
        try{
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = JSONObject.parseObject(oldJson.getString("data"));
            JSONArray returnData = data.getJSONArray("returnData");
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                JSONArray modeArray = returnData.getJSONArray(0);
                JSONObject mode = (JSONObject) modeArray.get(0);
                JSONObject p  = new JSONObject();
                p.put("code",mode.getInteger("RECIPE_NO")+"");
                p.put("createTime",mode.getString("APPLY_TIME"));
/*                Doctor doctor =  zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"),mode.getString("HEALTH_ORG_CODE"));
                // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                if(doctor!=null){
                    p.put("doctor",doctor.getCode());
                    p.put("doctorName",doctor.getName());
                    p.put("hospitalName",doctor.getHospitalName());
                    p.put("hospital",doctor.getHospital());
                    p.put("jwHospital",mode.getString("HEALTH_ORG_CODE"));
                }else{
                    p.put("doctor",mode.getString("APPLY_OPERATOR"));
                    p.put("doctorName",mode.getString("APPLY_OPERATOR_NAME"));
                    p.put("hospitalName",mode.getString("HEALTH_ORG_CODE"));
                    p.put("jwHospital",mode.getString("HEALTH_ORG_CODE"));
                }*/
                JSONObject diagnosis = new JSONObject();
                String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                String diagnoseCode = "E10.100";
//                String diagnoseName = "1型糖尿病性酮症";
                diagnosis.put("code",diagnoseCode);//诊断代码
                diagnosis.put("name",diagnoseName);//诊断名称
/*                String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                if(!StringUtils.isEmpty(icd10)){
                    JSONObject icd = JSONObject.parseObject(icd10);
                    diagnosis.put("healthProblemName",icd.getString("value"));//诊断名称
                    diagnosis.put("healthProblem",icd.getString("key"));//诊断代码
                }else{
                    diagnosis.put("healthProblemName",diagnoseName);//诊断名称
                    diagnosis.put("healthProblem",diagnoseCode);//诊断代码
                }*/
                JSONArray jsonArrayDt = new JSONArray();
                jsonArrayDt.add(diagnosis);
    
                if(mode.getString("DIAGNOSE_SUB_CODE")!=null){
                    JSONObject diagnosisSub = new JSONObject();
                    String diagnoseCodeSub = mode.getString("DIAGNOSE_SUB_CODE");
                    String diagnoseNameSub = mode.getString("DIAGNOSE_SUB_NAME");
                    diagnosisSub.put("code",diagnoseCodeSub);//诊断代码
                    diagnosisSub.put("name",diagnoseNameSub);//诊断名称
/*                    String icd10Sub = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCodeSub);
                    if(!StringUtils.isEmpty(icd10Sub)){
                        JSONObject icdSub = JSONObject.parseObject(icd10Sub);
                        diagnosisSub.put("healthProblemName",icdSub.getString("value"));//诊断名称
                        diagnosisSub.put("healthProblem",icdSub.getString("key"));//诊断代码
                    }else{
                        diagnosisSub.put("healthProblemName",diagnoseNameSub);//诊断名称
                        diagnosisSub.put("healthProblem",diagnoseCodeSub);//诊断代码
                    }*/
                    jsonArrayDt.add(diagnosisSub);
                }
                
                p.put("prescriptionDt",jsonArrayDt);
                JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                Iterator infoIt = infos.iterator();
                JSONArray prescriptionInfos = new JSONArray();
                while (infoIt.hasNext()){
                    JSONObject info = (JSONObject) infoIt.next();
                    JSONObject prescriptionInfo = new JSONObject();
                    prescriptionInfo.put("Remark",info.getString("REMARK"));
                    prescriptionInfo.put("BindFlag",info.getString("BIND_FLAG"));
                    prescriptionInfo.put("direction",info.getString("USAGE_NAME"));//药品用法
                    prescriptionInfo.put("drugCode",info.getString("ITEM_CODE"));//药品code
                    prescriptionInfo.put("drugName",info.getString("ITEM_NAME"));//药品名称
                    prescriptionInfo.put("drugRate",info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                    prescriptionInfo.put("drugRateName",info.getString("FREQUENCY_NAME"));
                    prescriptionInfo.put("drugFormat",info.getString("ITEM_SPEC"));//药品规格
                    prescriptionInfo.put("price",info.getDouble("ITEM_PRICE"));//药品单价
                    prescriptionInfo.put("num",info.getInteger("ITEM_QUANTITY"));//药品数目
                    prescriptionInfo.put("jwSubCode",info.getString("RECIPE_SUB_NO"));//智业子处方号
                    prescriptionInfo.put("drugNumUnit",info.getString("ITEM_UNIT"));//数量单位编码
                    prescriptionInfo.put("drugNumUnitName",info.getString("ITEM_UNIT_NAME"));//数量单位名称
                    prescriptionInfo.put("cost",info.getDouble("COST"));//金额
                    prescriptionInfo.put("charge",info.getDouble("CHARGE"));//自付
                    prescriptionInfo.put("bindFlag",info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                    prescriptionInfo.put("dayCount",info.getInteger("DAY_COUNT"));//用药天数
                    prescriptionInfo.put("drugUsage",info.getString("USAGE"));//用药方法编码
                    prescriptionInfo.put("usageName",info.getString("USAGE_NAME"));//用药方法名称
                    prescriptionInfo.put("physicDose",info.getString("PHYSIC_DOSE"));//用药剂量
                    prescriptionInfo.put("physicDoseUnit",info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                    prescriptionInfo.put("physicDoseUnitName",info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                    prescriptionInfo.put("physicAmount",info.getString("PHYSIC_AMOUNT"));//用药总量
                    prescriptionInfo.put("physicAmountUnit",info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                    prescriptionInfo.put("physicAmountUnitName",info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                    prescriptionInfo.put("physicInjectPlace",info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                    prescriptionInfo.put("physicInjectPlaceName",info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                    prescriptionInfo.put("physicSkinTest",info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                    prescriptionInfo.put("physicSkinTestName",info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                    prescriptionInfo.put("subjectClass",info.getString("SUBJECT_CLASS"));//科目类型
                    prescriptionInfos.add(prescriptionInfo);
                }
                p.put("prescriptionInfo",prescriptionInfos);
                return p;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modelToSinglePrescription:Json:"+json);
            throw e;
        }
        return new JSONObject();
    }
    /**
     * 思明上门处方详情转换
     * @param json
     * @return
     */
    public JSONArray modelToDoorPrescription(String json){
        try{
            JSONArray res = new JSONArray();
            JSONObject oldJson = JSONObject.parseObject(json);
            if(oldJson.getInteger("status")!=200){
                throw new RuntimeException("智业接口失败:"+oldJson.getString("msg"));
            }
            JSONObject data = JSONObject.parseObject(oldJson.getString("data"));
            JSONArray returnData = data.getJSONArray("returnData").getJSONArray(0);
            String code = data.getString("CODE");
            if(StringUtils.isNotBlank(code)&&"1".equals(code)&&returnData.size()>0){
                for(Object o : returnData) {
//                    JSONArray modeArray = returnData.getJSONArray(0);
                    JSONObject mode = (JSONObject) o;
                    JSONObject p = new JSONObject();
                    p.put("code", mode.getInteger("RECIPE_NO") + "");
                    p.put("createTime", mode.getString("APPLY_TIME"));
/*                    Doctor doctor = zyDictService.getDoctByJw(mode.getString("APPLY_OPERATOR"), mode.getString("HEALTH_ORG_CODE"));
                    // "APPLY_OPERATOR_NAME": 开单医生姓名","HEALTH_ORG_CODE": "开单机构编码",
                    if (doctor != null) {
                        p.put("doctor", doctor.getCode());
                        p.put("doctorName", doctor.getName());
                        p.put("hospitalName", doctor.getHospitalName());
                        p.put("hospital", doctor.getHospital());
                        p.put("jwHospital", mode.getString("HEALTH_ORG_CODE"));
                    } else {
                        p.put("doctor", mode.getString("APPLY_OPERATOR"));
                        p.put("doctorName", mode.getString("APPLY_OPERATOR_NAME"));
                        p.put("hospitalName", mode.getString("HEALTH_ORG_CODE"));
                        p.put("jwHospital", mode.getString("HEALTH_ORG_CODE"));
                    }*/
                    JSONObject diagnosis = new JSONObject();
                    String diagnoseCode = mode.getString("DIAGNOSE_CODE");
                    String diagnoseName = mode.getString("DIAGNOSE_NAME");
//                String diagnoseCode = "E10.100";
//                String diagnoseName = "1型糖尿病性酮症";
                    diagnosis.put("code", diagnoseCode);//诊断代码
                    diagnosis.put("name", diagnoseName);//诊断名称
/*                    String icd10 = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCode);
                    if (!StringUtils.isEmpty(icd10)) {
                        JSONObject icd = JSONObject.parseObject(icd10);
                        diagnosis.put("healthProblemName", icd.getString("value"));//诊断名称
                        diagnosis.put("healthProblem", icd.getString("key"));//诊断代码
                    } else {
                        diagnosis.put("healthProblemName", diagnoseName);//诊断名称
                        diagnosis.put("healthProblem", diagnoseCode);//诊断代码
                    }*/
                    JSONArray jsonArrayDt = new JSONArray();
                    jsonArrayDt.add(diagnosis);
                    if (mode.getString("DIAGNOSE_SUB_CODE") != null) {
                        JSONObject diagnosisSub = new JSONObject();
                        String diagnoseCodeSub = mode.getString("DIAGNOSE_SUB_CODE");
                        String diagnoseNameSub = mode.getString("DIAGNOSE_SUB_NAME");
                        diagnosisSub.put("code", diagnoseCodeSub);//诊断代码
                        diagnosisSub.put("name", diagnoseNameSub);//诊断名称
/*                        String icd10Sub = icd10DictServcie.getHealthProblemsByIcd10Code(diagnoseCodeSub);
                        if (!StringUtils.isEmpty(icd10Sub)) {
                            JSONObject icdSub = JSONObject.parseObject(icd10Sub);
                            diagnosisSub.put("healthProblemName", icdSub.getString("value"));//诊断名称
                            diagnosisSub.put("healthProblem", icdSub.getString("key"));//诊断代码
                        } else {
                            diagnosisSub.put("healthProblemName", diagnoseNameSub);//诊断名称
                            diagnosisSub.put("healthProblem", diagnoseCodeSub);//诊断代码
                        }*/
                        jsonArrayDt.add(diagnosisSub);
                    }
//                    p.put("prescriptionDt", jsonArrayDt);
                    JSONArray infos = mode.getJSONArray("RECIPE_DETAIL");
                    Iterator infoIt = infos.iterator();
                    JSONArray prescriptionInfos = new JSONArray();
                    while (infoIt.hasNext()) {
                        JSONObject info = (JSONObject) infoIt.next();
                        JSONObject prescriptionInfo = new JSONObject();
                        prescriptionInfo.put("Remark", info.getString("REMARK"));
                        prescriptionInfo.put("BindFlag", info.getString("BIND_FLAG"));
                        prescriptionInfo.put("direction", info.getString("USAGE_NAME"));//药品用法
                        prescriptionInfo.put("drugCode", info.getString("ITEM_CODE"));//药品code
                        prescriptionInfo.put("drugName", info.getString("ITEM_NAME"));//药品名称
                        prescriptionInfo.put("drugRate", info.getString("FREQUENCY"));//吃药频率 FREQUENCY
                        prescriptionInfo.put("drugRateName", info.getString("FREQUENCY_NAME"));
                        prescriptionInfo.put("drugFormat", info.getString("ITEM_SPEC"));//药品规格
                        prescriptionInfo.put("price", info.getDouble("ITEM_PRICE"));//药品单价
                        prescriptionInfo.put("num", info.getInteger("ITEM_QUANTITY"));//药品数目
                        prescriptionInfo.put("jwSubCode", info.getString("RECIPE_SUB_NO"));//智业子处方号
                        prescriptionInfo.put("drugNumUnit", info.getString("ITEM_UNIT"));//数量单位编码
                        prescriptionInfo.put("drugNumUnitName", info.getString("ITEM_UNIT_NAME"));//数量单位名称
                        prescriptionInfo.put("cost", info.getDouble("COST"));//金额
                        prescriptionInfo.put("charge", info.getDouble("CHARGE"));//自付
                        prescriptionInfo.put("bindFlag", info.getString("BIND_FLAG"));//成组标志, 0.非成组,1.成组
                        prescriptionInfo.put("dayCount", info.getInteger("DAY_COUNT"));//用药天数
                        prescriptionInfo.put("drugUsage", info.getString("USAGE"));//用药方法编码
                        prescriptionInfo.put("usageName", info.getString("USAGE_NAME"));//用药方法名称
                        prescriptionInfo.put("physicDose", info.getString("PHYSIC_DOSE"));//用药剂量
                        prescriptionInfo.put("physicDoseUnit", info.getString("PHYSIC_DOSE_UNIT"));//剂量单位编码
                        prescriptionInfo.put("physicDoseUnitName", info.getString("PHYSIC_DOSE_UNIT_NAME"));//剂量单位名称
                        prescriptionInfo.put("physicAmount", info.getString("PHYSIC_AMOUNT"));//用药总量
                        prescriptionInfo.put("physicAmountUnit", info.getString("PHYSIC_AMOUNT_UNIT"));//总量单位编码
                        prescriptionInfo.put("physicAmountUnitName", info.getString("PHYSIC_AMOUNT_UNIT_NAME"));//总量单位名称
                        prescriptionInfo.put("physicInjectPlace", info.getString("PHYSIC_INJECT_PLACE"));//注射地点编码
                        prescriptionInfo.put("physicInjectPlaceName", info.getString("PHYSIC_INJECT_PLACE_NAME"));//注射地点名称
                        prescriptionInfo.put("physicSkinTest", info.getString("PHYSIC_SKIN_TEST"));//皮试类型名称
                        prescriptionInfo.put("physicSkinTestName", info.getString("PHYSIC_SKIN_TEST_NAME"));//皮试类型名称
                        prescriptionInfo.put("subjectClass", info.getString("SUBJECT_CLASS"));//科目类型
                        prescriptionInfos.add(prescriptionInfo);
                    }
                    p.put("prescriptionInfo", prescriptionInfos);
                    res.add(p);
                }
                return res;
            }
        }catch (Exception e){
            logger.info("PresModeAdapter:modelToSinglePrescription:Json:"+json);
            throw e;
        }
        return new JSONArray();
    }
}

+ 1563 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/statics/DoorStatisticAnalyzeService.java

@ -0,0 +1,1563 @@
package com.yihu.jw.door.service.statics;
import com.yihu.jw.area.dao.BaseTownDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.area.BaseTownDO;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.es.util.SaveModel;
import com.yihu.jw.org.dao.BaseOrgDao;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author liuwenbin on 2019/3/21.
 */
@Service
public class DoorStatisticAnalyzeService {
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;
    @Autowired
    private BaseTownDao townDao;
    @Autowired
    private BaseOrgDao hospitalDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private StatisticsUtilService statisticsUtilService;
    public List<Map<String,Object>> doorQualificationAnalyzeList(String area,String startDate,String endDate,Integer level,String lowLevel)throws Exception{
        List<Map<String, Object>> resultList = new ArrayList<>();
        if(StringUtils.isNotEmpty(lowLevel)){
            lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel))+"";
        }else{
            lowLevel = String.valueOf(level + 1);
        }
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "120", "1", lowLevel, null);
        Map<String, List<SaveModel>> map = null;
        if (esModelList != null && esModelList.size() > 0) {
            if (lowLevel.equals("3")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getTown));
            } else if (lowLevel.equals("4")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            } else if (lowLevel.equals("5")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getDept));
            }
            for (String one1 : map.keySet()) {
                Map<String, Object> resultMap = new HashMap();
                List<SaveModel> list1 = map.get(one1);
                resultMap.put("code", one1);
                if (lowLevel.equals("3")) {
                    resultMap.put("name", list1.get(0).getTownName());
                } else if (lowLevel.equals("4")) {
                    resultMap.put("name", list1.get(0).getHospitalName());
                } else if (lowLevel.equals("5")) {
                    resultMap.put("name", list1.get(0).getDeptName());
                }
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                //0、审核中,1、未通过,2、已通过
                resultMap.put("examine", map2.get("0").get(0).getResult2().intValue());
                resultMap.put("nopass", map2.get("1").get(0).getResult2().intValue());
                resultMap.put("pass", map2.get("2").get(0).getResult2().intValue());
                resultMap.put("all", (Integer) resultMap.get("examine") + (Integer) resultMap.get("nopass") + (Integer) resultMap.get("pass"));
                resultList.add(resultMap);
            }
            resultList.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if ( (Integer) o1.get("all") > (Integer) o2.get("all")) {
                        return -1;
                    } else if ((Integer) o1.get("all") < (Integer) o2.get("all")) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        return resultList;
    }
    public Map<String,Object> doorQualificationAnalyzeHead(String area,String startDate,String endDate,Integer level)throws Exception{
        Map<String, Object> resultMap = new HashMap();
        String low_level = String.valueOf(level + 1);
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "120", "1", low_level, null);
        if (esModelList != null && esModelList.size() > 0) {
            Map<String, List<SaveModel>> map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            resultMap.put("examine", map.get("0").get(0).getResult2().intValue());
            resultMap.put("nopass", map.get("1").get(0).getResult2().intValue());
            resultMap.put("pass", map.get("2").get(0).getResult2().intValue());
            resultMap.put("all", (Integer) resultMap.get("examine") + (Integer) resultMap.get("nopass") + (Integer) resultMap.get("pass"));
        }
        return resultMap;
    }
    /**
     * 资质分析
     * @param area
     * @param startDate
     * @param endDate
     * @throws Exception
     */
    public List<Map<String,Object>> doorQualificationAnalyze(String area,String startDate,String endDate)throws Exception{
        List<BaseTownDO> areaCode = new ArrayList<>();
        if(StringUtils.isEmpty(area)){
            areaCode = townDao.findByCityCode("350200");
        }else{
            areaCode.add(townDao.findByCode(area));
        }
        List<Map<String,Object>> result = new ArrayList<>();
        for(BaseTownDO one:areaCode) {
            List<SaveModel> townList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "120", "1", null, null);//区
            List<SaveModel> orgList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "120", "1", "4", null);//区
            Map<String, List<SaveModel>> map = townList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            Map<String, List<SaveModel>> map1 = orgList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            Map<String, Object> parentResultMap = new HashMap<>();
            parentResultMap.put("level", 1);
            parentResultMap.put("area", one.getName());
            parentResultMap.put("examine", map.get("0").get(0).getResult2().intValue());
            parentResultMap.put("nopass", map.get("1").get(0).getResult2().intValue());
            parentResultMap.put("pass", map.get("2").get(0).getResult2().intValue());
            parentResultMap.put("all", (Integer) parentResultMap.get("examine") + (Integer) parentResultMap.get("nopass") + (Integer) parentResultMap.get("pass"));
            List<Map<String, Object>> childrenResultList = new LinkedList<>();
            for (String one1 : map1.keySet()) {
                Map<String, Object> childrenResultMap = new HashMap();
                List<SaveModel> list1 = map1.get(one1);//机构
                childrenResultMap.put("level", 2);
                childrenResultMap.put("area", hospitalDao.findByCode(one1).getName());
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                //0、审核中,1、未通过,2、已通过
                childrenResultMap.put("examine", map2.get("0").get(0).getResult2().intValue());
                childrenResultMap.put("nopass", map2.get("1").get(0).getResult2().intValue());
                childrenResultMap.put("pass", map2.get("2").get(0).getResult2().intValue());
                childrenResultMap.put("all", (Integer) childrenResultMap.get("examine") + (Integer) childrenResultMap.get("nopass") + (Integer) childrenResultMap.get("pass"));
                childrenResultList.add(childrenResultMap);
            }
            parentResultMap.put("children", childrenResultList);
            result.add(parentResultMap);
        }
        return result;
    }
    /**
     * 服务工单分析
     * @param area
     * @param startDate
     * @param endDate
     * @throws Exception
     */
    public List<Map<String,Object>> doorServiceOrderAnalyze(String area,String startDate,String endDate, Integer type)throws Exception{
        DecimalFormat df = new DecimalFormat("0.00");
        List<BaseTownDO> areaCode = new ArrayList<>();
        if(StringUtils.isEmpty(area)){
            areaCode = townDao.findByCityCode("350200");
        }else{
            areaCode.add(townDao.findByCode(area));
        }
        List<Map<String,Object>> result = new ArrayList<>();
        for(BaseTownDO one:areaCode) {
            List<SaveModel> townList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "121", "1", null, type);//区
            List<SaveModel> orgList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "121", "1", "4", type);//机构
            Map<String, List<SaveModel>> map = townList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            Map<String, List<SaveModel>> map1 = orgList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            Map<String, Object> parentResultMap = new HashMap<>();
            parentResultMap.put("level", 1);
            parentResultMap.put("area", one.getName());
            parentResultMap.put("cancelled", map.get("-1").get(0).getResult2().intValue());
            parentResultMap.put("waitinglist", map.get("1").get(0).getResult2().intValue());
            parentResultMap.put("waitingorder", map.get("2").get(0).getResult2().intValue());
            parentResultMap.put("waitingservice", map.get("3").get(0).getResult2().intValue());
            parentResultMap.put("waitingpay", map.get("4").get(0).getResult2().intValue());
            parentResultMap.put("waitingcomment", map.get("5").get(0).getResult2().intValue());
            parentResultMap.put("completed", map.get("6").get(0).getResult2().intValue());
            String evaluateSplitParent = "0.0";
            evaluateSplitParent = df.format(map.get("6").get(0).getResult2()> 0 ? map.get("6").get(0).getResult1()/(map.get("6").get(0).getResult2() *1.000) : 0.00);
            parentResultMap.put("evaluateSplit", evaluateSplitParent);
            parentResultMap.put("all", (Integer) parentResultMap.get("cancelled") + (Integer) parentResultMap.get("waitinglist") + (Integer) parentResultMap.get("waitingorder")
                    + (Integer) parentResultMap.get("waitingservice")+ (Integer) parentResultMap.get("waitingpay")+ (Integer) parentResultMap.get("waitingcomment")
                    + (Integer) parentResultMap.get("completed")
            );
            List<Map<String, Object>> childrenResultList = new LinkedList<>();
            for (String one1 : map1.keySet()) {
                Map<String, Object> childrenResultMap = new HashMap();
                List<SaveModel> list1 = map1.get(one1);//机构
                childrenResultMap.put("level", 2);
                childrenResultMap.put("area", hospitalDao.findByCode(one1).getName());
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                //工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待付款,5-待评价,6-已完成,评价均分-evaluateSplit
                childrenResultMap.put("cancelled", map2.get("-1").get(0).getResult2().intValue());
                childrenResultMap.put("waitinglist", map2.get("1").get(0).getResult2().intValue());
                childrenResultMap.put("waitingorder", map2.get("2").get(0).getResult2().intValue());
                childrenResultMap.put("waitingservice", map2.get("3").get(0).getResult2().intValue());
                childrenResultMap.put("waitingpay", map2.get("4").get(0).getResult2().intValue());
                childrenResultMap.put("waitingcomment", map2.get("5").get(0).getResult2().intValue());
                childrenResultMap.put("completed", map2.get("6").get(0).getResult2().intValue());
                String evaluateSplitChildren = "0.0";
                evaluateSplitChildren = df.format(map2.get("6").get(0).getResult2()> 0 ? map2.get("6").get(0).getResult1()/(map2.get("6").get(0).getResult2() *1.000) : 0.00);
                childrenResultMap.put("evaluateSplit", evaluateSplitChildren);
                childrenResultMap.put("all", (Integer) childrenResultMap.get("cancelled") + (Integer) childrenResultMap.get("waitinglist") + (Integer) childrenResultMap.get("waitingorder")
                        + (Integer) childrenResultMap.get("waitingservice")+ (Integer) childrenResultMap.get("waitingpay")+ (Integer) childrenResultMap.get("waitingcomment")
                        + (Integer) childrenResultMap.get("completed")
                );
                childrenResultList.add(childrenResultMap);
            }
            parentResultMap.put("children", childrenResultList);
            result.add(parentResultMap);
        }
        return result;
    }
    /**
     * 服务工单分析
     * @param area
     * @param startDate
     * @param endDate
     * @throws Exception
     */
    public Map<String,Object> doorServiceOrderAnalyzeHead(String area,String startDate,String endDate, Integer type,Integer level)throws Exception{
        Map<String, Object> resultMap = new HashMap();
        String low_level = String.valueOf(level + 1);
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "121", "1", low_level, type);
        DecimalFormat df = new DecimalFormat("0.00");
        if (esModelList != null && esModelList.size() > 0) {
        Map<String, List<SaveModel>> map2 = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
        //工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待付款,5-待评价,6-已完成,评价均分-evaluateSplit
        resultMap.put("cancelled", map2.get("-1").get(0).getResult2().intValue());
        resultMap.put("waitinglist", map2.get("1").get(0).getResult2().intValue());
        resultMap.put("waitingorder", map2.get("2").get(0).getResult2().intValue());
        resultMap.put("waitingservice", map2.get("3").get(0).getResult2().intValue());
        resultMap.put("waitingpay", map2.get("4").get(0).getResult2().intValue());
        resultMap.put("waitingcomment", map2.get("5").get(0).getResult2().intValue());
        resultMap.put("completed", map2.get("6").get(0).getResult2().intValue());
        String evaluateSplitChildren = "0.0";
        evaluateSplitChildren = df.format(map2.get("6").get(0).getResult2()> 0 ? map2.get("6").get(0).getResult1()/(map2.get("6").get(0).getResult2() *1.000) : 0.00);
        resultMap.put("evaluateSplit", evaluateSplitChildren);
        resultMap.put("all", (Integer) resultMap.get("cancelled") + (Integer) resultMap.get("waitinglist") + (Integer) resultMap.get("waitingorder")
                + (Integer) resultMap.get("waitingservice")+ (Integer) resultMap.get("waitingpay")+ (Integer) resultMap.get("waitingcomment")
                + (Integer) resultMap.get("completed"));
        }
        return resultMap;
    }
    /**
     * 服务工单分析
     * @param area
     * @param startDate
     * @param endDate
     * @throws Exception
     */
    public List<Map<String,Object>> doorServiceOrderAnalyzeList(String area,String startDate,String endDate, Integer type,Integer level,String lowLevel)throws Exception{
        List<Map<String, Object>> resultList = new ArrayList<>();
        if(StringUtils.isNotEmpty(lowLevel)){
            lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel))+"";
        }else{
            lowLevel = String.valueOf(level + 1);
        }
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "121", "1", lowLevel, type);
        Map<String, List<SaveModel>> map = null;
        DecimalFormat df = new DecimalFormat("0.00");
        if (esModelList != null && esModelList.size() > 0) {
            if (lowLevel.equals("3")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getTown));
            } else if (lowLevel.equals("4")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            } else if (lowLevel.equals("5")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getDept));
            }
            for (String one1 : map.keySet()) {
                Map<String, Object> resultMap = new HashMap();
                List<SaveModel> list1 = map.get(one1);
                resultMap.put("code", one1);
                if (lowLevel.equals("3")) {
                    resultMap.put("name", list1.get(0).getTownName());
                } else if (lowLevel.equals("4")) {
                    resultMap.put("name", list1.get(0).getHospitalName());
                } else if (lowLevel.equals("5")) {
                    resultMap.put("name", list1.get(0).getDeptName());
                }
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                //工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待付款,5-待评价,6-已完成,评价均分-evaluateSplit
                resultMap.put("cancelled", map2.get("-1").get(0).getResult2().intValue());
                resultMap.put("waitinglist", map2.get("1").get(0).getResult2().intValue());
                resultMap.put("waitingorder", map2.get("2").get(0).getResult2().intValue());
                resultMap.put("waitingservice", map2.get("3").get(0).getResult2().intValue());
                resultMap.put("waitingpay", map2.get("4").get(0).getResult2().intValue());
                resultMap.put("waitingcomment", map2.get("5").get(0).getResult2().intValue());
                resultMap.put("completed", map2.get("6").get(0).getResult2().intValue());
                String evaluateSplitChildren = "0.0";
                evaluateSplitChildren = df.format(map2.get("6").get(0).getResult2()> 0 ? map2.get("6").get(0).getResult1()/(map2.get("6").get(0).getResult2() *1.000) : 0.00);
                resultMap.put("evaluateSplit", evaluateSplitChildren);
                resultMap.put("all", (Integer) resultMap.get("cancelled") + (Integer) resultMap.get("waitinglist") + (Integer) resultMap.get("waitingorder")
                                + (Integer) resultMap.get("waitingservice")+ (Integer) resultMap.get("waitingpay")+ (Integer) resultMap.get("waitingcomment")
                                + (Integer) resultMap.get("completed"));
                resultList.add(resultMap);
            }
            resultList.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if ( (Integer) o1.get("all") > (Integer) o2.get("all")) {
                        return -1;
                    } else if ((Integer) o1.get("all") < (Integer) o2.get("all")) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        return resultList;
    }
    /**
     * 响应时间分析
     * @param area
     * @param startDate
     * @param endDate
     * @param roleType
     * @return
     */
    public Map<String,Object> doorResponseAnalyzeHead(String area,String startDate,String endDate,Integer roleType,Integer level)throws Exception{
        String index;
        if(roleType==1){
            index = "119";
        }else{
            index = "122";
        }
        Map<String, Object> resultMap = new HashMap();
        String low_level = String.valueOf(level + 1);
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, index, "1", low_level, null);
        Map<String, List<SaveModel>> map = null;
        if (esModelList != null && esModelList.size() > 0) {
            Map<String, List<SaveModel>> map2 = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            resultMap.put("h01", map2.get("1").get(0).getResult2().intValue());
            resultMap.put("h12", map2.get("2").get(0).getResult2().intValue());
            resultMap.put("h23", map2.get("3").get(0).getResult2().intValue());
            resultMap.put("h34", map2.get("4").get(0).getResult2().intValue());
            resultMap.put("h45", map2.get("5").get(0).getResult2().intValue());
            resultMap.put("h5more", map2.get("6").get(0).getResult2().intValue());
            Integer childrenAll = map2.get("1").get(0).getResult2().intValue()+map2.get("2").get(0).getResult2().intValue()+map2.get("3").get(0).getResult2().intValue()+
                    map2.get("4").get(0).getResult2().intValue()+map2.get("5").get(0).getResult2().intValue()+map2.get("6").get(0).getResult2().intValue();
            resultMap.put("all", childrenAll);
        }
        return resultMap;
    }
    /**
     * 响应时间分析
     * @param area
     * @param startDate
     * @param endDate
     * @param roleType
     * @return
     */
    public List<Map<String,Object>> doorResponseAnalyzeList(String area,String startDate,String endDate,Integer roleType,Integer level,String lowLevel)throws Exception{
        String index;
        if(roleType==1){
            index = "119";
        }else{
            index = "122";
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        if(StringUtils.isNotEmpty(lowLevel)){
            lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel))+"";
        }else{
            lowLevel = String.valueOf(level + 1);
        }
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, index, "1", lowLevel, null);
        Map<String, List<SaveModel>> map = null;
        if (esModelList != null && esModelList.size() > 0) {
            if (lowLevel.equals("3")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getTown));
            } else if (lowLevel.equals("4")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            } else if (lowLevel.equals("5")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getDept));
            }
            for (String one1 : map.keySet()) {
                Map<String, Object> resultMap = new HashMap();
                List<SaveModel> list1 = map.get(one1);
                resultMap.put("code", one1);
                if (lowLevel.equals("3")) {
                    resultMap.put("name", list1.get(0).getTownName());
                } else if (lowLevel.equals("4")) {
                    resultMap.put("name", list1.get(0).getHospitalName());
                } else if (lowLevel.equals("5")) {
                    resultMap.put("name", list1.get(0).getDeptName());
                }
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                resultMap.put("h01", map2.get("1").get(0).getResult2().intValue());
                resultMap.put("h12", map2.get("2").get(0).getResult2().intValue());
                resultMap.put("h23", map2.get("3").get(0).getResult2().intValue());
                resultMap.put("h34", map2.get("4").get(0).getResult2().intValue());
                resultMap.put("h45", map2.get("5").get(0).getResult2().intValue());
                resultMap.put("h5more", map2.get("6").get(0).getResult2().intValue());
                Integer childrenAll = map2.get("1").get(0).getResult2().intValue()+map2.get("2").get(0).getResult2().intValue()+map2.get("3").get(0).getResult2().intValue()+
                        map2.get("4").get(0).getResult2().intValue()+map2.get("5").get(0).getResult2().intValue()+map2.get("6").get(0).getResult2().intValue();
                resultMap.put("all", childrenAll);
                resultList.add(resultMap);
            }
            resultList.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if ( (Integer) o1.get("all") > (Integer) o2.get("all")) {
                        return -1;
                    } else if ((Integer) o1.get("all") < (Integer) o2.get("all")) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        return resultList;
    }
    /**
     * 响应时间分析
     * @param area
     * @param startDate
     * @param endDate
     * @param roleType
     * @return
     */
    public List<Map<String,Object>> doorResponseAnalyze(String area,String startDate,String endDate,Integer roleType, Integer type)throws Exception{
        String index = "";
        if(roleType==1){
            index = "119";
        }else{
            index = "122";
        }
        List<BaseTownDO> areaCode = new ArrayList<>();
        if(StringUtils.isEmpty(area)){
            areaCode = townDao.findByCityCode("350200");
        }else{
            areaCode.add(townDao.findByCode(area));
        }
        List<Map<String,Object>> result = new ArrayList<>();
        for(BaseTownDO one:areaCode) {
            List<SaveModel> townList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, index, "1", null, type);//区
            List<SaveModel> orgList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, index, "1", "4", type);//机构
            Map<String, List<SaveModel>> map = townList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            Map<String, List<SaveModel>> map1 = orgList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            Map<String, Object> parentResultMap = new HashMap<>();
            parentResultMap.put("level", 1);
            parentResultMap.put("area", one.getName());
            parentResultMap.put("h01", map.get("1").get(0).getResult2().intValue());
            parentResultMap.put("h12", map.get("2").get(0).getResult2().intValue());
            parentResultMap.put("h23", map.get("3").get(0).getResult2().intValue());
            parentResultMap.put("h34", map.get("4").get(0).getResult2().intValue());
            parentResultMap.put("h45", map.get("5").get(0).getResult2().intValue());
            parentResultMap.put("h5more", map.get("6").get(0).getResult2().intValue());
            Integer parentAll = map.get("1").get(0).getResult2().intValue()+map.get("2").get(0).getResult2().intValue()+map.get("3").get(0).getResult2().intValue()+
                    map.get("4").get(0).getResult2().intValue()+map.get("5").get(0).getResult2().intValue()+map.get("6").get(0).getResult2().intValue();
            parentResultMap.put("all", parentAll);
            List<Map<String, Object>> childrenResultList = new LinkedList<>();
            for (String one1 : map1.keySet()) {
                Map<String, Object> childrenResultMap = new HashMap();
                List<SaveModel> list1 = map1.get(one1);//机构
                childrenResultMap.put("level", 2);
                childrenResultMap.put("area", hospitalDao.findByCode(one1).getName());
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                childrenResultMap.put("h01", map2.get("1").get(0).getResult2().intValue());
                childrenResultMap.put("h12", map2.get("2").get(0).getResult2().intValue());
                childrenResultMap.put("h23", map2.get("3").get(0).getResult2().intValue());
                childrenResultMap.put("h34", map2.get("4").get(0).getResult2().intValue());
                childrenResultMap.put("h45", map2.get("5").get(0).getResult2().intValue());
                childrenResultMap.put("h5more", map2.get("6").get(0).getResult2().intValue());
                Integer childrenAll = map2.get("1").get(0).getResult2().intValue()+map2.get("2").get(0).getResult2().intValue()+map2.get("3").get(0).getResult2().intValue()+
                        map2.get("4").get(0).getResult2().intValue()+map2.get("5").get(0).getResult2().intValue()+map2.get("6").get(0).getResult2().intValue();
                childrenResultMap.put("all", childrenAll);
                childrenResultList.add(childrenResultMap);
            }
            parentResultMap.put("children", childrenResultList);
            result.add(parentResultMap);
        }
        return result;
    }
    /**
     * 补助费用
     * @param area
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public Map<String,Object> subsidyExpenseHead(String area,String startDate,String endDate,Integer level)throws Exception{
        Map<String, Object> resultMap = new HashMap<>();
        String low_level = String.valueOf(level + 1);
        List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "118", "1", low_level, null);
        if (esModelList != null && esModelList.size() > 0) {
            Map<String, List<SaveModel>> map2 = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            //上门出诊人次
            resultMap.put("outcalls_senior", map2.get("1").get(0).getResult2().intValue());//副高及以上
            resultMap.put("outcalls_attending", map2.get("2").get(0).getResult2().intValue());//主治医师
            resultMap.put("outcalls_nurse", map2.get("3").get(0).getResult2().intValue());//护士
            Integer subsidyChildrenAll = (Integer) resultMap.get("outcalls_senior")+(Integer) resultMap.get("outcalls_attending")+(Integer) resultMap.get("outcalls_nurse");
            resultMap.put("outcalls_all", subsidyChildrenAll);
            //补助费用
            resultMap.put("subsidy_senior", (Integer) resultMap.get("outcalls_senior")*150);//副高及以上
            resultMap.put("subsidy_attending", (Integer) resultMap.get("outcalls_attending")*120);//主治医师
            resultMap.put("subsidy_nurse", (Integer) resultMap.get("outcalls_nurse")*80);//护士
            Integer outcallsChildrenAll = (Integer) resultMap.get("subsidy_senior")+(Integer) resultMap.get("subsidy_attending")+(Integer) resultMap.get("subsidy_nurse");
            resultMap.put("subsidy_all", outcallsChildrenAll);
        }
        return resultMap;
    }
    /**
     * 补助费用
     * @param area
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> subsidyExpenseList(String area,String startDate,String endDate,Integer level,String lowLevel)throws Exception{
        List<Map<String, Object>> resultList = new ArrayList<>();
        if(StringUtils.isNotEmpty(lowLevel)){
            lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel))+"";
        }else{
            lowLevel = String.valueOf(level + 1);
        }
        Map<String, List<SaveModel>> map = null;
                List<SaveModel> esModelList = findDateQuotaLevel1(startDate, endDate, area, level, "118", "1", lowLevel, null);
        if (esModelList != null && esModelList.size() > 0) {
            if (lowLevel.equals("3")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getTown));
            } else if (lowLevel.equals("4")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            } else if (lowLevel.equals("5")) {
                map = esModelList.stream().collect(Collectors.groupingBy(SaveModel::getDept));
            }
            for (String one1 : map.keySet()) {
                Map<String, Object> resultMap = new HashMap();
                List<SaveModel> list1 = map.get(one1);
                resultMap.put("code", one1);
                if (lowLevel.equals("3")) {
                    resultMap.put("name", list1.get(0).getTownName());
                } else if (lowLevel.equals("4")) {
                    resultMap.put("name", list1.get(0).getHospitalName());
                } else if (lowLevel.equals("5")) {
                    resultMap.put("name", list1.get(0).getDeptName());
                }
                //上门出诊人次
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                resultMap.put("outcalls_senior", map2.get("1").get(0).getResult2().intValue());//副高及以上
                resultMap.put("outcalls_attending", map2.get("2").get(0).getResult2().intValue());//主治医师
                resultMap.put("outcalls_nurse", map2.get("3").get(0).getResult2().intValue());//护士
                Integer subsidyChildrenAll = (Integer) resultMap.get("outcalls_senior")+(Integer) resultMap.get("outcalls_attending")+(Integer) resultMap.get("outcalls_nurse");
                resultMap.put("outcalls_all", subsidyChildrenAll);
                //补助费用
                resultMap.put("subsidy_senior", (Integer) resultMap.get("outcalls_senior")*150);//副高及以上
                resultMap.put("subsidy_attending", (Integer) resultMap.get("outcalls_attending")*120);//主治医师
                resultMap.put("subsidy_nurse", (Integer) resultMap.get("outcalls_nurse")*80);//护士
                Integer outcallsChildrenAll = (Integer) resultMap.get("subsidy_senior")+(Integer) resultMap.get("subsidy_attending")+(Integer) resultMap.get("subsidy_nurse");
                resultMap.put("subsidy_all", outcallsChildrenAll);
                resultList.add(resultMap);
            }
            resultList.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    if ( (Integer) o1.get("outcalls_all") > (Integer) o2.get("outcalls_all")) {
                        return -1;
                    } else if ((Integer) o1.get("outcalls_all") < (Integer) o2.get("outcalls_all")) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        return resultList;
    }
    /**
     * 补助费用
     * @param area
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> subsidyExpense(String area,String startDate,String endDate)throws Exception{
        List<BaseTownDO> areaCode = new ArrayList<>();
        if(StringUtils.isEmpty(area)){
            areaCode = townDao.findByCityCode("350200");
        }else{
            areaCode.add(townDao.findByCode(area));
        }
        List<Map<String,Object>> result = new ArrayList<>();
        for(BaseTownDO one:areaCode) {
            List<SaveModel> townList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "118", "1", null, null);//区
            List<SaveModel> orgList = findDateQuotaLevel1(startDate, endDate, one.getCode(), 3, "118", "1", "4", null);//机构
            Map<String, List<SaveModel>> map = townList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            Map<String, List<SaveModel>> map1 = orgList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
            Map<String, Object> parentResultMap = new HashMap<>();
            parentResultMap.put("level", 1);
            parentResultMap.put("area", one.getName());
            //医生、护士80/人次;主治医师120/人次;副高及以上150/人次
            //上门出诊人次
            parentResultMap.put("outcalls_senior", map.get("1").get(0).getResult2().intValue());//副高及以上
            parentResultMap.put("outcalls_attending", map.get("2").get(0).getResult2().intValue());//主治医师
            parentResultMap.put("outcalls_nurse", map.get("3").get(0).getResult2().intValue());//护士
            Integer subsidyParentAll = (Integer) parentResultMap.get("outcalls_senior")+(Integer) parentResultMap.get("outcalls_attending")+(Integer) parentResultMap.get("outcalls_nurse");
            parentResultMap.put("outcalls_all", subsidyParentAll);
            //补助费用
            parentResultMap.put("subsidy_senior", (Integer) parentResultMap.get("outcalls_senior")*150);//副高及以上
            parentResultMap.put("subsidy_attending", (Integer) parentResultMap.get("outcalls_attending")*120);//主治医师
            parentResultMap.put("subsidy_nurse", (Integer) parentResultMap.get("outcalls_nurse")*80);//护士
            Integer outcallsParentAll = (Integer) parentResultMap.get("subsidy_senior")+(Integer) parentResultMap.get("subsidy_attending")+(Integer) parentResultMap.get("subsidy_nurse");
            parentResultMap.put("subsidy_all", outcallsParentAll);
            List<Map<String, Object>> childrenResultList = new LinkedList<>();
            for (String one1 : map1.keySet()) {
                Map<String, Object> childrenResultMap = new HashMap();
                List<SaveModel> list1 = map1.get(one1);//机构
                childrenResultMap.put("level", 2);
                childrenResultMap.put("area", hospitalDao.findByCode(one1).getName());
                Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
                childrenResultMap.put("outcalls_senior", map2.get("1").get(0).getResult2().intValue());//副高及以上
                childrenResultMap.put("outcalls_attending", map2.get("2").get(0).getResult2().intValue());//主治医师
                childrenResultMap.put("outcalls_nurse", map2.get("3").get(0).getResult2().intValue());//护士
                Integer subsidyChildrenAll = (Integer) childrenResultMap.get("outcalls_senior")+(Integer) childrenResultMap.get("outcalls_attending")+(Integer) childrenResultMap.get("outcalls_nurse");
                childrenResultMap.put("outcalls_all", subsidyChildrenAll);
                //补助费用
                childrenResultMap.put("subsidy_senior", (Integer) childrenResultMap.get("outcalls_senior")*150);//副高及以上
                childrenResultMap.put("subsidy_attending", (Integer) childrenResultMap.get("outcalls_attending")*120);//主治医师
                childrenResultMap.put("subsidy_nurse", (Integer) childrenResultMap.get("outcalls_nurse")*80);//护士
                Integer outcallsChildrenAll = (Integer) childrenResultMap.get("subsidy_senior")+(Integer) childrenResultMap.get("subsidy_attending")+(Integer) childrenResultMap.get("subsidy_nurse");
                childrenResultMap.put("subsidy_all", outcallsChildrenAll);
                childrenResultList.add(childrenResultMap);
            }
            parentResultMap.put("children", childrenResultList);
            result.add(parentResultMap);
        }
        return result;
    }
    /*****************************************************export Excel start**************************************************************************************/
    /**
     * 资质分析导出excel
     * @param area
     * @param startDate
     * @param endDate
     * @param response
     * @throws Exception
     */
    public void doorQualificationAnalyzeExport(String area,String startDate,String endDate, HttpServletResponse response)throws Exception{
        WritableWorkbook book = null;
        OutputStream os = null;
        try{
            List<Map<String,Object>> list = doorQualificationAnalyze(area,startDate,endDate);
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "上门服务资质分析统计";
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "_" + sdf.format(date) + ".xls");
            os = response.getOutputStream();
            book = Workbook.createWorkbook(os);
            WritableSheet sheet = book.createSheet("上门服务资质分析统计", 0);
            WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            WritableCellFormat headerFormat = new WritableCellFormat (headerFont);
            sheet.addCell(new Label(0, 0, "地区/机构",headerFormat));
            sheet.addCell(new Label(1, 0, "合计(人)",headerFormat));
            sheet.addCell(new Label(2, 0, "待审核(人)",headerFormat));
            sheet.addCell(new Label(3, 0, "已通过(人)",headerFormat));
            sheet.addCell(new Label(4, 0, "未通过(人)",headerFormat));
            Integer a = 0;
            for (int i = 0; i < list.size(); i++) {
                sheet.addCell(new Label(0, i + a + 1,list.get(i).get("area")+"",headerFormat));
                sheet.addCell(new Label(1, i + a + 1,list.get(i).get("all")+"",headerFormat));
                sheet.addCell(new Label(2, i + a + 1,list.get(i).get("examine")+"",headerFormat));
                sheet.addCell(new Label(3, i + a + 1,list.get(i).get("pass")+"",headerFormat));
                sheet.addCell(new Label(4, i + a + 1,list.get(i).get("nopass")+"",headerFormat));
                List<Map<String,Object>> childrenList = (List<Map<String,Object>>)list.get(i).get("children");
                for(int j = 0; j < childrenList.size(); j++){
                    sheet.addCell(new Label(0, i + 1 + a + 1+j,childrenList.get(j).get("area")+""));
                    sheet.addCell(new Label(1, i + 1 + a + 1+j,childrenList.get(j).get("all")+""));
                    sheet.addCell(new Label(2, i + 1 + a + 1+j,childrenList.get(j).get("examine")+""));
                    sheet.addCell(new Label(3, i + 1 + a + 1+j,childrenList.get(j).get("pass")+""));
                    sheet.addCell(new Label(4, i + 1 + a + 1+j,childrenList.get(j).get("nopass")+""));
                }
                a+=childrenList.size();
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if(book!=null){
                book.write();
                book.close();
            }
            if(os!=null){
                os.flush();
                os.close();
            }
        }
    }
    /**
     * 响应速度导出excel
     * @param area
     * @param startDate
     * @param endDate
     * @param roleType
     * @param response
     * @throws Exception
     */
    public void doorResponseAnalyzeExport(String area,String startDate,String endDate,Integer roleType, HttpServletResponse response, Integer type)throws Exception{
        WritableWorkbook book = null;
        OutputStream os = null;
        try{
            List<Map<String,Object>> list = doorResponseAnalyze(area,startDate,endDate,roleType, type);
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "上门服务响应速度分析统计";
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "_" + sdf.format(date) + ".xls");
            os = response.getOutputStream();
            book = Workbook.createWorkbook(os);
            WritableSheet sheet = book.createSheet("上门服务响应速度分析统计", 0);
            WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            WritableCellFormat headerFormat = new WritableCellFormat (headerFont);
            sheet.addCell(new Label(0, 0, "地区/机构",headerFormat));
            sheet.addCell(new Label(1, 0, "0-1h(个)",headerFormat));
            sheet.addCell(new Label(2, 0, "1-2h(个)",headerFormat));
            sheet.addCell(new Label(3, 0, "2-3h(个)",headerFormat));
            sheet.addCell(new Label(4, 0, "3-4h(个)",headerFormat));
            sheet.addCell(new Label(5, 0, "4-5h(个)",headerFormat));
            sheet.addCell(new Label(6, 0, "5h以上(个)",headerFormat));
            Integer a = 0;
            for (int i = 0; i < list.size(); i++) {
                sheet.addCell(new Label(0, i + a + 1,list.get(i).get("area")+"",headerFormat));
                sheet.addCell(new Label(1, i + a + 1,list.get(i).get("h01")+"",headerFormat));
                sheet.addCell(new Label(2, i + a + 1,list.get(i).get("h12")+"",headerFormat));
                sheet.addCell(new Label(3, i + a + 1,list.get(i).get("h23")+"",headerFormat));
                sheet.addCell(new Label(4, i + a + 1,list.get(i).get("h34")+"",headerFormat));
                sheet.addCell(new Label(5, i + a + 1,list.get(i).get("h45")+"",headerFormat));
                sheet.addCell(new Label(6, i + a + 1,list.get(i).get("h5more")+"",headerFormat));
                List<Map<String,Object>> childrenList = (List<Map<String,Object>>)list.get(i).get("children");
                for(int j = 0; j < childrenList.size(); j++){
                    sheet.addCell(new Label(0, i + 1 + a + 1 + j,childrenList.get(j).get("area")+""));
                    sheet.addCell(new Label(1, i + 1 + a + 1 + j,childrenList.get(j).get("h01")+""));
                    sheet.addCell(new Label(2, i + 1 + a + 1 + j,childrenList.get(j).get("h12")+""));
                    sheet.addCell(new Label(3, i + 1 + a + 1 + j,childrenList.get(j).get("h23")+""));
                    sheet.addCell(new Label(4, i + 1 + a + 1 + j,childrenList.get(j).get("h34")+""));
                    sheet.addCell(new Label(5, i + 1 + a + 1 + j,childrenList.get(j).get("h45")+""));
                    sheet.addCell(new Label(6, i + 1 + a + 1 + j,childrenList.get(j).get("h5more")+""));
                }
                a+=childrenList.size();
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if(book!=null){
                book.write();
                book.close();
            }
            if(os!=null){
                os.flush();
                os.close();
            }
        }
    }
    /**
     * 补助费用导出excel
     * @param area
     * @param startDate
     * @param endDate
     * @param response
     * @throws Exception
     */
    public void subsidyExpenseExport(String area,String startDate,String endDate, HttpServletResponse response)throws Exception{
        WritableWorkbook book = null;
        OutputStream os = null;
        try{
            List<Map<String,Object>> list = subsidyExpense(area,startDate,endDate);
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "上门服务补助费用分析统计";
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "_" + sdf.format(date) + ".xls");
            os = response.getOutputStream();
            book = Workbook.createWorkbook(os);
            WritableSheet sheet = book.createSheet("上门服务补助费用分析统计", 0);
            WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            WritableCellFormat headerFormat = new WritableCellFormat (headerFont);
            sheet.mergeCells(0,0,0,1);
            sheet.mergeCells(1,0,4,0);
            sheet.mergeCells(5,0,8,0);
            sheet.addCell(new Label(0, 0, "地区/机构",headerFormat));
            sheet.addCell(new Label(1, 0, "补助费用",headerFormat));
            sheet.addCell(new Label(5, 0, "上门出诊人次",headerFormat));
            sheet.addCell(new Label(1, 1, "合计(元)",headerFormat));
            sheet.addCell(new Label(2, 1, "医生/护士(元)",headerFormat));
            sheet.addCell(new Label(3, 1, "主治医师(元)",headerFormat));
            sheet.addCell(new Label(4, 1, "副高及以上(元",headerFormat));
            sheet.addCell(new Label(5, 1, "合计(人次)",headerFormat));
            sheet.addCell(new Label(6, 1, "医生/护士(人次)",headerFormat));
            sheet.addCell(new Label(7, 1, "主治医师(人次)",headerFormat));
            sheet.addCell(new Label(8, 1, "副高及以上(人次)",headerFormat));
            Integer a = 0;
            for (int i = 0; i < list.size(); i++) {
                sheet.addCell(new Label(0, i + a + 2,list.get(i).get("area")+"",headerFormat));
                sheet.addCell(new Label(1, i + a + 2,list.get(i).get("subsidy_all")+"",headerFormat));
                sheet.addCell(new Label(2, i + a + 2,list.get(i).get("subsidy_nurse")+"",headerFormat));
                sheet.addCell(new Label(3, i + a + 2,list.get(i).get("subsidy_attending")+"",headerFormat));
                sheet.addCell(new Label(4, i + a + 2,list.get(i).get("subsidy_senior")+"",headerFormat));
                sheet.addCell(new Label(5, i + a + 2,list.get(i).get("outcalls_all")+"",headerFormat));
                sheet.addCell(new Label(6, i + a + 2,list.get(i).get("outcalls_nurse")+"",headerFormat));
                sheet.addCell(new Label(7, i + a + 2,list.get(i).get("outcalls_attending")+"",headerFormat));
                sheet.addCell(new Label(8, i + a + 2,list.get(i).get("outcalls_senior")+"",headerFormat));
                List<Map<String,Object>> childrenList = (List<Map<String,Object>>)list.get(i).get("children");
                for(int j = 0; j < childrenList.size(); j++){
                    sheet.addCell(new Label(0, i + 2 + a + 1 + j,childrenList.get(j).get("area")+""));
                    sheet.addCell(new Label(1, i + 2 + a + 1 + j,childrenList.get(j).get("subsidy_all")+""));
                    sheet.addCell(new Label(2, i + 2 + a + 1 + j,childrenList.get(j).get("subsidy_nurse")+""));
                    sheet.addCell(new Label(3, i + 2 + a + 1 + j,childrenList.get(j).get("subsidy_attending")+""));
                    sheet.addCell(new Label(4, i + 2 + a + 1 + j,childrenList.get(j).get("subsidy_senior")+""));
                    sheet.addCell(new Label(5, i + 2 + a + 1 + j,childrenList.get(j).get("outcalls_all")+""));
                    sheet.addCell(new Label(6, i + 2 + a + 1 + j,childrenList.get(j).get("outcalls_nurse")+""));
                    sheet.addCell(new Label(7, i + 2 + a + 1 + j,childrenList.get(j).get("outcalls_attending")+""));
                    sheet.addCell(new Label(8, i + 2 + a + 1 + j,childrenList.get(j).get("outcalls_senior")+""));
                }
                a+=childrenList.size();
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if(book!=null){
                book.write();
                book.close();
            }
            if(os!=null){
                os.flush();
                os.close();
            }
        }
    }
    /**
     * 服务工单分析导出excel
     * @param area
     * @param startDate
     * @param endDate
     * @param response
     * @param type
     * @throws Exception
     */
    public void doorServiceOrderAnalyzeExport(String area, String startDate, String endDate, HttpServletResponse response, Integer type)throws Exception{
        WritableWorkbook book = null;
        OutputStream os = null;
        try{
            List<Map<String,Object>> list = doorServiceOrderAnalyze(area,startDate,endDate, type);
            response.setCharacterEncoding("utf-8");
            response.setContentType("octets/stream");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "上门服务工单分析统计";
            response.setHeader("Content-Disposition", "attachment; filename="
                    + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "_" + sdf.format(date) + ".xls");
            os = response.getOutputStream();
            book = Workbook.createWorkbook(os);
            WritableSheet sheet = book.createSheet("上门服务工单分析统计", 0);
            WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            WritableCellFormat headerFormat = new WritableCellFormat (headerFont);
            sheet.addCell(new Label(0, 0, "地区/机构",headerFormat));
            sheet.addCell(new Label(1, 0, "合计(个)",headerFormat));
            sheet.addCell(new Label(2, 0, "待派单(个)",headerFormat));
            sheet.addCell(new Label(3, 0, "待接单(个)",headerFormat));
            sheet.addCell(new Label(4, 0, "待服务(个)",headerFormat));
            sheet.addCell(new Label(5, 0, "待付款(个)",headerFormat));
            sheet.addCell(new Label(6, 0, "待评价(个)",headerFormat));
            sheet.addCell(new Label(7, 0, "已完成(个)",headerFormat));
            sheet.addCell(new Label(8, 0, "已取消(个)",headerFormat));
            sheet.addCell(new Label(9, 0, "评价均分(分)",headerFormat));
            Integer a = 0;
            for (int i = 0; i < list.size(); i++) {
                sheet.addCell(new Label(0, i + a + 1,list.get(i).get("area")+"",headerFormat));
                sheet.addCell(new Label(1, i + a + 1,list.get(i).get("all")+"",headerFormat));
                sheet.addCell(new Label(2, i + a + 1,list.get(i).get("waitinglist")+"",headerFormat));
                sheet.addCell(new Label(3, i + a + 1,list.get(i).get("waitingorder")+"",headerFormat));
                sheet.addCell(new Label(4, i + a + 1,list.get(i).get("waitingservice")+"",headerFormat));
                sheet.addCell(new Label(5, i + a + 1,list.get(i).get("waitingpay")+"",headerFormat));
                sheet.addCell(new Label(6, i + a + 1,list.get(i).get("waitingcomment")+"",headerFormat));
                sheet.addCell(new Label(7, i + a + 1,list.get(i).get("completed")+"",headerFormat));
                sheet.addCell(new Label(8, i + a + 1,list.get(i).get("cancelled")+"",headerFormat));
                sheet.addCell(new Label(9, i + a + 1,list.get(i).get("evaluateSplit")+"",headerFormat));
                List<Map<String,Object>> childrenList = (List<Map<String,Object>>)list.get(i).get("children");
                for(int j = 0; j < childrenList.size(); j++){
                    sheet.addCell(new Label(0, i + 2 + a + 1 + j,childrenList.get(j).get("area")+""));
                    sheet.addCell(new Label(1, i + 2 + a + 1 + j,childrenList.get(j).get("all")+""));
                    sheet.addCell(new Label(2, i + 2 + a + 1 + j,childrenList.get(j).get("waitinglist")+""));
                    sheet.addCell(new Label(3, i + 2 + a + 1 + j,childrenList.get(j).get("waitingorder")+""));
                    sheet.addCell(new Label(4, i + 2 + a + 1 + j,childrenList.get(j).get("waitingservice")+""));
                    sheet.addCell(new Label(5, i + 2 + a + 1 + j,childrenList.get(j).get("waitingpay")+""));
                    sheet.addCell(new Label(6, i + 2 + a + 1 + j,childrenList.get(j).get("waitingcomment")+""));
                    sheet.addCell(new Label(7, i + 2 + a + 1 + j,childrenList.get(j).get("completed")+""));
                    sheet.addCell(new Label(8, i + 2 + a + 1 + j,childrenList.get(j).get("cancelled")+""));
                    sheet.addCell(new Label(9, i + 2 + a + 1 + j,childrenList.get(j).get("evaluateSplit")+""));
                }
                a+=childrenList.size();
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (WriteException e) {
            e.printStackTrace();
        }finally {
            if(book!=null){
                book.write();
                book.close();
            }
            if(os!=null){
                os.flush();
                os.close();
            }
        }
    }
    /*****************************************************export Excel end**************************************************************************************/
    private List findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String lowLevel, Integer type) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = elasticsearchUtil.changeTime(startDate);
            } else {
                startDate = elasticsearchUtil.changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = elasticsearchUtil.changeTime(endDate);
            } else {
                endDate = elasticsearchUtil.changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.deptLevel.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");
            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");
            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");
            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");
            groupBy.append(",slaveKey1,slaveKey1Name");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.deptLevel.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(type != null){
            if(type == 3) {
                sql.append(" and slaveKey2 = 3 ");
            }else {
                sql.append(" and (slaveKey2 is null or slaveKey2 in (1,2))");
            }
        }
        sql.append(groupBy);
        sql.append(" order by slaveKey1 desc,slaveKey2 desc");
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public List findDateQuotaLevelByPage(String startDate, String endDate, String area, int level, String index, String timeLevel, String lowLevel, Integer page, Integer pageSize) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = elasticsearchUtil.changeTime(startDate);
            } else {
                startDate = elasticsearchUtil.changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = elasticsearchUtil.changeTime(endDate);
            } else {
                endDate = elasticsearchUtil.changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.deptLevel.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");
            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");
            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");
            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");
            groupBy.append(",slaveKey1,slaveKey1Name");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.deptLevel.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' and result1 > 0 ");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        sql.append(groupBy);
        sql.append(" order by result1 desc,result2 desc limit " + (page-1) * pageSize + "," + pageSize);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public Map<String,Object> doorAggregateAnalysis(String area, int level, String startDate, String endDate) throws Exception {
        Map<String,Object> resMap = new HashMap<>();
        String whereSql = "";
        //计算上门服务已服务居民
        String sql = "SELECT count(DISTINCT o.patient) count FROM `wlyy_door_service_order` o LEFT JOIN wlyy.wlyy_sign_family f ON f.patient = o.patient " +
                "WHERE o.`status` != -1 and f. STATUS = 1 AND f.expenses_status = 1 AND o.create_time >= '" +startDate +"' AND o.create_time <= '" + endDate + "' ";
        if(level == 3){
            whereSql += "and f.hospital like '" + area + "%' ";
        }else if(level == 4){
            whereSql += "and f.hospital = '" + area + "' ";
        }else if(level == 5){
            whereSql += "and f.admin_team_code='" + area + "' ";
        }
        Integer doorPatientService = jdbcTemplate.queryForObject(sql + whereSql, Integer.class);
        resMap.put("doorPatientServiceCount", doorPatientService);
        //获取上门服务资质服务人群分析,到达量
        List<SaveModel> voucherList = findDateQuotaLevel1(endDate, endDate, area, level, "133", "2", level + "", null);
        resMap.put("voucherList", voucherList);
        //获取上门服务处方主诊断疾病分析
        List<Map<String, Object>> diagnosisList = getOrderByDiagnosis(area, level, startDate, endDate, 1, 5);
        resMap.put("diagnosisList", diagnosisList);
        //获取服务项目和药品分析
        List<Map<String, Object>> drugList = getGroupbyDrugCodeList(area, level, "010", 1, 5, startDate, endDate);
        List<Map<String, Object>> itemList = getGroupbyDrugCodeList(area, level, "020", 1, 5, startDate, endDate);
        resMap.put("drugList", drugList);
        resMap.put("itemList", itemList);
        //获取服务工单排行
        List<SaveModel> orderList = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, "121", "1", null, level + "");
        List<SaveModel> slaveList = findDateQuotaLevel1(startDate, endDate, area, level, "121", "1", level + "", null);
        Map<String, List<SaveModel>> map = slaveList.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
//        resMap.put("orderList", orderList);
        //计算服务评价均分
        Double parentResult1= 0.0;
        Double parentResult2 = 0.0;
        for(SaveModel saveModel : orderList){
            parentResult1 +=saveModel.getResult1();
            parentResult2 +=saveModel.getResult2();
        }
        BigDecimal decimalParent1 = new BigDecimal(Double.toString(parentResult1));
        BigDecimal decimalParent2 = new BigDecimal(Double.toString(parentResult2));
        DecimalFormat df = new DecimalFormat("0.00");
        String evaluateSplitParent = "0.0";
        evaluateSplitParent = df.format(map.get("6").get(0).getResult2()> 0 ? map.get("6").get(0).getResult1()/(map.get("6").get(0).getResult2() *1.000) : 0.00);
        resMap.put("evaluateSplit", evaluateSplitParent);
        return resMap;
    }
    public List<Map<String,Object>> getOrderByDiagnosis(String area, int level, String startDate, String endDate, Integer page, Integer pageSize) {
        String sql = "SELECT p.diagnosis_code code,p.diagnosis_name name,count(p.order_id) as orderCount " +
                "FROM `wlyy_door_prescription` p LEFT JOIN wlyy.wlyy_sign_family f ON f.patient = p.patient " +
                "WHERE p.`status`>=50 and f. STATUS = 1 AND f.expenses_status = 1 ";
        if(level == 3){
            sql += "and f.hospital like '" + area + "%' ";
        }else if(level == 4){
            sql += "and f.hospital = '" + area + "' ";
        }else if(level == 5){
            sql += "and f.admin_team_code='" + area + "' ";
        }
        if(StringUtils.isNotBlank(startDate)){
            sql += "and p.create_time >= '" + startDate + "' ";
        }
        if(StringUtils.isNotBlank(endDate)){
            sql += "and p.create_time <= '" + endDate + "' ";
        }
        List<Map<String, Object>> diagnosisList = jdbcTemplate.queryForList(sql + " GROUP BY p.diagnosis_code limit " + (page-1) * pageSize + "," + pageSize);
        return diagnosisList;
    }
    /**
     * 获取服务项目和药品分析
     * @param area 对应等级机构
     * @param level 机构等级 3区 4机构 5团队
     * @param subjectClass 科目类别,010开头为药品,020为服务项目
     * @param page
     * @param pageSize
     * @param startDate
     * @param endDate
     * @return
     */
    public List<Map<String,Object>> getGroupbyDrugCodeList(String area, int level, String subjectClass, int page, int pageSize, String startDate, String endDate) {
        String drugSql="SELECT d.drug_code code,d.drug_name name,count(DISTINCT p.order_id) orderCount,count(DISTINCT p.patient) patientCount " +
                "FROM `wlyy_door_prescription_drug` d , wlyy_door_prescription p LEFT JOIN wlyy.wlyy_sign_family f ON f.patient = p.patient  " +
                "where d.prescription_code = p.code and p.`status`>=50  and f. STATUS = 1 AND f.expenses_status = 1 AND p.create_time >= '" +startDate +"' AND p.create_time <= '" + endDate + "'  ";
        if(StringUtils.isNotBlank(subjectClass)){
            drugSql += "and d.subject_class like '" + subjectClass + "%' ";
        }
        if(level == 3){
            drugSql += "and f.hospital like '" + area + "%' ";
        }else if(level == 4){
            drugSql += "and f.hospital = '" + area + "' ";
        }else if(level == 5){
            drugSql += "and f.admin_team_code='" + area + "' ";
        }
        drugSql += "GROUP BY d.drug_code order by orderCount desc, patientCount desc limit " + (page-1) * pageSize + "," + pageSize;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(drugSql);
        return list;
    }
    /**
     * 获取上门服务合计工单排行
     * @param endDate
     * @param area
     * @param level
     * @param sort
     * @param lowLevel
     * @param year
     * @return
     * @throws Exception
     */
    public JSONArray getOrderLowlevelAll(String startDate, String endDate, String area, int level, int sort, String lowLevel, String year) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //工单状态列表
        List<SaveModel> slaveList = findDateQuotaLevel1(startDate, endDate, area, level, "121", "1", lowLevel, null);
        Map<String, List<SaveModel>> map1 = new HashMap<>();
        if (SaveModel.OrgLevel.equals(lowLevel)) {
            map1 = slaveList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
        } else if (SaveModel.townLevel.equals(lowLevel)) {
            map1 = slaveList.stream().collect(Collectors.groupingBy(SaveModel::getTown));
        } else if (SaveModel.deptLevel.equals(lowLevel)) {
            map1 = slaveList.stream().collect(Collectors.groupingBy(SaveModel::getDept));
        }
//        Map<String, List<SaveModel>> map1 = slaveList.stream().collect(Collectors.groupingBy(SaveModel::getHospital));
        for (String one1 : map1.keySet()) {
            Map<String, Object> childrenResultMap = new HashMap();
            List<SaveModel> list1 = map1.get(one1);//机构
            childrenResultMap.put("code", one1);
            if (SaveModel.OrgLevel.equals(lowLevel)) {
                childrenResultMap.put("name", list1.get(0).getHospitalName());
            } else if (SaveModel.townLevel.equals(lowLevel)) {
                childrenResultMap.put("name", list1.get(0).getTownName());
            } else if (SaveModel.deptLevel.equals(lowLevel)) {
                childrenResultMap.put("name", list1.get(0).getDeptName());
            }
            Map<String, List<SaveModel>> map2 = list1.stream().collect(Collectors.groupingBy(SaveModel::getSlaveKey1));
            //工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待服务,5-待评价,6-已完成,评价均分-evaluateSplit
            childrenResultMap.put("cancelled", map2.get("-1").get(0).getResult2().intValue());
            childrenResultMap.put("waitinglist", map2.get("1").get(0).getResult2().intValue());
            childrenResultMap.put("waitingorder", map2.get("2").get(0).getResult2().intValue());
            childrenResultMap.put("waitingservice", map2.get("3").get(0).getResult2().intValue());
            childrenResultMap.put("waitingpay", map2.get("4").get(0).getResult2().intValue());
            childrenResultMap.put("waitingcomment", map2.get("5").get(0).getResult2().intValue());
            childrenResultMap.put("completed", map2.get("6").get(0).getResult2().intValue());
            DecimalFormat df = new DecimalFormat("0.00");
            String evaluateSplitChildren = "";
            evaluateSplitChildren = df.format(map2.get("6").get(0).getResult2()> 0 ? map2.get("6").get(0).getResult1()/(map2.get("6").get(0).getResult2() *1.000) : 0.00);
            childrenResultMap.put("evaluateSplit", evaluateSplitChildren);
            childrenResultMap.put("all", (Integer) childrenResultMap.get("cancelled") + (Integer) childrenResultMap.get("waitinglist") + (Integer) childrenResultMap.get("waitingorder")
                    + (Integer) childrenResultMap.get("waitingservice")+ (Integer) childrenResultMap.get("waitingpay")+ (Integer) childrenResultMap.get("waitingcomment")
                    + (Integer) childrenResultMap.get("completed")
            );
            resultList.add(childrenResultMap);
        }
        // 结果为空时,自建结果集
        Collections.sort(resultList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Integer map1value = 0;
                Integer map2value = 0;
                if (o1.get("all") != null && o1.get("all") + "" != "") {
                    map1value = (Integer) o1.get("all");
                }
                if (o2.get("all") != null && o2.get("all") + "" != "") {
                    map2value = (Integer) o2.get("all");
                }
                if (map1value - map2value > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value - map2value < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        return new JSONArray(resultList);
    }
    /**
     * 上门服务统计 1.6.8.3 版本
     * @param area
     * @param level
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public Map<String,Object> doorServiceAnalysis(String area, int level, String startDate, String endDate) throws Exception {
        Map<String,Object> resMap = new HashMap<>();
        startDate = statisticsUtilService.getStartDate(startDate,endDate);
        //已服务居民
        long servedPatientNum = statisticsUtilService.getTotalAmountDDLOrZL(startDate,endDate,area,level,"178",null);
        //服务工单
        long serviceOrderNum = statisticsUtilService.getTotalAmountDDLOrZL(startDate,endDate,area,level,"121","5,6");
        //开具处方
        long doorPrescriptionNum = statisticsUtilService.getTotalAmountDDLOrZL(startDate,endDate,area,level,"134",null);
        resMap.put("serviceOrderNum", serviceOrderNum);
        resMap.put("doorPrescriptionNum", doorPrescriptionNum);
        resMap.put("servedPatientNum", servedPatientNum);
        String ddlOrZl = statisticsUtilService.getDDLOrZL(startDate,endDate);
        //服务费用:上门服务的开单以及处方收入费用
        List<SaveModel> priceList = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, "177", ddlOrZl, null, "020", null, null);
        resMap.put("totalPrice", priceList.get(0).getResult1());
        //服务类型
        List<SaveModel> doorServiceTypeList = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, "121", ddlOrZl, null, statisticsUtilService.commonParams, null, null);
        List<Map<String,Object>> doorServiceTypeList2 = new ArrayList<>();
        long patientOrderNum = 0;
        for(SaveModel saveModel:doorServiceTypeList){
            if("3".equals(saveModel.getSlaveKey2())){
                doorServiceTypeList2.add(statisticsUtilService.slaveKay2ToMapLong(saveModel));
            }else{
                patientOrderNum += saveModel.getResult2().longValue();
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", "1");
        map.put("name", "居民自主预约");
        map.put("num", patientOrderNum);
        doorServiceTypeList2.add(map);
        resMap.put("doorServiceTypeList", doorServiceTypeList2);
        //服务人群分析,到达量
        List<SaveModel> voucherList = findDateQuotaLevel1(endDate, endDate, area, level, "133", ddlOrZl, level + "", null);
        List<Map<String,Object>> voucherList2 = new ArrayList<>();
        voucherList.forEach(one->voucherList2.add(statisticsUtilService.slaveKay1ToMapLong(one)));
        resMap.put("voucherList", voucherList2);
        return resMap;
    }
    /**
     * 新增服务工单趋势-v1.6.8.3
     * @param area
     * @param level
     * @param startDate
     * @param endDate
     * @param interval
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> serviceOrderTrend(String area, int level, String startDate, String endDate,String interval) throws Exception {
        List<Map<String,Object>> list = new ArrayList<>();
        //新增服务工单趋势
        List<SaveModel> serviceOrderList = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, "121", SaveModel.timeLevel_ZL, interval, null);
        serviceOrderList.forEach(one->list.add(statisticsUtilService.saveModelToMap(one)));
        return list;
    }
    /**
     * 获取上门服务服务项目分析-v1.6.8.3
     * @param area
     * @param level
     * @param pageSize
     * @param startDate
     * @param endDate
     * @return
     */
    public List<Map<String,Object>> doorServiceItemAnalysis(String area, int level , Integer pageSize, String startDate, String endDate) {
        List<Map<String,Object>> list = new ArrayList<>();
        startDate = statisticsUtilService.getStartDate(startDate,endDate);
        String ddlOrZl = statisticsUtilService.getDDLOrZL(startDate,endDate);
        List<SaveModel> doorServiceTypeList = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, "177", ddlOrZl, "xmijk_quota","020", null, null);
        for (SaveModel saveModel:doorServiceTypeList){
            if(StringUtils.isNoneBlank(saveModel.getSlaveKey1())){
                list.add(statisticsUtilService.slaveKay1ToMapLong2(saveModel));
            }
        }
        statisticsUtilService.sortDoubleList(list,"num");
        if(pageSize == 999){
            return list;
        }else{
            int total = list.size();
            int fromIndex = 0;
            if (pageSize >= total) {
                pageSize = total;
            }
            list =list.subList(fromIndex, pageSize);
        }
        return list;
    }
    /**
     * 获取上门服务合计工单排行
     * @param endDate
     * @param area
     * @param level
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public JSONArray doorServiceOrderLowlevelAll(String startDate, String endDate, String area, int level,String slaveKey1,  String lowLevel) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        startDate = statisticsUtilService.getStartDate(startDate,endDate);
        String ddlOrZl = statisticsUtilService.getDDLOrZL(startDate,endDate);
        //服务工单数
        List<SaveModel> slaveList1 = statisticsUtilService.findDateQuotaLevel0BySlaveKey1(startDate, endDate, area, level, "121", ddlOrZl,null, lowLevel,"5,6");
        //服务费用
        List<SaveModel> slaveList = elasticsearchUtil.findDateQuotaLevel2(startDate, endDate, area, level, "177", ddlOrZl, slaveKey1,"020", null, lowLevel);
        for (SaveModel saveModel:slaveList1){
            Map<String, Object> map = statisticsUtilService.getMapTurnDownResult2(saveModel,lowLevel,"num");
            for (SaveModel one:slaveList){
                if(statisticsUtilService.compareSaveModel(saveModel,one,lowLevel)){
                    map.put("price",one.getResult1());
                    break;
                }
            }
            resultList.add(map);
        }
        statisticsUtilService.sortLongList(resultList,"num");
        return new JSONArray(resultList);
    }
    /**
     * 入户访视统计-获取总量头部-v1.6.8.3
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public JSONObject getHomeVisitTotalHead(String startDate, String endDate, String area, Integer level, String slaveKey1) throws Exception {
        JSONObject object = new JSONObject();
        startDate = statisticsUtilService.getStartDate(startDate, endDate);
        //人数
        long numTotal =  statisticsUtilService.getTotalAmountDDLOrZL(startDate,endDate,area,level,"151",slaveKey1);
        //人次
        long timesTotal =  statisticsUtilService.getTotalAmountDDLOrZL(startDate,endDate,area,level,"150",slaveKey1);
        object.put("numTotal",numTotal);
        object.put("timesTotal",timesTotal);
        return object;
    }
    /**
     * 通用单条折线图趋势-v1.6.8.3
     * @param area
     * @param level
     * @param index 上门服务150
     * @param startDate
     * @param endDate
     * @param interval
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> generalSingleLineChartTrend(String area, int level,String index, String startDate, String endDate,String interval,String slaveKey1) throws Exception {
        List<Map<String,Object>> list = new ArrayList<>();
        //新增服务工单趋势
        List<SaveModel> serviceOrderList = statisticsUtilService.findDateQuotaLevel0BySlaveKey1(startDate,endDate,area,level,index,SaveModel.timeLevel_ZL,interval,slaveKey1);
        serviceOrderList.forEach(one->list.add(statisticsUtilService.saveModelToMap(one)));
        return list;
    }
    /**
     * 通用饼图-v1.6.8.3
     * @param area
     * @param level
     * @param index 上门服务150
     * @param startDate
     * @param endDate
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public List<Map<String,Object>> generalPieChartTrend(String area, int level,String index, String startDate, String endDate,String slaveKey1) throws Exception {
        List<Map<String,Object>> list = new ArrayList<>();
        startDate = statisticsUtilService.getStartDate(startDate, endDate);
        String ddlOrZl = statisticsUtilService.getDDLOrZL(startDate,endDate);
        slaveKey1 = statisticsUtilService.returnSlaveKey(slaveKey1);
        List<SaveModel> serviceOrderList = statisticsUtilService.findDateQuotaLevel1(startDate,endDate,area,level,index,ddlOrZl, slaveKey1,null,null);
        serviceOrderList.forEach(one->list.add(statisticsUtilService.slaveKay1ToMapLong(one)));
        return list;
    }
    /**
     * 通用下砖接口 区-社区-团队-v1.6.8.3
     * @param endDate
     * @param area
     * @param level
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> generalLowlevelAll(String startDate, String endDate, String area, int level,String index,String slaveKey1,  String lowLevel) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        startDate = statisticsUtilService.getStartDate(startDate,endDate);
        String ddlOrZl = statisticsUtilService.getDDLOrZL(startDate,endDate);
        //工单状态列表
        List<SaveModel> slaveList = statisticsUtilService.findDateQuotaLevel0BySlaveKey1(startDate,endDate,area,level,index,ddlOrZl,null,lowLevel, slaveKey1);
        for (SaveModel saveModel:slaveList){
            resultList.add(statisticsUtilService.getMapTurnDownResult2(saveModel,lowLevel,"num"));
        }
        statisticsUtilService.sortLongList(resultList,"num");
        return resultList;
    }
}

+ 662 - 0
svr/svr-door-serivce/src/main/java/com/yihu/jw/door/service/statics/StatisticsUtilService.java

@ -0,0 +1,662 @@
package com.yihu.jw.door.service.statics;
import com.yihu.jw.es.service.StatisticsEsService;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.es.util.SaveModel;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.*;
/**
 * 统计工具类
 * Created by yeshijie on 2020/12/14.
 */
@Service
public class StatisticsUtilService {
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private StatisticsEsService statisticsESService;
    public final String commonParams = "xmijk_quota";
    /**
     * 根据开始时间 结束时间判断查询增量还是到达量
     * @param startDate
     * @param endDate
     * @return
     */
    public String getDDLOrZL(String startDate,String endDate){
        String ddlOrZl = "1";
        if(endDate.equals(startDate)){
            ddlOrZl = SaveModel.timeLevel_DDL;
        }
        return ddlOrZl;
    }
    /**
     * 获取签约开始时间,7月1号
     * @return
     */
    public String getSignStartDay(){
        return DateUtil.getSignYear()+"-07-01";
    }
    /**
     * 如果开始时间是7月1号 就设置为结束时间
     * @param startDate
     * @param endDate
     * @return
     */
    public String getStartDate(String startDate,String endDate){
        if(startDate.equals(getSignStartDay())){
            return endDate;
        }
        return startDate;
    }
    /**
     * 是否是专科
     * @param level
     * @param area
     * @return
     */
    public boolean isSpecialist(int level,String area){
        if(level == 4 && area.length() != 10){
            return true;
        }
        return false;
    }
    /**
     * 获取下转的map
     * @param saveModel
     * @param lowLevel
     * @param result2Name
     * @return
     */
    public Map<String, Object> getMapTurnDownResult2(SaveModel saveModel,String lowLevel,String result2Name){
        Map<String, Object> map = getMapTurnDown(saveModel, lowLevel);
        map.put(result2Name, saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> getMapTurnDownResult12(SaveModel saveModel,String lowLevel,String result1Name,String result2Name){
        Map<String, Object> map = getMapTurnDown(saveModel, lowLevel);
        map.put(result1Name, saveModel.getResult1());
        map.put(result2Name, saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> getMapTurnDown(SaveModel saveModel,String lowLevel){
        Map<String, Object> map = new HashMap<>(16);
        if (SaveModel.OrgLevel.equals(lowLevel)) {
            map.put("code", saveModel.getHospital());
            map.put("name", saveModel.getHospitalName());
        } else if (SaveModel.townLevel.equals(lowLevel)) {
            map.put("code", saveModel.getTown());
            map.put("name", saveModel.getTownName());
        } else if (SaveModel.cityLevel.equals(lowLevel)) {
            map.put("code", saveModel.getCity());
            map.put("name", saveModel.getCityName());
        } else if (SaveModel.deptLevel.equals(lowLevel)) {
            map.put("code", saveModel.getDept());
            map.put("name", saveModel.getDeptName());
        }
        return map;
    }
    public boolean compareSaveModel(SaveModel saveModel1,SaveModel saveModel2,String lowLevel){
        if (SaveModel.OrgLevel.equals(lowLevel)) {
            return saveModel1.getHospital().equals(saveModel2.getHospital());
        } else if (SaveModel.townLevel.equals(lowLevel)) {
            return saveModel1.getTown().equals(saveModel2.getTown());
        } else if (SaveModel.cityLevel.equals(lowLevel)) {
            return saveModel1.getCity().equals(saveModel2.getCity());
        } else if (SaveModel.deptLevel.equals(lowLevel)) {
            return saveModel1.getDept().equals(saveModel2.getDept());
        }
        return false;
    }
    /**
     * 获取到达量或者增量
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param level2_type
     * @return
     * @throws Exception
     */
    public long getTotalAmountDDLOrZL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception{
        if(endDate.equals(startDate)){
            return getTotalAmount3DDL(startDate, endDate, area, level, index, level2_type);
        }
        return getTotalAmount3ZL(startDate, endDate, area, level, index, level2_type);
    }
    public long getTotalAmount3ZL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        SaveModel saveModel = null;
        if (StringUtils.isNotEmpty(level2_type)) {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL, level2_type);
        } else {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_ZL);
        }
        return saveModel.getResult2().longValue();
    }
    public long getTotalAmount3DDL(String startDate, String endDate, String area, int level, String index, String level2_type) throws Exception {
        SaveModel saveModel = null;
        if (StringUtils.isNotEmpty(level2_type)) {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(startDate, endDate, area, level, index, SaveModel.timeLevel_DDL, level2_type);
        } else {
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_DDL);
        }
        return saveModel.getResult2().longValue();
    }
    public Map<String, Object> saveModelToMap(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("range", DateUtil.dateToStr(saveModel.getQuotaDate(), "yyyy-MM-dd"));
        map.put("amount", saveModel.getResult2());
        return map;
    }
    public Map<String, Object> slaveKay1ToMapLong(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey1());
        map.put("name", saveModel.getSlaveKey1Name());
        map.put("num", saveModel.getResult2().longValue());
        return map;
    }
    public Map<String, Object> slaveKay1ToMapLong2(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey1());
        map.put("name", saveModel.getSlaveKey1Name());
        map.put("num", saveModel.getResult2().longValue());
        map.put("price", saveModel.getResult1());
        return map;
    }
    public Map<String, Object> slaveKay2ToMapLong(SaveModel saveModel){
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", saveModel.getSlaveKey2());
        map.put("name", saveModel.getSlaveKey2Name());
        map.put("num", saveModel.getResult2().longValue());
        return map;
    }
    /**
     * 计算开始时间
     * @param endDate
     * @param type 1周,2月
     * @return
     */
    public String calStart(String endDate,String type){
        if(StringUtils.isEmpty(endDate)){
            return endDate;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.strToDate(endDate));
        if("1".equals(type)){
            if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
                cal.add(Calendar.DAY_OF_WEEK,-1);
            }
            cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        }else{
            cal.set(Calendar.DAY_OF_MONTH,1);
        }
        return DateUtil.dateToStrShort(cal.getTime());
    }
    public String getSaveModelCode(int level,SaveModel saveModel){
        if(level == 4){
            return saveModel.getDept();
        }else if(level == 3){
            return saveModel.getHospital();
        }else if(level == 2){
            return saveModel.getTown();
        }
        return null;
    }
    /**
     * 按sortName排序 降序
     * @param resultList
     */
    public void sortDoubleList(List<Map<String,Object>> resultList, String sortName){
        resultList.sort((x,y)->{
            if ( (Double) x.get(sortName) > (Double) y.get(sortName)) {
                return 1;
            } else if ((Double) x.get(sortName) < (Double) y.get(sortName)) {
                return -1;
            } else {
                return 0;
            }
        });
    }
    /**
     *  降序
     * @param resultList
     * @param sortName
     */
    public void sortLongList(List<Map<String,Object>> resultList,String sortName){
        resultList.sort((x,y)->{
            if ( (Long) x.get(sortName) > (Long) y.get(sortName)) {
                return -1;
            } else if ((Long) x.get(sortName) < (Long) y.get(sortName)) {
                return 1;
            } else {
                return 0;
            }
        });
    }
    /**************************************************封装的方法 start ********************************************/
    /**
     * 查询总量
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timelevel
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public long getTotalAmount(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception{
        if(SaveModel.timeLevel_DDL.equals(timelevel)){
            return getTotalAmount3DDL(startDate,endDate,area,level,index,slaveKey1);
        }else {
            return getTotalAmount3ZL(startDate,endDate,area,level,index,slaveKey1);
        }
    }
    /**
     * 查一级指标
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param slaveKey1
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String slaveKey1) throws Exception {
        if(StringUtils.isEmpty(slaveKey1)){
            return elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, timeLevel, interval, null);
        }else {
            return findDateQuotaLevel0BySlaveKey1(startDate,endDate,area,level,index,timeLevel,interval,null,slaveKey1);
        }
    }
    public long getTotalAmountLevel2BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2 ) throws Exception{
        SaveModel saveModel = findOneDateQuotaLevel2BySlaveKey1(startDate, endDate, area, level, index, timeLevel, slaveKey1, slaveKey2);
        return saveModel.getResult1().longValue();
    }
    public SaveModel findOneDateQuotaLevel2BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2) throws Exception {
        if(StringUtils.isEmpty(slaveKey2)){
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2BySlaveKey1(startDate, endDate, area, level, index, timeLevel, slaveKey1, slaveKey2,null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 查找一级或二级维度
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param slaveKey1
     * @param slaveKey2
     * @param interval
     * @param lowLevel
     * @return
     */
    public List findDateQuotaLevel2BySlaveKey1(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
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey2,"slaveKey2","slaveKey2Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        sqlSlaveKey(slaveKey2,"slaveKey2",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     * @param dateTime
     * @return
     */
    public String changeDateTime(String dateTime){
        if (StringUtils.isNotEmpty(dateTime)) {
            if (dateTime.length() > 10) {
                return elasticsearchUtil.changeTime(dateTime);
            } else {
                return elasticsearchUtil.changeDate(dateTime);
            }
        }
        return dateTime;
    }
    public void groupByInterval(String interval,StringBuffer groupBy){
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
    }
    public void sqlArea(StringBuffer sql,String area,int level,boolean isAnd){
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.deptLevel.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 + "'");
            }
            if(isAnd){
                sql.append(" and ");
            }
        }
    }
    public void sqlArea(StringBuffer sql,String area,int level,String index,String timeLevel,String startDate,String endDate){
        sqlArea(sql,area,level,true);
        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 + "'");
        }
    }
    public void sqlSlaveKey(String slaveKey,String slaveKeyName,StringBuffer sql){
        if (StringUtils.isNotBlank(slaveKey)&&!commonParams.equals(slaveKey)) {
            String[] str = slaveKey.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and "+slaveKeyName+" in (" + buffer + ")");
        }
    }
    public void groupBySlaveKey(StringBuffer groupBy,String slaveKeyValue,String slaveKey,String slaveKeyName){
        if (StringUtils.isNotEmpty(slaveKeyValue)||commonParams.equals(slaveKeyValue)) {
            groupBy.append(","+slaveKey+","+slaveKeyName);
        }
    }
    public void sqlGroupBySlaveKey(StringBuffer sql,StringBuffer groupBy,String low_level,String slaveKeyValue,String slaveKey,String slaveKeyName){
        String tmp = "";
        if(StringUtils.isNotBlank(slaveKeyValue)){
            tmp = slaveKey +","+slaveKeyName+",";
        }
        if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select team,teamName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,"+tmp+"sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            groupBySlaveKey(groupBy,slaveKeyValue,slaveKey,slaveKeyName);
        }
    }
    public List findDateQuotaLevel3BySlaveKey13(String startDate, String endDate, String area, int level, String index,
           String timeLevel, String slaveKey1, String slaveKey2,String slaveKey3, String interval, String lowLevel) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        sqlSlaveKey(slaveKey2,"slaveKey2",sql);
        sqlSlaveKey(slaveKey3,"slaveKey3",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public String returnSlaveKey(String slaveKey){
        if(StringUtils.isEmpty(slaveKey)){
            return commonParams;
        }
        return slaveKey;
    }
    /**
     * 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 findDateQuotaLevel0BySlaveKey1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel, String slaveKey1) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public List<SaveModel> 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
        startDate = changeDateTime(startDate);
        endDate = changeDateTime(endDate);
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        sqlGroupBySlaveKey(sql,groupBy,low_level,slaveKey1,"slaveKey1","slaveKey1Name");
        sqlArea(sql,area,level,index,timeLevel,startDate,endDate);
        sqlSlaveKey(slaveKey1,"slaveKey1",sql);
        //根据时间维度分组
        groupByInterval(interval,groupBy);
        sql.append(groupBy);
        return elasticsearchUtil.excute(sql.toString(), SaveModel.class, "", "");
    }
    public List<Map<String, Object>> getDataList(int level,String area,String startDate,String endDate,String quota){
        startDate = getStartDate(startDate, endDate);
        StringBuffer initalStr = new StringBuffer(" where quotaDate >= '" + startDate + "T00:00:00+0800'" + " and quotaDate <= '" + endDate + "T23:59:59+0800'");
        sqlArea(initalStr,area,level,false);
        String ddlOrZl = getDDLOrZL(startDate, endDate);
        String quotaCodeAndWhere = quota.substring(quota.indexOf("quotaCode="));
        String filter = "";
        String quotaCode = "";
        if(quotaCodeAndWhere.contains("-")){
            quotaCode = quotaCodeAndWhere.split("-")[0];
            filter = " and " + quotaCodeAndWhere.split("-")[1];
        }else {
            quotaCode = quotaCodeAndWhere;
        }
        filter += " and " + quotaCode +" and timeLevel = '"+ddlOrZl+"'  and areaLevel='5'";
        String sql="";
        if(level == 3){
            sql = "select sum(result1) result,hospital,hospitalName from  " + esIndex + initalStr.toString() + filter + " group by hospital,hospitalName";
        }else if(level == 2){
            sql = "select sum(result1) result,town,townName from  " + esIndex + initalStr.toString() + filter + " group by town,townName";
        }else{
            sql = "select sum(result1) result,team,teamName from  " + esIndex + initalStr.toString() + filter + " group by team,teamName";
        }
        List<Map<String, Object>> dataList = elasticsearchUtil.excuteDataModel(sql);
        return dataList;
//        teamList = dataListIntegration(totalMap,teamList,dataList,quotaName,range);
    }
    public  List<Map<String, Object>> dataListIntegration( Map<String, Object> totalMap,List<Map<String, Object>>  teamList
            ,List<Map<String, Object>>  dataList,String quotaName,int level){
        DecimalFormat df = new DecimalFormat("###");
        Double total=0.00;
        List<Map<String, Object>>  resultList=new ArrayList<>();
        String teamCloumn = "";
        for(Map<String, Object> teamMap : teamList){
            String teamId;
            if(level == 3){
                teamId = teamMap.get("code").toString();
                teamCloumn = "hospital";
            }else if(level == 2) {
                teamId = teamMap.get("town").toString();
                teamCloumn = "town";
            }else{
                teamId = teamMap.get("id").toString();
                teamCloumn = "team";
            }
            boolean exit = false;
            if(dataList != null && dataList.size() > 0){
                for(Map<String, Object> dataMap : dataList){
                    if(dataMap.get(teamCloumn)!= null && dataMap.get(teamCloumn).toString().equals(teamId)){
                        if(dataMap.get("result") != null){
                            String result = df.format(Double.valueOf(dataMap.get("result").toString()));
                            total=total+Double.valueOf(dataMap.get("result").toString());
                            teamMap.put(quotaName,result);
                            exit = true;
                            break;
                        }else if(dataMap.get("count") != null){
                            String result = df.format(Double.valueOf(dataMap.get("count").toString()));
                            total=total+Double.valueOf(dataMap.get("count").toString());
                            teamMap.put(quotaName,result);
                            exit = true;
                            break;
                        }
                    }
                }
            }
            if( !exit){
                teamMap.put(quotaName,0);
            }
            resultList.add(teamMap);
        }
        totalMap.put(quotaName,df.format(total));
        return resultList;
    }
    /**************************************************封装的方法 end ********************************************/
}

+ 268 - 0
svr/svr-door-serivce/src/main/resource/application.yml

@ -0,0 +1,268 @@
##如果有配置服务的话,远程服务器和本地服务器配置不一致的情况下,优先远程的为主  git上 svr-base ->  git application ->本地 appliction ->本地 bootstarp
server:
  port: 10060
spring:
  jmx:
    default-domain: jkzl_doorService
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50
    max-idle: 50 #最大空闲连接
    min-idle: 10 #最小空闲连接
    validation-query-timeout: 20
    log-validation-errors: true
    validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
    validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
    test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
    test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
    idle-timeout: 30000
    connection-test-query: SELECT 1
    num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
    test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
  data:
    elasticsearch: #ElasticsearchProperties
      cluster-name: jkzl #默认即为elasticsearch  集群名
      cluster-nodes: 172.26.0.115:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
      local: false #是否本地连接
      properties: # Additional properties used to configure the client.
        enable: true
  # JEST (Elasticsearch HTTP client) (JestProperties)
  elasticsearch:
    jest:
      uris: http://172.26.0.112:9200
#      uris: http://172.19.103.68:9200
      connection-timeout: 60000 # Connection timeout in milliseconds.
      multi-threaded: true # Enable connection requests from multiple execution threads.
#      username: # Login user.
#      password: # Login password.
#      proxy.port:  # Proxy port the HTTP client should use.
#      proxy.host:  # Proxy host the HTTP client should use.
#hibernate 配置
hibernate:
  dialect: org.hibernate.dialect.MySQL5Dialect
  show_sql: true
  ejb:
    naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
  physical_naming_strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
  implicit_naming_strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
  connect-timeout: 2 #链接超时时间
  network-timeout: 30
  charset: ISO8859-1 #编码
  http:
    tracker-http-port: 80
    anti-steal-token: no
    secret-key: FastDFS1234567890
  pool: #连接池大小
    init-size: 5
    max-size: 20
    wait-time: 500
basedb: #base数据基础数据数据源,用于跨库查询
  name: wlyy
---
spring:
  profiles: jwdev
  datasource:
    url: jdbc:mysql://172.26.0.104:3306/door_service?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: root
    password: jkzlehr
  redis:
    host: 172.26.0.253 # Redis server host.
    port: 6379 # Redis server port.
fastDFS:
  fastdfs_file_url: http://172.26.0.110:80/
fast-dfs:
  tracker-server: 172.26.0.110:22122
  public-server: http://172.26.0.110:80/
server:
  server_url: http://ehr.yihu.com/wlyy/
neiwang:
  enable: true
  wlyy: http://172.26.0.110:22122/
base:
  url: http://172.17.110.212:10020/
wechat:
  appId: wxd03f859efdf0873d
  appSecret: 2935b54b53a957d9516c920a544f2537
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fweixin.xmtyw.cn%2fwlyy-dev
  accId: gh_ffd64560fb21
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
im:
  im_list_get: http://172.26.0.118:3000/
  #im_list_get: http://192.168.131.24:3000/
  data_base_name: ichat
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
wlyy:
  url: http://ehr.yihu.com/wlyy/
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
demo:
  flag: false
---
spring:
  profiles: jwtest
  datasource:
    url: jdbc:mysql://172.26.0.104/door_service?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
  redis:
    host: 172.26.0.253 # Redis server host.
    port: 6379 # Redis server port.
fastDFS:
  fastdfs_file_url: http://172.26.0.110:80/
fast-dfs:
  tracker-server: 172.26.0.110:22122
  public-server: http://172.26.0.110:80/
server:
  server_url: http://ehr.yihu.com/wlyy/
neiwang:
  enable: true
  wlyy: http://172.26.0.110:22122/
base:
  url: http://172.17.110.212:10020/
wechat:
  appId: wx1f129f7b51701428
  appSecret: 988f005d8309ed1795939e0f042431fb
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fehr.yihu.com%2fwlyy
  accId: gh_ffd64560fb21
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
im:
  im_list_get: http://172.26.0.118:3000/
  data_base_name: im_new
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
wlyy:
  url: http://ehr.yihu.com/wlyy/
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
demo:
  flag: false
express:
  sf_url: https://mrds-admin.sf-express.com:443
  sf_code: WH000101
  sf_check_word: EDSAFWFAQWyjt8099
pay:
  flag: true
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
---
spring:
  profiles: prod
  datasource:
    url: jdbc:mysql://59.61.92.90:9069/wlyy_specialist?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: wlyy
    password: jkzlehr@123
  redis:
    host: 59.61.92.90 # Redis server host.
    port: 9054 # Redis server port.
    password: jkzlehr
fastDFS:
  fastdfs_file_url: http://172.19.103.54:80/
fast-dfs:
  tracker-server: 172.19.103.54:22122
  public-server: http://172.19.103.54:80/
neiwang:
  enable: false
  wlyy: http://59.61.92.90:9099/iot/
server:
  server_url: http://ehr.yihu.com/wlyy/
base:
  url: http://192.168.120.96:10020/svr-base/
wechat:
  appId: wxad04e9c4c5255acf
  appSecret: ae77c48ccf1af5d07069f5153d1ac8d3
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fwlyy
  accId: gh_ffd64560fb21
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
im:
  im_list_get: http://27.155.101.77:3000/
  data_base_name: im
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
wlyy:
  url: http://ehr.yihu.com/wlyy/
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
demo:
  flag: false

+ 0 - 0
svr/svr-door-serivce/src/main/resource/banner.txt


Some files were not shown because too many files changed in this diff