Prechádzať zdrojové kódy

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

yeshijie 4 rokov pred
rodič
commit
a35c48fea8
35 zmenil súbory, kde vykonal 6222 pridanie a 140 odobranie
  1. 1 0
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  2. 167 1
      common/common-entity/sql记录
  3. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java
  4. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java
  5. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java
  6. 12 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/common/BusinessSysDictDO.java
  7. 88 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachCancelLogDO.java
  8. 80 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachConclusionDO.java
  9. 79 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachDoctorStatusDO.java
  10. 193 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachFeeDetailDO.java
  11. 1195 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachOrderDO.java
  12. 89 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachPatientConfirmLogDO.java
  13. 93 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachProcessLogDO.java
  14. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  15. 6 3
      svr/svr-base/src/main/java/com/yihu/jw/base/service/doctor/BaseDoctorService.java
  16. 18 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachCancelLogDao.java
  17. 17 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachConclusionDao.java
  18. 33 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachDoctorStatusDao.java
  19. 39 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachFeeDetailDao.java
  20. 50 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachOrderDao.java
  21. 14 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachPatientConfirmLogDao.java
  22. 21 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachProcessLogDao.java
  23. 471 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java
  24. 89 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/PatientDoorCoachOrderController.java
  25. 146 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/HospitalService.java
  26. 165 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/ServerPackageService.java
  27. 46 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/WlyySystemDictService.java
  28. 84 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultTeamService.java
  29. 861 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java
  30. 1085 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java
  31. 272 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/prescription/PresModeAdapter.java
  32. 0 43
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java
  33. 667 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsUtilService.java
  34. 95 90
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java
  35. 42 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/StreamUtil.java

+ 1 - 0
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -247,6 +247,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        }
        BasePatientDO basePatientDO1 = basePatientDao.findById(basePatientDO.getId());
        if (null!=basePatientDO1){
            basePatientDO1.setName(basePatientDO.getName());
            basePatientDO1.setMobile(basePatientDO.getMobile());
            basePatientDO1.setIdcard(basePatientDO.getIdcard());

+ 167 - 1
common/common-entity/sql记录

@ -649,4 +649,170 @@ CREATE TABLE `wlyy_devices` (
  `neighborhood_committee_name` varchar(100) DEFAULT NULL COMMENT '居委会名称',
  PRIMARY KEY (`id`),
  KEY `idx_device_code` (`device_code`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='厦门设备信息表';
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='厦门设备信息表';
-- 2021-05-12 lb
alter table base.base_business_sys_dict add column org_code varchar(50) default null comment '归属机构';
-- 2021-05-13 lb
CREATE TABLE `base_door_coach_order` (
  `id` varchar(50) NOT NULL DEFAULT '',
  `number` varchar(50) DEFAULT NULL COMMENT '服务编号',
  `proxy_patient` varchar(50) DEFAULT NULL COMMENT '代理发起工单的居民code,替父母,孩子等发起工单',
  `proxy_patient_name` varchar(10) DEFAULT NULL COMMENT '代理发起工单的居民code,替父母,孩子等发起工单',
  `proxy_patient_phone` varchar(15) DEFAULT NULL COMMENT '代理发起工单的居民联系电话',
  `patient` varchar(50) DEFAULT NULL COMMENT '被服务的居民code,发起工单的居民的亲属',
  `patient_name` varchar(10) DEFAULT NULL COMMENT '被服务的居民姓名,发起工单的居民的亲属',
  `patient_phone` varchar(15) DEFAULT NULL COMMENT '被服务的居民联系电话',
  `patient_relation` varchar(10) DEFAULT NULL COMMENT '发起人与被服务人的关系:自己,父亲,母亲,儿子等',
  `dispatcher` varchar(50) DEFAULT NULL COMMENT '调度员code',
  `dispatcher_name` varchar(50) DEFAULT NULL COMMENT '调度员name',
  `patient_expected_serve_time` varchar(200) DEFAULT NULL COMMENT '居民期望服务时间',
  `serve_desc` varchar(200) DEFAULT NULL COMMENT '居民自己服务描述',
  `serve_town` varchar(100) DEFAULT NULL COMMENT '上门服务的区',
  `serve_address` varchar(100) DEFAULT NULL COMMENT '上门服务详细地址',
  `serve_lat` varchar(100) DEFAULT NULL COMMENT '上门服务地址纬度',
  `serve_lon` varchar(100) DEFAULT NULL COMMENT '上门服务地址经度',
  `remark` varchar(200) DEFAULT NULL COMMENT '调度员备注',
  `is_patient_confirm` int(1) DEFAULT NULL COMMENT '居民对工单需要服务情况是否已确认,0-未确认,1-已确认 2-不同意',
  `patient_confirm_time` timestamp NULL DEFAULT NULL COMMENT '居民对工单需要服务情况确认时间',
  `is_trans_other_org` int(1) DEFAULT NULL COMMENT '工单是否转给其他机构,0-不转,1-已转',
  `transed_org_code` varchar(50) DEFAULT NULL COMMENT '最后转接的机构code',
  `transed_dispatcher` varchar(50) DEFAULT NULL COMMENT '最后转接的机构调度员code',
  `transed_dispatcher_name` varchar(50) DEFAULT NULL COMMENT '最后转接的机构调度员name',
  `total_fee` decimal(10,2) DEFAULT NULL COMMENT '服务总的支付费用',
  `doctor` varchar(50) DEFAULT NULL COMMENT '接单的医生code',
  `doctor_name` varchar(50) DEFAULT NULL COMMENT '接单的医生name',
  `doctor_type` varchar(50) DEFAULT NULL COMMENT '接单的医生类型:医生,健管师,护士等',
  `doctor_arriving_time` varchar(200) DEFAULT NULL COMMENT '医生预计到达时间',
  `doctor_sign_time` timestamp NULL DEFAULT NULL COMMENT '医生签到时间',
  `doctor_sign_way` int(1) DEFAULT NULL COMMENT '医生签到方式:1-定位,2-扫码,3-拍照',
  `doctor_sign_location` varchar(50) DEFAULT NULL COMMENT '医生签到位置,记录详细地址',
  `doctor_sign_img` varchar(3000) DEFAULT NULL COMMENT '医生签到照片',
  `patient_confirm_finish_way` int(1) DEFAULT NULL COMMENT '居民确认结束服务方式:1-电子签名,2-手持身份证拍照',
  `patient_confirm_finish_img` varchar(200) DEFAULT NULL COMMENT '居民确认结束服务照片',
  `patient_confirm_finish_time` timestamp NULL DEFAULT NULL COMMENT '居民确认医生结束服务时间',
  `present_imgs` varchar(3000) DEFAULT NULL COMMENT '医生诊疗现场照片,最多9张,逗号分隔',
  `exam_paper_status` int(1) DEFAULT NULL COMMENT '是否需要上传补录报告:0-不需要,1-需要,待补录;2-需要,已补录',
  `exam_paper_imgs` varchar(3000) DEFAULT NULL COMMENT '医生上传居民的化验检查报告照片',
  `exam_paper_upload_time` timestamp NULL DEFAULT NULL COMMENT '化验检查报告补录时间',
  `exam_paper_upload_way` int(1) DEFAULT NULL COMMENT '化验检查报告补录方式,1-拍照补录,2-接口数据',
  `status` int(1) DEFAULT NULL COMMENT '工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-已接单,4-签到,5-登记服务小结,6-已完成',
  `complete_time` timestamp NULL DEFAULT NULL COMMENT '工单完成时间(对工单评价完即工单完成)',
  `cancel_type` int(1) DEFAULT NULL COMMENT '取消类型:1-调度员取消,2-居民取消,3-医生取消',
  `cancel_reason` varchar(200) DEFAULT NULL COMMENT '取消理由',
  `cancel_time` timestamp NULL DEFAULT NULL COMMENT '取消时间',
  `pay_way` int(1) DEFAULT NULL COMMENT '付款方式:1-微信支付,2-线下支付(居民自己向医院支付,具体怎么支付由医院来定)',
  `pay_number` varchar(100) DEFAULT NULL COMMENT '支付流水号',
  `pay_time` timestamp NULL DEFAULT NULL COMMENT '支付时间',
  `dispatcher_response_time` timestamp NULL DEFAULT NULL COMMENT '调度员响应时间(派单时间或取消时间)',
  `service_response_time` timestamp NULL DEFAULT NULL COMMENT '服务医生响应时间(第一条咨询或者接单时间)',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者名称',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  `expected_doctor_name` varchar(10) DEFAULT '' COMMENT '居民期望服务的医生姓名',
  `hospital` varchar(50) DEFAULT NULL COMMENT '服务机构',
  `conclusion_status` int(1) DEFAULT NULL COMMENT '服务小结登记状态:1待补录;2-已补录',
  `prescription_status` int(1) DEFAULT NULL COMMENT '开方状态:1已完成,0未开方',
  `prescription_code` varchar(100) DEFAULT NULL COMMENT '处方单号,多个用逗号隔开',
  `prescription_time` timestamp NULL DEFAULT NULL COMMENT '开方完成时间',
  `outpatient_id` varchar(50) DEFAULT NULL COMMENT '关联门诊记录',
  `type` tinyint(2) DEFAULT '1' COMMENT '发起类型(1本人发起 2家人待预约 3医生代预约)',
  `authorize_image` varchar(500) DEFAULT NULL COMMENT '电子健康卡授权图片',
  `relation_code` varchar(50) DEFAULT NULL COMMENT '业务关联',
  `service_status` varchar(15) DEFAULT NULL COMMENT '服务类型 1-预约项目 2-即时项目',
  `order_info` varchar(15) DEFAULT NULL COMMENT '工单详情 0-未推送 1-未确认 2-已确认',
  `shortcut_type` char(1) DEFAULT NULL COMMENT '快捷类型,1是快捷类型,其他值不是',
  `followup_date` varchar(50) DEFAULT NULL COMMENT '随访时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导服务工单';
CREATE TABLE `base_door_coach_fee_detail` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) DEFAULT NULL COMMENT '工单id',
  `type` int(1) NOT NULL COMMENT '费用类型,1-服务项费用,2-医生出诊费用',
  `code` varchar(50) DEFAULT NULL COMMENT '居民请求的服务项code,医生出诊费用code',
  `name` varchar(50) DEFAULT NULL COMMENT '居民请求的服务项名称,医生出诊费用名称',
  `fee` decimal(10,2) DEFAULT NULL COMMENT '费用',
  `fee_discount` decimal(10,2) DEFAULT NULL COMMENT '折扣费用',
  `number` int(1) DEFAULT NULL COMMENT '数量',
  `status` int(1) NOT NULL COMMENT '状态,1-居民新增(预约),2-医生新增,3-医生删除',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者名称',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  `pay_status` tinyint(1) DEFAULT NULL COMMENT '付款状态:0未付款 1已付款',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导服务工单价格明细(服务项价格,医生出诊费用)';
CREATE TABLE `base_door_coach_doctor_status` (
  `id` varchar(50) NOT NULL,
  `doctor` varchar(50) NOT NULL COMMENT '医生code',
  `status` int(1) NOT NULL DEFAULT '1' COMMENT '医生状态:1-待派单,2-待接单,3-待服务,4-服务中,5-停止接单',
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '转接时间',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='医生上门辅导服务工单状态情况';
CREATE TABLE `base_door_coach_process_log` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `status` int(1) NOT NULL COMMENT '工单处理状态',
  `dispatcher` varchar(50) DEFAULT NULL COMMENT '变更状态的调度员',
  `dispatcher_name` varchar(50) DEFAULT NULL COMMENT '变更状态的调度员姓名',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导工单状态变更记录(调度员操作记录)';
CREATE TABLE `base_door_coach_conclusion` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `patient` varchar(50) DEFAULT NULL COMMENT '工单服务的居民',
  `patient_name` varchar(50) DEFAULT NULL COMMENT '居民姓名',
  `doctor` varchar(50) DEFAULT NULL COMMENT '医生',
  `doctor_name` varchar(50) DEFAULT NULL COMMENT '医生姓名',
  `conclusion` varchar(2000) DEFAULT NULL COMMENT '处置小结',
  `conclusion_img` varchar(1000) DEFAULT NULL COMMENT '服务相关附件',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `orderId` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导工单服务小结';
CREATE TABLE `base_door_coach_patient_confirm_log` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `patient` varchar(50) NOT NULL COMMENT '居民',
  `patient_name` varchar(50) NOT NULL COMMENT '居民姓名',
  `type` int(1) NOT NULL COMMENT '确认操作类型:1-确认基础信息无误或变更,2-确认上门医生变更上门信息,3-同意工单转接',
  `description` varchar(200) DEFAULT NULL COMMENT '操作描述',
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '转接时间',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导服务工单居民确认操作日志记录';
CREATE TABLE `base_door_coach_cancel_log` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `patient` varchar(50) NOT NULL COMMENT '居民code',
  `cancel_type` int(1) NOT NULL COMMENT '取消类型:1-调度员取消,2-居民取消',
  `cancel_reason` varchar(50) DEFAULT NULL COMMENT '取消理由',
  `time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '取消时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上门辅导工单取消记录';

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java

@ -284,7 +284,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    private String visitTime;
    /**
     * 类型 1社区医生,2助老员 3 教师
     * 类型 1社区医生,2助老员, 3教师
     */
    private Integer level;
    private String doctorLat;//医生当前定位地址纬度

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

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

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java

@ -279,6 +279,7 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
    private String bloodName;
    private String marriageName;
    public String getCardType() {
        return cardType;
    }

+ 12 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/common/BusinessSysDictDO.java

@ -54,6 +54,10 @@ public class BusinessSysDictDO extends UuidIdentityEntityWithTime {
     * 备用字段2
     */
    private String ext2;
    /**
     * 归属机构
     */
    private String orgCode;
    @Column(name = "model_name")
    public String getModelName() {
@ -129,4 +133,12 @@ public class BusinessSysDictDO extends UuidIdentityEntityWithTime {
    public void setExt2(String ext2) {
        this.ext2 = ext2;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
}

+ 88 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachCancelLogDO.java

@ -0,0 +1,88 @@
package com.yihu.jw.entity.care.doorCoach;
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;
/**
* 上门辅导工单取消记录实体
*/
@Entity
@Table(name = "base_door_coach_cancel_log")
public class BaseDoorCoachCancelLogDO 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;
    }
}

+ 80 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachConclusionDO.java

@ -0,0 +1,80 @@
package com.yihu.jw.entity.care.doorCoach;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 上门辅导工单服务小结
 *
 */
@Entity
@Table(name = "base_door_coach_conclusion")
public class BaseDoorCoachConclusionDO extends UuidIdentityEntityWithOperator {
    private String orderId;//工单id
    private String patient;//工单服务的居民
    private String patientName;//居民姓名
    private String doctor;//医生
    private String doctorName;//医生姓名
    private String conclusion;//处置小结
    private String conclusionImg;//附件
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    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 getConclusion() {
        return conclusion;
    }
    public void setConclusion(String conclusion) {
        this.conclusion = conclusion;
    }
    public String getConclusionImg() {
        return conclusionImg;
    }
    public void setConclusionImg(String conclusionImg) {
        this.conclusionImg = conclusionImg;
    }
}

+ 79 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachDoctorStatusDO.java

@ -0,0 +1,79 @@
package com.yihu.jw.entity.care.doorCoach;
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 = "base_door_coach_doctor_status")
public class BaseDoorCoachDoctorStatusDO 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;
    }
}

+ 193 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachFeeDetailDO.java

@ -0,0 +1,193 @@
package com.yihu.jw.entity.care.doorCoach;
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 = "base_door_coach_fee_detail")
public class BaseDoorCoachFeeDetailDO 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;
    /**
     * 付款状态:0未付款 1已付款
     */
    private Integer payStatus;
	@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;
    }
    @Column(name = "pay_status")
    public Integer getPayStatus() {
        return payStatus;
    }
    public void setPayStatus(Integer payStatus) {
        this.payStatus = payStatus;
    }
}

+ 1195 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachOrderDO.java

@ -0,0 +1,1195 @@
package com.yihu.jw.entity.care.doorCoach;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import com.yihu.jw.entity.door.WlyyDoorConclusionDO;
import com.yihu.jw.entity.door.WlyyDoorDoctorDO;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
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 = "base_door_coach_order")
public class BaseDoorCoachOrderDO 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 BaseDoorCoachConclusionDO 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;//处方单号,多个用逗号隔开
    private String outpatientId;//复诊id
    @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<WlyyPrescriptionDO> prescriptionDOList;//上门前开的方
    private List<WlyyPrescriptionDO> afterPrescriptionList;//上门后开的方
    private List<Followup> followupList;//上门随访
    private String followupDate;//随访时间
    /**
     * 快捷类型,1是快捷类型,其他值不是
     */
    private String shortcutType;
    @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<Map<String, Object>> getDoctors() {
        return doctors;
    }
    public void setDoctors(List<Map<String, Object>> doctors) {
        this.doctors = doctors;
    }
    @Transient
    public BaseDoorCoachConclusionDO getDoorConclusion() {
        return doorConclusion;
    }
    public void setDoorConclusion(BaseDoorCoachConclusionDO 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;
    }
    @Transient
    public List<Followup> getFollowupList() {
        return followupList;
    }
    public void setFollowupList(List<Followup> followupList) {
        this.followupList = followupList;
    }
    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;
    }
    @Column(name = "outpatient_id")
    public String getOutpatientId() {
        return outpatientId;
    }
    public void setOutpatientId(String outpatientId) {
        this.outpatientId = outpatientId;
    }
    @Column(name = "followup_date")
    public String getFollowupDate() {
        return followupDate;
    }
    public void setFollowupDate(String followupDate) {
        this.followupDate = followupDate;
    }
}

+ 89 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachPatientConfirmLogDO.java

@ -0,0 +1,89 @@
package com.yihu.jw.entity.care.doorCoach;
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 = "base_door_coach_patient_confirm_log")
public class BaseDoorCoachPatientConfirmLogDO 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;
    }
}

+ 93 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/doorCoach/BaseDoorCoachProcessLogDO.java

@ -0,0 +1,93 @@
package com.yihu.jw.entity.care.doorCoach;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
/**
* 工单状态变更记录(调度员操作记录)实体
*
* @author Administrator on  2019年04月09日
*
*/
@Entity
@Table(name = "base_door_coach_process_log")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_door_process_log")
public class BaseDoorCoachProcessLogDO 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;
    }
}

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

@ -18,7 +18,7 @@ import java.util.Date;
public class SystemMessageDO extends UuidIdentityEntity {
    /**
     *消息类型 上门服务400开头,生活照料500开头 ,安防监控600开头
     *消息类型 上门服务400开头,生活照料500开头 ,安防监控600开头, 上门辅导700开头
     */
    private String type;
    /**

+ 6 - 3
svr/svr-base/src/main/java/com/yihu/jw/base/service/doctor/BaseDoctorService.java

@ -566,9 +566,12 @@ public class BaseDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDa
                        }
                    }
                }
                doctorMappingDO.setOrgCode(orgCode);
                doctorMappingDO.setOrgName(orgName);
                doctorMappingDao.save(doctorMappingDO);
                if(doctorMappingDO!=null){
                    doctorMappingDO.setOrgCode(orgCode);
                    doctorMappingDO.setOrgName(orgName);
                    doctorMappingDao.save(doctorMappingDO);
                }
            } catch (IOException e) {
                result.put("msg", "convert hospital jsonObject to baseDoctorHospitalDO failed," + e.getCause());
                result.put("response", ConstantUtils.FAIL);

+ 18 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachCancelLogDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachCancelLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 工单取消记录 数据库访问层
 *
 */
public interface BaseDoorCoachCancelLogDao extends PagingAndSortingRepository<BaseDoorCoachCancelLogDO, String>, JpaSpecificationExecutor<BaseDoorCoachCancelLogDO>  {
    @Query(value = "select count(cl.id) from base_door_coach_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);
}

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

@ -0,0 +1,17 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachConclusionDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/4/7.
 */
public interface BaseDoorCoachConclusionDao extends PagingAndSortingRepository<BaseDoorCoachConclusionDO,String>,
        JpaSpecificationExecutor<BaseDoorCoachConclusionDO> {
    @Query("select c from BaseDoorCoachConclusionDO c where c.orderId = ?1")
    BaseDoorCoachConclusionDO findByOrderId(String orderId);
}

+ 33 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachDoctorStatusDao.java

@ -0,0 +1,33 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachDoctorStatusDO;;
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 BaseDoorCoachDoctorStatusDao extends PagingAndSortingRepository<BaseDoorCoachDoctorStatusDO, String>, JpaSpecificationExecutor<BaseDoorCoachDoctorStatusDO>  {
    BaseDoorCoachDoctorStatusDO findByDoctor(String doctor);
    BaseDoorCoachDoctorStatusDO queryByDoctorAndStatusIn(String doctor, Integer[] status);
    List<BaseDoorCoachDoctorStatusDO> queryByStatusIn(Integer[] status, Pageable pageable);
    Integer countByStatusIn(Integer[] status);
    boolean existsByDoctorAndStatusIn(String doctor, Integer[] status);
}

+ 39 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachFeeDetailDao.java

@ -0,0 +1,39 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachFeeDetailDO;
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.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 BaseDoorCoachFeeDetailDao extends PagingAndSortingRepository<BaseDoorCoachFeeDetailDO, String>, JpaSpecificationExecutor<BaseDoorCoachFeeDetailDO>  {
    @Query("select d from BaseDoorCoachFeeDetailDO d where d.orderId = ?1 and d.type=?2 and d.status <> 3")
    List<BaseDoorCoachFeeDetailDO> findByOrderIdAndType(String orderId, Integer type);
    @Query("select d from BaseDoorCoachFeeDetailDO d where d.orderId = ?1 and d.payStatus=?2 and d.status <> 3")
    List<BaseDoorCoachFeeDetailDO> findByOrderIdAndPayStatus(String orderId, Integer payStatus);
    @Query("select d.id as id,d.fee as fee,d.orderId as orderId from BaseDoorCoachFeeDetailDO d where d.code in(:codes) and d.type = :type")
    List<Map<String,Object>> findIdByCodeAndType(@Param("codes") List<String> codes, @Param("type") Integer type);
    @Modifying
    @Query("update BaseDoorCoachFeeDetailDO  set payStatus = 1 where id in (?1) ")
    int updatePayStatusById(String[] ids);
}

+ 50 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachOrderDao.java

@ -0,0 +1,50 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
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 BaseDoorCoachOrderDao extends PagingAndSortingRepository<BaseDoorCoachOrderDO, String>, JpaSpecificationExecutor<BaseDoorCoachOrderDO>  {
    boolean existsByPatientAndStatusNot(String patient, int status);
    boolean existsByPatientAndStatusIn(String patient, Integer[] status);
    @Modifying
    @Transactional
    @Query("update BaseDoorCoachOrderDO o set o.conclusionStatus = 1 where o.id = ?1")
    void updateConclusionStatus(String orderId);
    @Query("select o from BaseDoorCoachOrderDO o where o.doctor = ?1 and o.status in (2,3)")
    List<BaseDoorCoachOrderDO> getNotFinishOrderByDoctor(String doctor);
    @Modifying
    @Transactional
    @Query("update BaseDoorCoachOrderDO 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 BaseDoorCoachOrderDO o where o.prescriptionCode like ?1 and o.status <> -1 ")
    List<BaseDoorCoachOrderDO> findByPrescriptionCode(String prescriptionCode);
    @Query("select o from BaseDoorCoachOrderDO o where o.relationCode = ?1 order by o.createTime desc")
    List<BaseDoorCoachOrderDO> findByRelationCode(String relationCode);
}

+ 14 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachPatientConfirmLogDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachPatientConfirmLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 上门辅导服务工单居民确认操作日志记录
 *
 */
public interface BaseDoorCoachPatientConfirmLogDao extends PagingAndSortingRepository<BaseDoorCoachPatientConfirmLogDO, String>, JpaSpecificationExecutor<BaseDoorCoachPatientConfirmLogDO>  {
}

+ 21 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/doorCoach/BaseDoorCoachProcessLogDao.java

@ -0,0 +1,21 @@
package com.yihu.jw.care.dao.doorCoach;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachDoctorStatusDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachProcessLogDO;
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 BaseDoorCoachProcessLogDao extends PagingAndSortingRepository<BaseDoorCoachProcessLogDO, String>, JpaSpecificationExecutor<BaseDoorCoachProcessLogDO>  {
}

+ 471 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java

@ -0,0 +1,471 @@
package com.yihu.jw.care.endpoint.doorCoach;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.doorCoach.DoctorDoorCoachOrderService;
import com.yihu.jw.care.service.doorCoach.PatientDoorCoachOrderService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachConclusionDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 上门辅导
 *
 */
@RestController
@RequestMapping(value = "/doctor/doorCoach/serviceOrder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-上门辅导")
public class DoctorDoorCoachOrderController extends BaseController {
    @Autowired
    private PatientDoorCoachOrderService patientDoorCoachOrderService;
    @Autowired
    private DoctorDoorCoachOrderService doctorDoorCoachOrderService;
    @PostMapping(value = "proxyCreate")
    @ApiOperation(value = "创建上门服务咨询--医生代预约")
    public String create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        try{
            JSONObject result = patientDoorCoachOrderService.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());
        }
    }
    @GetMapping("/getDoorOrderNum")
    @ApiOperation(value = "获取医生待服务工单数量")
    public String getDoorOrderNum(
            @ApiParam(name = "doctor", value = "医生codedoctor")
            @RequestParam(value = "doctor", required = true) String doctor) {
        try {
            return write(200, "获取成功", "data",doctorDoorCoachOrderService.getDoorOrderNum(doctor));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @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 = patientDoorCoachOrderService.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 = patientDoorCoachOrderService.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 = "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 = patientDoorCoachOrderService.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("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 = false) @RequestParam(value = "jobCode", required = true) String jobCode,
            @ApiParam(value = "医生职称", name = "jobCodeName", required = false) @RequestParam(value = "jobCodeName", required = true) String jobCodeName,
            @ApiParam(value = "医院级别", name = "hospitalLevel", required = false) @RequestParam(value = "hospitalLevel", required = false) int hospitalLevel) {
        try {
            doctorDoorCoachOrderService.acceptOrder(orderId,jobCode,jobCodeName,hospitalLevel);
            return write(200, "操作成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @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 {
            doctorDoorCoachOrderService.refuseOrder(getUID(),orderId, reason);
            return write(200, "操作成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @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 = patientDoorCoachOrderService.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("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 {
            BaseDoorCoachOrderDO baseDoorCoachOrderDO = doctorDoorCoachOrderService.signIn(orderId, signTime, signWay, signLocation, signImg,twoDimensionalCode,getUID());
            if (baseDoorCoachOrderDO != null){
                return write(200, "操作成功", "data", baseDoorCoachOrderDO);
            }else {
                return error(-1,"扫码签到失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!" + e.getMessage());
        }
    }
    @PostMapping("updateDoorConclusion")
    @ApiOperation("编辑保存服务工单小结")
    public String updateDoorConclusion(
            @ApiParam(value = "服务附件,至少一张,至多3张", name = "orderId",required = true)
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "服务附件,至少一张,至多3张", name = "conclusionImg",required = true)
            @RequestParam(value = "conclusionImg", required = true) String conclusionImg,
            @ApiParam(value = "服务小结", name = "conclusion",required = true)
            @RequestParam(value = "conclusion", required = true) String conclusion,
            @ApiParam(value = "服务小结是否登记,1跳过登记;2-登记", name = "conclusionStatus")
            @RequestParam(value = "conclusionStatus", required = false,defaultValue = "2") Integer conclusionStatus) {
        try {
            BaseDoorCoachConclusionDO doorConclusion = doctorDoorCoachOrderService.updateDoorConclusion(orderId,conclusion,conclusionImg,conclusionStatus);
            return write(200, "保存成功", "data", doorConclusion);
        } 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 = doctorDoorCoachOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return error(204, "获取失败,该医生暂无工单" );
                }
            }
            // 根据orderId查询工单小结表
            BaseDoorCoachConclusionDO doorConclusion = doctorDoorCoachOrderService.getDoorConclusion(orderId);
            return write(200, "获取成功", "data", doorConclusion);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @PostMapping("saveOrderFinishByDoctor")
    @ApiOperation(value = "确认完成工单")
    public String saveOrderFinishByDoctor(
            @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) {
        try {
            return write(200, "获取成功", "data", doctorDoorCoachOrderService.saveOrderFinishByDoctor(orderId, finishWay, finishImg));
        } 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 {
            BaseDoorCoachOrderDO baseDoorCoachOrderDO = doctorDoorCoachOrderService.updateArrivingTime(orderId, arrivingTime);
            return write(200, "修改成功", "data", baseDoorCoachOrderDO);
        } 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) {
        try {
            Map<String, Integer> map = doctorDoorCoachOrderService.getNumGroupByStatus(doctor);
            return write(200, "获取成功", "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @GetMapping("/getDoorOrderList")
    @ApiOperation(value = "服务工单列表")
    public String getDoorOrderList(
            @ApiParam(value = "工单服务编号", 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 = "发起类型(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 = doctorDoorCoachOrderService.getDoorOrderList(orderId,patientName,patientPhone,hospitalCode,
                    ss,createTimeStart,createTimeEnd,serverDoctorName,doctorCode,page,pageSize, type);
            return write(200, "获取成功","data",result);
        } catch (Exception e) {
            e.printStackTrace();
            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) {
        try {
            // 没有提供工单id的情况下,则获取该医生当前最新一条的工单
            if (StringUtils.isEmpty(orderId)) {
                // 根据接单医生code获取最近一次服务orderId
                orderId = doctorDoorCoachOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return error(-1, "获取失败, 该医生暂无工单" );
                }
            }
            // 根据orderId获取工单信息
            BaseDoorCoachOrderDO baseDoorCoachOrderDO = doctorDoorCoachOrderService.getDoorServiceOrderById(orderId);
            return write(200, "获取成功", "data", baseDoorCoachOrderDO);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败, 该医生暂无工单!" + e.getMessage());
        }
    }
    @PostMapping("/initDoorStatus")
    @ApiOperation(value = "初始化医生分派订单开关状态")
    public String initDoorStatus() {
        try {
            doctorDoorCoachOrderService.initDoorStatus();
            return success("成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!" + e.getMessage());
        }
    }
    @GetMapping("/getDispatchOrderSwitch")
    @ApiOperation(value = "获取医生分派订单开关状态")
    public String getDispatchOrderSwitch(
            @ApiParam(name = "doctor", value = "医生codedoctor")
            @RequestParam(value = "doctor", required = true) String doctor) {
        try {
            String status = doctorDoorCoachOrderService.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 {
            doctorDoorCoachOrderService.updateDispatchStatusByDoctor(doctor, value);
            return write(200, "修改成功");
        } 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",doctorDoorCoachOrderService.urlAnalysis(url));
        }catch (Exception e){
            //日志文件中记录异常信息
            error(e);
            //返回接口异常信息处理结果
            return error(-1, "操作失败!");
        }
    }
}

+ 89 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/PatientDoorCoachOrderController.java

@ -0,0 +1,89 @@
package com.yihu.jw.care.endpoint.doorCoach;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.doorCoach.PatientDoorCoachOrderService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * 上门辅导服务工单控制器
 *
 */
@RestController
@RequestMapping(value = "/patient/doorCoach/serviceOrder")
@Api(value = "居民端-上门辅导", description = "居民端-上门辅导")
public class PatientDoorCoachOrderController extends EnvelopRestEndpoint {
    @Autowired
    private PatientDoorCoachOrderService patientDoorCoachOrderService;
    @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 = patientDoorCoachOrderService.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 = patientDoorCoachOrderService.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);
    }
    @PostMapping(value = "delete")
    @ApiOperation(value = "删除")
    public Envelop delete(
            @ApiParam(name = "ids", value = "id串,中间用,分隔", required = true) @RequestParam(value = "ids") String ids) {
        patientDoorCoachOrderService.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 = patientDoorCoachOrderService.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 = "orgCode", value = "机构Code") @RequestParam(value = "orgCode", required = true) String orgCode) {
        JSONObject result = patientDoorCoachOrderService.queryDispatcherInfoByPatient(orgCode);
        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));
    }
}

+ 146 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/HospitalService.java

@ -0,0 +1,146 @@
package com.yihu.jw.care.service.common;
import com.yihu.jw.entity.base.system.SystemDictEntryDO;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.util.date.DateUtil;
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.Date;
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;
    @Autowired
    private WlyySystemDictService systemDictService;
    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 ";
        }*/
        String sql = "SELECT d.id," +
                " d.id name,d.name,h.org_code hospital,h.org_name hospital_name, " +
                " h.dept_name,d.job_title_code job,d.job_title_name job_name,d.photo,d.expertise,d.introduce " +
                "FROM base_doctor d, base_doctor_hospital h " +
                "WHERE d.id = h.doctor_code AND h.del = 1 AND d.del = 1";
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNoneEmpty(hospital)) {
            sql += " and h.org_code =? ";
            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<>();
        String startWorkingTimeAm = null ;
        String stopWorkingTimeAm = null ;
        String startWorkingTimePm = null ;
        String stopWorkingTimePm = null;
                List<SystemDictEntryDO> systemDictEntryDOList = systemDictService.getDictByDictName("350211A1002_org_work_time");
        for (SystemDictEntryDO dictEntryDO:systemDictEntryDOList){
            if("startAm".equals(dictEntryDO.getCode())){
                startWorkingTimeAm = dictEntryDO.getValue();
            }else  if("stopAm".equals(dictEntryDO.getCode())){
                stopWorkingTimeAm = dictEntryDO.getValue();
            }else  if("startPm".equals(dictEntryDO.getCode())){
                startWorkingTimePm = dictEntryDO.getValue();
            }else  if("stopPm".equals(dictEntryDO.getCode())){
                stopWorkingTimePm = dictEntryDO.getValue();
            }
        }
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        int amCount = 0;
        //获取机构早上上班时间
        if(StringUtils.isNotBlank(startWorkingTimeAm) && StringUtils.isNotBlank(stopWorkingTimeAm)) {
            String startWorkTime = startWorkingTimeAm;
            String stopWokingTime = stopWorkingTimeAm;
            Date startWokingTimeAm = DateUtil.strToDate(startWorkingTimeAm, "HH:mm");
            Date stopWokingTimeAm = DateUtil.strToDate(stopWorkingTimeAm, "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));
                    startWorkTime = DateUtil.getNextMin(startWorkTime, 30);
                }else {
                    result.add(startWorkTime + "-" + stopWokingTime);
                }
            }
        }
        //获取机构下午上班时间
        if(StringUtils.isNotBlank(startWorkingTimePm) && StringUtils.isNotBlank(stopWorkingTimePm)) {
            String startWorkTime = startWorkingTimePm;
            String stopWokingTime = stopWorkingTimePm;
            Date startWokingTimePm = DateUtil.strToDate(startWorkingTimePm, "HH:mm");
            Date stopWokingTimePm = DateUtil.strToDate(stopWorkingTimePm, "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;
    }
}

+ 165 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/ServerPackageService.java

@ -0,0 +1,165 @@
package com.yihu.jw.care.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.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.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by wzn54 on 2019/3/19.
 */
@Service
@Transactional
public class ServerPackageService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${wechat.id}")
    private String wxId;
    /**
     * 根据机构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 = "";
        if("sd_tnzyy_wx".equals(wxId)){
            if("door".equals(type)){
                //上门护理
                sql = "SELECT code,value title,'' unit,0 expense   from base_system_dict_entry WHERE dict_code = 'door_service_door_dict' ORDER BY sort";
            }else{
                sql = "SELECT DISTINCT a.FYXH code,a.FYMC title,a.FYDW unit,a.FYDJ expense from gy_ylsf a ";
                if("used".equals(type)){
                    sql += " JOIN wlyy_door_order_item i on i.code = a.FYXH and (i.patient = '"+patient+"' or i.doctor='"+doctor+"') ";
                }else if("other".equals(type)){
                    sql += " where a.FYGB not in (SELECT code from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict')";
                }else{
                    sql += " WHERE a.FYGB ="+type;
                }
            }
        }else {
            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;
    }
    /**
     * 居民端服务项类型
     * @return
     */
    public List<Map<String,Object>> selectPatientTypes(){
        String sql = "SELECT code,value type from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict' and code = 'door'";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    /**
     * 医生端服务项类型
     * @return
     */
    public List<Map<String,Object>> selectTypes(){
        String sql = "SELECT code,value type from base_system_dict_entry WHERE dict_code = 'door_service_subject_class_dict' ORDER BY sort";
        List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sql);
        Map<String,Object> map1 = new HashedMap();
        map1.put("code","used");
        map1.put("type","常用");
        mapList1.add(map1);
        Map<String,Object> map2 = new HashedMap();
        map2.put("code","other");
        map2.put("type","其他");
        mapList1.add(map2);
        return mapList1;
    }
}

+ 46 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/WlyySystemDictService.java

@ -0,0 +1,46 @@
package com.yihu.jw.care.service.common;
import com.yihu.jw.entity.base.system.SystemDictEntryDO;
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.List;
/**
 * Created by yeshijie on 2021/1/9.
 */
@Service
@Transactional
public class WlyySystemDictService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<SystemDictEntryDO> getDictByDictName(String dictCode) {
        String sql = "select d.* from base_system_dict_entry d where d.dict_code = '"+dictCode+"'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SystemDictEntryDO.class));
    }
    /**
     * 查找字典项
     * @param dictCode
     * @param code
     * @return
     */
    public String getDictValue(String dictCode, String code) {
        String re = null;
        try {
            String sql = "select d.value from base_system_dict_entry d where d.dict_code = '"+dictCode+"' and d.code = '"+code+"'";
            re = jdbcTemplate.queryForObject(sql,String.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return re;
    }
}

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

@ -1,6 +1,7 @@
package com.yihu.jw.care.service.consult;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.doorCoach.BaseDoorCoachOrderDao;
import com.yihu.jw.care.dao.sign.ServicePackageSignRecordDao;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
@ -10,6 +11,7 @@ import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSignRecordDO;
import com.yihu.jw.entity.care.assistance.EmergencyAssistanceDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
@ -46,6 +48,8 @@ public class ConsultTeamService {
    private ServicePackageService servicePackageService;
    @Autowired
    private ServicePackageSignRecordDao servicePackageSignRecordDao;
    @Autowired
    private BaseDoorCoachOrderDao baseDoorCoachOrderDao;
    public JSONObject updateIMMsg(String sessionId,String sessionType,String msgId,String content){
@ -242,4 +246,84 @@ public class ConsultTeamService {
        }
        return true;
    }
    /**
     * 添加上门辅导服务咨询
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    public JSONObject addDoorCoachServiceConsult(String orderId) throws Exception {
        JSONObject result = new JSONObject();
        //上门服务关联的工单
        BaseDoorCoachOrderDO doorServiceOrderDO = baseDoorCoachOrderDao.findOne(orderId);
        String patient = doorServiceOrderDO.getPatient();
//        String doctor =  doorServiceOrderDO.getDispatcher();
//        String doctorName = doorServiceOrderDO.getDispatcherName();
//        int orderStatus = doorServiceOrderDO.getStatus();
        // 添加咨询记录
        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(21);  //上门服务咨询
        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);
        String content = patientDO.getName() + "-上门辅导服务咨询";
        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;
        }
        // 把医生拉入会话,作为其中一个成员
        if(StringUtils.isNotBlank(doorServiceOrderDO.getDoctor())){
            imUtill.updateParticipantNew(sessionId,doorServiceOrderDO.getDoctor(),null);
        }
        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;
    }
}

+ 861 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/DoctorDoorCoachOrderService.java

@ -0,0 +1,861 @@
package com.yihu.jw.care.service.doorCoach;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.doorCoach.*;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
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.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.care.doorCoach.*;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
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 com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import org.apache.commons.lang.StringUtils;
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.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 上门辅导
 */
@Service
@Transactional
public class DoctorDoorCoachOrderService {
    private Logger logger = LoggerFactory.getLogger(DoctorDoorCoachOrderService.class);
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoorCoachConclusionDao doorConclusionDao;
    @Autowired
    private BaseDoorCoachOrderDao baseDoorCoachOrderDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BaseDoorCoachFeeDetailDao doorFeeDetailDao;
    @Autowired
    private BaseDoorCoachPatientConfirmLogDao confirmLogDao;
    @Autowired
    private BaseDoorCoachDoctorStatusDao doctorStatusDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private PatientDoorCoachOrderService patientDoorCoachOrderService;
    @Autowired
    private BasePatientDao patientInfoService;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private BaseDoorCoachOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private BaseDoorCoachFeeDetailDao wlyyDoorFeeDetailDao;
    @Value("${base.hospitalUrl}")
    private String hospitalUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    /**
     * 根据id获取服务工单信息
     * @param id
     * @return
     */
    public BaseDoorCoachOrderDO getDoorServiceOrderById(String id) throws Exception {
        BaseDoorCoachOrderDO doorServiceOrder = baseDoorCoachOrderDao.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 = patientDoorCoachOrderService.countPatientDoorTimes(doorServiceOrder.getPatient());
        List<Map<String, Object>> feeDetailDOS = this.getDoorFeeDetailGroupByStatus(id);
        String jsonData = this.serverPackagePriceByOrderId(id);
        if (null != feeDetailDOS && feeDetailDOS.size() > 0) {
            // 设置服务项及费用信息
            doorServiceOrder.setDoorFeeDetailList(feeDetailDOS);
        }
        //获取咨询
        ConsultDo consult = consultDao.queryByRelationCode(id);
        if (null != consult) {
            doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getId() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
        }
        // 设置服务小结
        BaseDoorCoachConclusionDO doorConclusion = this.getDoorConclusion(id);
        if (null == doorConclusion) {
            doorConclusion = new BaseDoorCoachConclusionDO();
        }
        doorServiceOrder.setDoorConclusion(doorConclusion);
        return doorServiceOrder;
    }
    /**
     * 获取工单列表
     * @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 page, Integer pageSize, Integer type)throws Exception{
        String sqlList = "select DISTINCT o.id as orderId,o.status,h.code orgCode,h.name as orgName,o.is_trans_other_org," +
                "o.transed_org_code, 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.org_level as hosLevel, o.doctor," +
                "o.doctor_name as doctorName, o.doctor_type as doctorType"
                ;
        String sqlCount = " select count(DISTINCT o.id) as total ";
        String sql = " from base_door_coach_order o LEFT JOIN base_org h on h.code=o.hospital and h.del=1 where 1=1 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 (o.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{
            sql += " and o.type = " + type ;
        }
        if(StringUtils.isNotBlank(doctorCode)){
            sql += "and o.doctor= '"+doctorCode+"' ";
        }
        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;
            hospital = one.get("orgCode");
            hospitalName = one.get("orgName");//签约表中的机构
            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"));
            object.put("totalFee",one.get("total_fee"));
            List<BaseDoorCoachFeeDetailDO> feeDetailDOs = doorFeeDetailDao.findByOrderIdAndType(one.get("orderId")+"", 1);
            List<Map<String,Object>> feeDetailResultList = new ArrayList();
            for(BaseDoorCoachFeeDetailDO 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) {
                object.put("sex", IdCardUtil.getSexForIdcard(patient.getIdcard()));
                object.put("age", IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
                object.put("photo", patient.getPhoto());
//                object.put("typeValue", "儿童");
            }
            String id = one.get("orderId").toString();
            BaseDoorCoachOrderDO doorServiceOrder = this.baseDoorCoachOrderDao.findOne(id);
            //获取咨询
            ConsultDo consult = consultDao.queryByRelationCode(id);
            if (null != consult) {
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + 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;
    }
    /**
     * 根据orderId获取工单服务小结
     * @param orderId
     * @return
     */
    public BaseDoorCoachConclusionDO getDoorConclusion(String orderId){
        BaseDoorCoachConclusionDO doorConclusion = doorConclusionDao.findByOrderId(orderId);
        return doorConclusion;
    }
    public BaseDoorCoachOrderDO acceptOrder1(String orderId, String jobCode, String jobCodeName, int hospitalLevel ) throws Exception{
        BaseDoorCoachOrderDO doorServiceOrder = baseDoorCoachOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        doorServiceOrder.setDoctorArrivingTime(doorServiceOrder.getPatientExpectedServeTime());
        doorServiceOrder.setStatus(BaseDoorCoachOrderDO.Status.accept.getType()); // 2-待(医生)接单,3-已接单
        this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 3);//3待服务
        doorServiceOrder.setServiceResponseTime(new Date());
        baseDoorCoachOrderDao.save(doorServiceOrder);
        systemMessageDao.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() + "医生正在为您服务!";
            patientDoorCoachOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "1", noticeContent);
            // 发送居民上门服务简要信息
            JSONObject orderInfoContent = patientDoorCoachOrderService.queryOrderCardInfo(doorServiceOrder);
            orderInfoContent.put("re_msg_type", 0);
            patientDoorCoachOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "2201", orderInfoContent.toJSONString());
        }
        return doorServiceOrder;
    }
    /**
     * 接单
     * @param orderId
     */
    public void acceptOrder(String orderId,String jobCode,String jobCodeName,int hospitalLevel ) throws Exception {
        BaseDoorCoachOrderDO doorServiceOrder = acceptOrder1(orderId, jobCode, jobCodeName, hospitalLevel);
        if(doorServiceOrder==null){
            return;
        }
        // 发送微信模板消息通知患者医生已接单
        BasePatientDO patient = patientInfoService.findById(doorServiceOrder.getPatient());//·
        // 获取微信模板
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {
            JSONObject json = new JSONObject();
            if(consult != null) {
                json.put("consult", consult.getId());
            }
            String first = "key1,您好!您的上门预约服务已由【key2】医生接单了";
            first = first.replace("key1",(patient.getName()==null?"":patient.getName()));
            first = first.replace("key2", null != doorServiceOrder.getDoctorName() ? doorServiceOrder.getDoctorName() : "");
            List<BasePatientWechatDo> basePatientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patient.getId());
            String openId = basePatientWechatDos.get(0).getOpenid();
            messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","smyyyjjd",openId,first,null,null,30,json, DateUtil.dateToChineseDate(new Date()),"上门服务已接单");
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678
        messageUtil.updateDoorCoachMessage(doorServiceOrder,new String[]{"703","707"},"734",null,null);
    }
    /**
     * 拒单
     * @param orderId
     * @param reason
     * @throws Exception
     */
    public void refuseOrder(String receiver, String orderId, String reason) throws Exception {
        BaseDoorCoachOrderDO doorServiceOrder = baseDoorCoachOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        //给代预约医生发消息
        if (doorServiceOrder.getType() != null && doorServiceOrder.getType() == 3) {
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doorServiceOrder.getProxyPatient());//·
            this.createMessage("代预约服务工单重新派单","703","system","system", doorServiceOrder.getId(), doorServiceOrder.getProxyPatient(),baseDoctorDO.getName() ,null, doorServiceOrder.getPatientName() + "的代预约服务工单需重新派单,请您前往处理");
        } else {
            systemMessageDao.orderMessageDel(doorServiceOrder.getDoctor(),orderId);
            if(StringUtils.isNotBlank(doorServiceOrder.getDispatcher())){
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doorServiceOrder.getDispatcher());//·
                this.createMessage("服务工单拒单待重新派单","704","system","system", doorServiceOrder.getId(), doorServiceOrder.getDispatcher(),baseDoctorDO.getName() , null,doorServiceOrder.getDoctorName() + "拒绝了" + doorServiceOrder.getProxyPatientName() + "的服务预约申请,请重新派单");
                //  调度员-派单-实时工单消息:435 医生拒单-- 王五拒绝了服务工单12345678
                messageUtil.updateDoorCoachMessage(doorServiceOrder,new String[]{"731","733"},"735",null,null);
            }
        }
        doorServiceOrder.setDoctor(null);
        doorServiceOrder.setDoctorName(null);
        doorServiceOrder.setStatus(BaseDoorCoachOrderDO.Status.waitForSend.getType());  // 设置为1-待(调度员)派单
        doorServiceOrder.setCancelReason(reason);   // 拒绝原因
        doorServiceOrder.setCancelTime(new Date());
        baseDoorCoachOrderDao.save(doorServiceOrder);
    }
    /**
     * 签到保存
     * @param orderId
     * @param signTime
     * @param signWay
     * @param signLocation
     * @param signImg
     * @return
     */
    public BaseDoorCoachOrderDO signIn(String orderId, String signTime, Integer signWay, String signLocation,
                                         String signImg, String twoDimensionalCode,String doctorId) throws Exception {
        BaseDoorCoachOrderDO doorServiceOrder = this.baseDoorCoachOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        doorServiceOrder.setDoctorSignTime(DateUtil.strToDate(signTime));
        doorServiceOrder.setDoctorSignWay(signWay);
        // 签到方式-2扫码时,需要去解析地址
        doorServiceOrder.setDoctorSignLocation(signLocation);
        doorServiceOrder.setDoctorSignImg(StringUtils.isEmpty(signImg) ? null : signImg);
        doorServiceOrder.setStatus(4);
        if(signWay == 4 ){//扫码签到
            if (twoDimensionalCode.equals(doorServiceOrder.getNumber())){
                this.setUpdateColumnInfo(doorServiceOrder);
                doorServiceOrder = baseDoorCoachOrderDao.save(doorServiceOrder);
                // 修改医生上门服务工单状态 4服务中
                this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);
//                appointmentRevisitOnDoor(doorServiceOrder,doctorId);挂号
                return doorServiceOrder;
            }else {
                logger.info("扫码签到失败");
                return null;
            }
        }else {
            this.setUpdateColumnInfo(doorServiceOrder);
            doorServiceOrder = baseDoorCoachOrderDao.save(doorServiceOrder);
            // 修改医生上门服务工单状态 4服务中
            this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);
//            appointmentRevisitOnDoor(doorServiceOrder,doctorId);挂号
            return doorServiceOrder;
        }
    }
    /**
     * 编辑保存服务工单小结
     * @return
     * @throws Exception
     */
    public BaseDoorCoachConclusionDO updateDoorConclusion(String orderId,String conclusion,String conclusionImg,Integer conclusionStatus) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        BaseDoorCoachOrderDO one = baseDoorCoachOrderDao.findOne(orderId);
        if (null == one) {
            throw new Exception("该工单不存在");
        }
        BaseDoorCoachConclusionDO doorConclusion = new BaseDoorCoachConclusionDO();
        if (conclusionStatus==2) {
            doorConclusion.setOrderId(orderId);
            doorConclusion.setPatient(one.getPatient());
            doorConclusion.setPatientName(one.getPatientName());
            doorConclusion.setConclusionImg(conclusionImg);
            doorConclusion.setDoctor(one.getDoctor());
            doorConclusion.setConclusion(conclusion);
            doorConclusion.setDoctorName(one.getDoctorName());
            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.setConclusionStatus(conclusionStatus);
        if (one.getStatus()<=BaseDoorCoachOrderDO.Status.waitForCommnet.getType()){
            one.setStatus(BaseDoorCoachOrderDO.Status.waitForCommnet.getType());
        }
        baseDoorCoachOrderDao.save(one);
        return doorConclusion;
    }
    /**
     * 居民拍照确认
     * @param orderId
     * @param finishWay
     * @param finishImg
     * @return
     */
    public BaseDoorCoachOrderDO saveOrderFinishByDoctor(String orderId, Integer finishWay, String finishImg) throws Exception {
        BaseDoorCoachOrderDO one = baseDoorCoachOrderDao.findOne(orderId);
        if (null == one) {
            throw new Exception("该工单不存在");
        }
        one.setPatientConfirmFinishWay(finishWay);
        one.setPatientConfirmFinishImg(finishImg);
        one.setStatus(BaseDoorCoachOrderDO.Status.complete.getType());
        one.setPatientConfirmFinishTime(new Date());
        // 更新记录
        this.setUpdateColumnInfo(one);
        // 计算保存服务总的支付费用
        Integer times = patientDoorCoachOrderService.countPatientDoorTimes(one.getPatient());
        String jsonData = this.serverPackagePriceByOrderId(orderId);
        baseDoorCoachOrderDao.save(one);
        BaseDoorCoachOrderDO doorServiceOrderDO = this.getDoorServiceOrderById(orderId);
        // 发送微信通知  待付款
        BasePatientDO patient = patientInfoService.findById(one.getPatient());
        // 获取微信模板 smfwdwk-上门服务待付款
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {//·
            JSONObject json = new JSONObject();
            String finish="";
            json.put("id",orderId);
            finish = "1";
            json.put("finish",finish);
            List<BasePatientWechatDo> basePatientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patient.getId());
            String openId = basePatientWechatDos.get(0).getOpenid();
            String first="key1预约上门服务医生已完成服务。".replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
            messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","fwyspf",openId,first,null,null,31,json,DateUtil.dateToChineseDate(new Date()),"服务医生评分");
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return doorServiceOrderDO;
    }
    /**
     * 根据接单医生code获取最近一次服务orderId
     * @param doctor
     * @return
     */
    public String getOrderIdByDoctor(String doctor) {
        String sql = "SELECT id as orderId from base_door_coach_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;
    }
    /**
     * 系统更新医生上门服务工单状态
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusBySystem(String doctor, Integer dispatchOrderStatus) {
        BaseDoorCoachDoctorStatusDO doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        } else {
            doctorSwitch = new BaseDoorCoachDoctorStatusDO();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        }
        doctorStatusDao.save(doctorSwitch);
    }
    /**
     * 修改预计到达时间
     * @param orderId
     * @param arrivingTime
     * @return
     */
    public BaseDoorCoachOrderDO updateArrivingTime(String orderId, String arrivingTime) {
        BaseDoorCoachOrderDO one = baseDoorCoachOrderDao.findOne(orderId);
        one.setDoctorArrivingTime(arrivingTime);
        this.setUpdateColumnInfo(one);
        one = baseDoorCoachOrderDao.save(one);
        // 医生修改预计到达时间保存到日志表中
        BaseDoorCoachPatientConfirmLogDO confirmLogDO = new BaseDoorCoachPatientConfirmLogDO();
        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 Integer getDoorOrderNum(String doctor){
        String sql = "SELECT COUNT(DISTINCT a.id) as num FROM base_door_coach_order a " ;
        sql +=  " WHERE  a.doctor = '"+doctor+"'  and a.status = "+BaseDoorCoachOrderDO.Status.waitForServe.getType();
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }
    /**
     * 顶部状态栏订单各分类总条数
     * @param doctor
     * @return
     */
    public Map<String, Integer> getNumGroupByStatus(String doctor) throws Exception {
        String sql = "SELECT a.status, COUNT(DISTINCT a.id) as num FROM base_door_coach_order a  where a.doctor = '"+doctor+"' group BY a.status " ;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Map<String, Integer> map = new HashMap<>();
        Integer all = list.size();
        Integer waitForServe = 0;
        Integer served = 0;
        Integer cancel = 0;
        // -1已取消 [1,4]待服务 [5,6]已服务
       for (Map<String, Object> tmp:list){
           switch (String.valueOf(tmp.get("status"))){
               case "-1":
                   cancel += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "1":
                   waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "2":
                   waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "3":
                   waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "4":
                   waitForServe += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "5":
                   served += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               case "6":
                   served += Integer.valueOf(tmp.get("num").toString()) ;
                   break;
               default: {
                   throw new Exception("类型错误!"+String.valueOf(tmp.get("status")));
               }
           }
       }
       map.put("all",all);
       map.put("waitForServe",waitForServe);
       map.put("served",served);
       map.put("cancel",cancel);
       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;
    }
    /**
     * 获取订单下服务包数量、单价
     * @param orderId
     * @return
     * @throws Exception
     */
    public String serverPackagePriceByOrderId(String orderId) throws Exception {
        String sql = "SELECT d.code itemCode,sum(d.number) number,fee from base_door_coach_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 one
     * @return
     */
    private void setUpdateColumnInfo(BaseDoorCoachOrderDO one) {
        one.setUpdateTime(new Date());
        one.setUpdateUser(one.getDoctor());
        one.setUpdateUserName(one.getDoctorName());
    }
    /**
     * 根据工单id获取服务工单-服务项价格,按status分组,1-居民新增(预约),2-医生新增,3-医生删除
     * @param orderId
     * @return
     */
    public List<Map<String, Object>> getDoorFeeDetailGroupByStatus(String orderId) {
        String sql = "SELECT d.id, d.status, CONCAT(d.pay_status,'') payStatus,d.name,d.code,sum(d.number) num,fee,sum(d.number)*fee sum from base_door_coach_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 patient
     * @return
     */
    public Integer serviceCount(String patient) {
        String sql = "SELECT count(id) times FROM base_door_coach_order WHERE DATE_FORMAT(doctor_sign_time, '%Y') = DATE_FORMAT(NOW(), '%Y') AND patient=? and status>="+BaseDoorCoachOrderDO.Status.waitForCommnet.getType();
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, patient);
        return count;
    }
    public void initDoorStatus(){
        String sql = "SELECT * from base_doctor WHERE id not in ( " +
                "SELECT doctor from base_door_coach_doctor_status " +
                ")";
        List<BaseDoctorDO> doctorDOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(BaseDoctorDO.class));
        List<BaseDoorCoachDoctorStatusDO> statusDOList = new ArrayList<>(doctorDOs.size());
        for (BaseDoctorDO baseDoctorDO:doctorDOs){
            BaseDoorCoachDoctorStatusDO doctorSwitch = new BaseDoorCoachDoctorStatusDO();
            doctorSwitch.setDoctor(baseDoctorDO.getId());
            doctorSwitch.setStatus(1);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
            statusDOList.add(doctorSwitch);
        }
        doctorStatusDao.save(statusDOList);
    }
    /**
     * 查看指定医生是否开启分派订单功能
     * @param doctor
     * @return
     */
    public String findDispatchStatusByDoctor(String doctor) {
        BaseDoorCoachDoctorStatusDO doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        BaseDoctorDO doctorVO = doctorDao.findById(doctor);
        if (null == doctorSwitch) {
            BaseDoorCoachDoctorStatusDO DoorDoctorStatusDO =new BaseDoorCoachDoctorStatusDO();
            DoorDoctorStatusDO.setDoctor(doctor);
            DoorDoctorStatusDO.setStatus(5);
            DoorDoctorStatusDO.setCreateTime(new Date());
            DoorDoctorStatusDO.setCreateUser(doctor);
            DoorDoctorStatusDO.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
            doctorStatusDao.save(DoorDoctorStatusDO);
            return "0";
        }
        return doctorSwitch.getStatus() == 5 ? "0" : "1";
    }
    /**
     * 修改指定医生的分派订单开关,不存在该医生的开关,则创建
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusByDoctor(String doctor, Integer dispatchOrderStatus) {
        BaseDoorCoachDoctorStatusDO 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 BaseDoorCoachDoctorStatusDO();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser(doctor);
            doctorSwitch.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        doctorStatusDao.save(doctorSwitch);
    }
    /**
     * 门牌地址解析
     * @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();
    }
    /**
     * 添加【工单派单,转单】等系统消息
     */
    public void createMessage(String title,String type,String sender,String senderName,String relationCode,String Receiver,String ReceiverName,String idCard,String msg){
        SystemMessageDO messageDO = new SystemMessageDO();
        messageDO.setTitle(title);
        messageDO.setType(type);//401为资质申请审核
        messageDO.setSender(sender);
        messageDO.setSenderName(senderName);
        messageDO.setRelationCode(relationCode);
        messageDO.setReceiver(Receiver);
        messageDO.setReceiverName(ReceiverName);
        messageDO.setData(msg);
        messageDO.setDel("1");
        messageDO.setOver("1");
        messageDO.setCreateTime(new Date());
        systemMessageDao.save(messageDO);
    }
}

+ 1085 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doorCoach/PatientDoorCoachOrderService.java

@ -0,0 +1,1085 @@
package com.yihu.jw.care.service.doorCoach;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.doorCoach.*;
import com.yihu.jw.care.service.consult.ConsultTeamService;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
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.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.care.doorCoach.*;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
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.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.CollectionUtils;
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.math.BigDecimal;
import java.util.*;
/**
 * 上门辅导服务工单服务service--居民端
 **/
@Service
public class PatientDoorCoachOrderService extends BaseJpaService<BaseDoorCoachOrderDO, BaseDoorCoachOrderDao> {
    private Logger logger = LoggerFactory.getLogger(PatientDoorCoachOrderService.class);
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoorCoachOrderDao baseDoorCoachOrderDao;
    @Autowired
    private BaseDoorCoachFeeDetailDao baseDoorCoachFeeDetailDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseDoorCoachDoctorStatusDao baseDoorCoachDoctorStatusDao;
    @Autowired
    private BaseDoorCoachProcessLogDao baseDoorCoachProcessLogDao;
    @Autowired
    private DoctorDoorCoachOrderService doorOrderService;
    @Autowired
    private BaseDoorCoachCancelLogDao baseDoorCoachCancelLogDao;
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private BaseDoorCoachPatientConfirmLogDao patientConfirmLogDao;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private SystemMessageDao systemMessageDao;
    /**
     * 创建上门辅导服务工单
     *
     * @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;
        }
        BaseDoorCoachOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), BaseDoorCoachOrderDO.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;
        }
        //已取消的订单也可以申请
        boolean bool = baseDoorCoachOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                new Integer[]{BaseDoorCoachOrderDO.Status.waitForSend.getType(),
                        BaseDoorCoachOrderDO.Status.waitForAccept.getType(),
                        BaseDoorCoachOrderDO.Status.waitForServe.getType(),
                        BaseDoorCoachOrderDO.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);
        result.put("orderId",orderDO.getId());
        //创建咨询
        JSONObject successOrNot = null;
        try {
            successOrNot = consultTeamService.addDoorCoachServiceConsult(orderDO.getId());
        } catch (Exception e) {
            e.printStackTrace();
            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,null)) {return result;}
        JSONObject dispatcherJson = queryDispatcherInfoByPatient(jsonObjectParam.getJSONObject("hospital").get("code").toString());
        List<Map<String,Object>> dispatcherInfoList = (List)dispatcherJson.get(ResponseContant.resultMsg);
        for(Map<String,Object> map: dispatcherInfoList){
            String dispatcher = map.get("code").toString();
            BaseDoctorDO doctorVO = doctorDao.findById(dispatcher);
            // 派单消息-首页
            this.createMessage("新增居民预约服务申请","702","system","system", orderDO.getId(), dispatcher,doctorVO.getName() ,doctorVO.getIdcard(), orderDO.getPatientName() + "提交了服务预约申请,请您前往处理");
            // 派单-实时工单消息  430 居民提交工单申请-- 张三提交了服务工单12345678申请
            this.createMessage("居民提交工单申请","730","system","system", orderDO.getId(), dispatcher,doctorVO.getName() ,doctorVO.getIdcard(), orderDO.getPatientName() + "提交了服务工单"+orderDO.getNumber()+"申请");
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        //发送智能助手消息
        sendWeixinMessage(4,orderDO.getDoctor(),orderDO.getPatient());
        //发送 预约卡片信息(2201类型)
        JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
        orderInfoContent.put("re_msg_type",0);//居民预约
        this.qucikSendIM(orderDO.getId(), "system", "智能助手", "2201", 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;
    }
    @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;
        }
        BaseDoorCoachOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), BaseDoorCoachOrderDO.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())) {
            //已取消的订单也可以申请
            boolean bool = baseDoorCoachOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                    new Integer[]{BaseDoorCoachOrderDO.Status.waitForAccept.getType(),
                            BaseDoorCoachOrderDO.Status.waitForServe.getType(),
                            BaseDoorCoachOrderDO.Status.accept.getType(),
                            BaseDoorCoachOrderDO.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 {
            BaseDoorCoachOrderDO serviceOrderDO = baseDoorCoachOrderDao.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;
            }
            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,doctorCode)) {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);
                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("服务工单待接单","707",orderDO.getProxyPatient(),orderDO.getProxyPatientName(), orderDO.getId(),orderDO.getDoctor(),orderDO.getDoctorName(), null,"您有新的服务工单,请前往处理");
            //发送智能助手消息
            sendWeixinMessage(4,orderDO.getDoctor(),orderDO.getPatient());
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        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 DISTINCT ds.doctor,d.name, d.job_title_name as jobName, 1 as sortFlag " +
                " from base_door_coach_doctor_status ds " +
                "        JOIN (select b.* from base_doctor b,base_doctor_hospital dh where b.id=dh.doctor_code and dh.del = 1 and dh.org_code='" + hospital + "')  d on ds.doctor = d.id " +
                " LEFT JOIN base_doctor_role dr ON dr.doctor_code = d.id where ds.status in (1,2,3,4) AND dr.role_code != 'nurse' " +
                " limit " + start + "," + end ;
        String countSql = "select DISTINCT count(ds.id) " +
                "from wlyy_door_doctor_status ds " +
                "         JOIN (select b.* from base_doctor b,base_door_coach_doctor_status dh where b.id=dh.doctor_code and dh.del = 1 and dh.org_code= '" + hospital + "') d on ds.doctor = d.id " +
                " LEFT JOIN base_doctor_role dr ON dr.doctor_code = d.id where ds.status in (1,2,3,4) AND dr.role_code != 'nurse' ";
        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;
        }
        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 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;
        }
        BaseDoorCoachOrderDO wlyyDoorServiceOrder = new BaseDoorCoachOrderDO();
        wlyyDoorServiceOrder = jsonToWlyyDoorServiceOrder(result, jsonObjectParam, jsonData);
        this.save(wlyyDoorServiceOrder);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        return result;
    }
    /**
     * 删除出诊医生或服务项
     * @param jsonObjectParam
     * {
     *     "deleteItemArr":[
     *        {
     *           "id":""
     *       },
     *        {
     *           "id":""
     *      }
     *     ],
     *     "deleteDoctorArr":[
     *     {
     *         "id":""
     *     },
     *      {
     *         "id":""
     *     }
     *     ]
     * }
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithFeeDelete(JSONObject jsonObjectParam, BaseDoorCoachOrderDO orderDO) {
        BigDecimal totalFee = orderDO.getTotalFee();
        //删除的服务项
        JSONArray itemArray = jsonObjectParam.getJSONArray("deleteItemArr");
        if (!CollectionUtils.isEmpty(itemArray)) {
            List<BaseDoorCoachFeeDetailDO> list = new ArrayList<>();
            //删除的服务项要减去服务项费用
            BigDecimal itemFee = new BigDecimal(0);
            for(Object oneId : itemArray) {
                JSONObject oneIdJson = (JSONObject) oneId;
                BaseDoorCoachFeeDetailDO doorFeeDetail = baseDoorCoachFeeDetailDao.findOne(String.valueOf(oneIdJson.get("id")));
                if(doorFeeDetail.getPayStatus()==0){
                    doorFeeDetail.setStatus(3);
                    doorFeeDetail.setUpdateTime(new Date());
                    list.add(doorFeeDetail);
                    itemFee = itemFee.add(doorFeeDetail.getFee().multiply(BigDecimal.valueOf(doorFeeDetail.getNumber())));
                }
            }
            baseDoorCoachFeeDetailDao.save(list);
        }
        return false;
    }
    /**
     * 上门服务工单服务基本信息
     *
     * @param result
     * @param jsonObjectParam
     * @param jsonData
     * @return
     */
    public BaseDoorCoachOrderDO jsonToWlyyDoorServiceOrder(JSONObject result, JSONObject jsonObjectParam, String jsonData) {
        BaseDoorCoachOrderDO wlyyDoorServiceOrder;
        try {
            wlyyDoorServiceOrder = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), BaseDoorCoachOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return new BaseDoorCoachOrderDO();
        }
        wlyyDoorServiceOrder.setNumber(getRandomIntStr());
        return wlyyDoorServiceOrder;
    }
    /**
     * 查询预约简要卡片信息
     *
     * 服务时间:2019-01-01   12:30
     * 服务对象:张三
     * 联系电话:13125256565(儿子)
     * 上门地址:福建省厦门市思明区望海路55号
     *
     * @param orderDO
     * @return
     */
    public JSONObject queryOrderCardInfo(BaseDoorCoachOrderDO 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;
    }
    /**
     * 【调度员,医生】快速发送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;
        }
        BaseDoorCoachOrderDO baseDoorCoachOrderDO = null;
        String response = null;
        if(StringUtils.isBlank(sendId)){
            baseDoorCoachOrderDO = baseDoorCoachOrderDao.findOne(orderId);
            String sender = "system";
            if(StringUtils.isNoneBlank(baseDoorCoachOrderDO.getDispatcher())){
                sender = baseDoorCoachOrderDO.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 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();
        BaseDoorCoachOrderDO doorServiceOrderDO = baseDoorCoachOrderDao.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;
        }
        BaseDoorCoachDoctorStatusDO doorDoctorStatusDO = baseDoorCoachDoctorStatusDao.queryByDoctorAndStatusIn(doctor,new Integer[]{BaseDoorCoachOrderDO.Status.waitForSend.getType(),
                BaseDoorCoachDoctorStatusDO.Status.waitForAccept.getType(),
                BaseDoorCoachDoctorStatusDO.Status.waitForServe.getType(),
                BaseDoorCoachDoctorStatusDO.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(BaseDoorCoachOrderDO.Status.waitForAccept.getType());
        doorServiceOrderDO.setUpdateUser(dispatcher);
        doorServiceOrderDO.setUpdateUserName(dispathcherName);
        doorServiceOrderDO.setDispatcherResponseTime(new Date());
        this.save(doorServiceOrderDO);
        // 给医生发派单消息
        if(BaseDoorCoachOrderDO.IsTransOtherOrg.yes.getType().equals(doorServiceOrderDO.getIsTransOtherOrg())){
            this.createMessage("服务工单待接单","707",doorServiceOrderDO.getTransedDispatcher(),doorServiceOrderDO.getTransedDispatcherName(), orderId,doctor,doctorName, null,"您有新的服务工单,请前往处理");
        }else{
            this.createMessage("服务工单待接单","707",doorServiceOrderDO.getDispatcher(),doorServiceOrderDO.getDispatcherName(), orderId,doctor,doctorName, null,"您有新的服务工单,请前往处理");
        }
        //发送智能助手消息//·
        sendWeixinMessage(4,doctor,doorServiceOrderDO.getPatient());
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipantNew(sessionId,doctor,null);
        messageUtil.updateDoorCoachMessage(doorServiceOrderDO,new String[]{"702","703","730","735"},"731",dispatcher,dispatcher);
        // 工单状态变更记录
        BaseDoorCoachProcessLogDO processLogDO = new BaseDoorCoachProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(BaseDoorCoachOrderDO.Status.waitForAccept.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispathcherName);
        processLogDO.setCreateTime(new Date());
        baseDoorCoachProcessLogDao.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();
        BaseDoorCoachOrderDO doorServiceOrderDO = baseDoorCoachOrderDao.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;
        }
        BaseDoorCoachDoctorStatusDO doorDoctorStatusDO = baseDoorCoachDoctorStatusDao.queryByDoctorAndStatusIn(doctor,new Integer[]{BaseDoorCoachDoctorStatusDO.Status.waitForSend.getType(),
                BaseDoorCoachDoctorStatusDO.Status.waitForAccept.getType(),
                BaseDoorCoachDoctorStatusDO.Status.waitForServe.getType(),
                BaseDoorCoachDoctorStatusDO.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(BaseDoorCoachOrderDO.Status.waitForAccept.getType());
        doorServiceOrderDO.setUpdateUser(dispatcher);
        doorServiceOrderDO.setUpdateUserName(dispathcherName);
        doorServiceOrderDO.setDispatcherResponseTime(new Date());
        System.out.println(dispathcherName+"医生派单给"+doctorName+"医生");
        String sql = "DELETE FROM wlyy_door_doctor WHERE order_id ='"+orderId+"' AND doctor = '"+dispatcher+"'";
        jdbcTemplate.execute(sql);
        this.save(doorServiceOrderDO);
        // 给医生发派单消息
        if(BaseDoorCoachOrderDO.IsTransOtherOrg.yes.getType().equals(doorServiceOrderDO.getIsTransOtherOrg())){
            this.createMessage("服务工单待接单","707",doorServiceOrderDO.getTransedDispatcher(),doorServiceOrderDO.getTransedDispatcherName(), orderId,doctor,doctorName, null,"您有新的服务工单,请前往处理");
        }else{
            this.createMessage("服务工单待接单","707",doorServiceOrderDO.getDispatcher(),doorServiceOrderDO.getDispatcherName(), orderId,doctor,doctorName, null,"您有新的服务工单,请前往处理");
        }
        //发送智能助手消息
        sendWeixinMessage(4,doctor,doorServiceOrderDO.getPatient());
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipantNew(sessionId,doctor,null);
        messageUtil.updateDoorCoachMessage(doorServiceOrderDO,new String[]{"702","703","730","735"},"731",dispatcher,dispatcher);
        // 工单状态变更记录
        BaseDoorCoachProcessLogDO processLogDO = new BaseDoorCoachProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(BaseDoorCoachOrderDO.Status.waitForAccept.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispathcherName);
        processLogDO.setCreateTime(new Date());
        baseDoorCoachProcessLogDao.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;
    }
    /**
     * 取消工单
     * @param orderId
     * @param type 取消类型
     * @param reason 取消理由
     */
    public JSONObject cancelOrder(String orderId,int type,String reason,String dispatcher,String dispatcherName){
        JSONObject result = new JSONObject();
        BaseDoorCoachOrderDO orderDO = baseDoorCoachOrderDao.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() > BaseDoorCoachOrderDO.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);
        }
        //如果是调度员取消,推送IM取消工单json消息,
        orderDO.setStatus(BaseDoorCoachOrderDO.Status.cancel.getType());
        this.save(orderDO);
        if(type == BaseDoorCoachOrderDO.CancelType.dispatcher.getType()){
            messageUtil.updateDoorCoachMessage(orderDO,new String[]{"702","703","730"},"732",dispatcher,dispatcher);
        }
        else if(type == BaseDoorCoachOrderDO.CancelType.patient.getType()){                   //居民取消,消息列表也应该不显示
            messageUtil.updateDoorCoachMessage(orderDO,new String[]{"702","703","730"},"patientCancel",dispatcher,dispatcher);
        }
        //保存取消记录
        BaseDoorCoachCancelLogDO cancelLogDO = new BaseDoorCoachCancelLogDO();
        cancelLogDO.setOrderId(orderId);
        cancelLogDO.setPatient(orderDO.getProxyPatient());
        cancelLogDO.setCancelType(type);
        cancelLogDO.setCancelReason(reason);
        cancelLogDO.setTime(orderDO.getCancelTime());
        baseDoorCoachCancelLogDao.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);
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
        String first = "key1,您好,您的上门预约服务已退回,点击查看原因";
        BasePatientDO patient = patientDao.findById(orderDO.getPatient());
        first  = first.replace("key1", null != patient.getName() ? patient.getName() : "");
        JSONObject json = new JSONObject();
        if(consult != null) {
            json.put("consult", consult.getId());
        }else {
            json.put("id", orderDO.getId());
        }
        List<BasePatientWechatDo> basePatientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patient.getId());
        String openId = basePatientWechatDos.get(0).getOpenid();
        messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","smyyyqx",openId,first,null,null,30,json, DateUtil.dateToChineseDate(new Date()),"上门预约已取消");
        // 工单状态变更记录
        BaseDoorCoachProcessLogDO processLogDO = new BaseDoorCoachProcessLogDO();
        processLogDO.setOrderId(orderId);
        processLogDO.setStatus(BaseDoorCoachOrderDO.Status.cancel.getType());
        processLogDO.setDispatcher(dispatcher);
        processLogDO.setDispatcherName(dispatcherName);
        baseDoorCoachProcessLogDao.save(processLogDO);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, "工单服务已取消!");
        return result;
    }
    /**
     * 服务工单居民确认操作日志记录
     *
     * {
     *     "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) {
            BaseDoorCoachPatientConfirmLogDO confirmLogDO = null;
            try {
                confirmLogDO = EntityUtils.jsonToEntity(confirmInfo.toString(), BaseDoorCoachPatientConfirmLogDO.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 {
                patientConfirmLogDao.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;
    }
    public void sendWeixinMessage(Integer type,String doctorCode,String patient){
        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 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, BaseDoorCoachOrderDO order, String doctorId) {
        List<BaseDoorCoachFeeDetailDO> feeDetailDOList = new ArrayList<>();
        BigDecimal totalFee = order.getTotalFee();
        if(null == totalFee){
            totalFee = new BigDecimal(0);
        }
        //新增服务项
        int addNum = 0;
        //服务项费用
        JSONArray packageItemArray = jsonObjectParam.getJSONArray("packageItemArr");
        if (!CollectionUtils.isEmpty(packageItemArray)) {
            for (Object one : packageItemArray) {
                BaseDoorCoachFeeDetailDO feeDetailDO = null;
                JSONObject oneJson = (JSONObject)one;
                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(BaseDoorCoachFeeDetailDO.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());
                }
                if(StringUtils.isBlank(feeDetailDO.getId())){
                    feeDetailDO.setPayStatus(0);
                    addNum++;
                    feeDetailDOList.add(feeDetailDO);
                }
            }
            try {
                baseDoorCoachFeeDetailDao.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;
            }
        }
        return false;
    }
    public List<Map<String,Object>> queryDispatcherInfoByHospital(String hospital){
        String sql ="    SELECT" +
                "                 d.`code`, " +
                "                 d.`name`, " +
                "                 d.`hospital_name` as hospitalName " +
                "                 FROM " +
                "                 base_doctor_role m " +
                "                 JOIN base_doctor_role_dict r ON m.role_code = r.code " +
                "                 JOIN (select a.id code,a.name,o.org_name hospital_name from base_doctor_hospital o,base_doctor a " +
                " where a.id = o.doctor_code and o.del=1 and o.org_code = '"+hospital+"') as d ON m.doctor_code = d.code" +
                "                 WHERE " +
                "                 r.code = 'dispatcher'";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 获取居民所签约的机构的调度员(一个机构可以有多个调度员)
     * 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 void createMessage(String title,String type,String sender,String senderName,String relationCode,String Receiver,String ReceiverName,String idCard,String msg){
        SystemMessageDO messageDO = new SystemMessageDO();
        messageDO.setTitle(title);
        messageDO.setType(type);//401为资质申请审核
        messageDO.setSender(sender);
        messageDO.setSenderName(senderName);
        messageDO.setRelationCode(relationCode);
        messageDO.setReceiver(Receiver);
        messageDO.setReceiverName(ReceiverName);
        messageDO.setOver("1");
        messageDO.setData(msg);
        messageDO.setDel("1");
        messageDO.setCreateTime(new Date());
        systemMessageDao.save(messageDO);
    }
    /**
     * 统计居民已经服务的次数
     * @param patient
     * @return
     */
    public Integer countPatientDoorTimes(String patient){
        Integer count = 0;
        String sql = "SELECT count(o.id) as count FROM base_door_coach_order o where  o.patient = '" + patient + "' and status>="+BaseDoorCoachOrderDO.Status.waitForCommnet.getType();
        count = jdbcTemplate.queryForObject(sql,Integer.class);
        return count;
    }
    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);
    }
}

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

@ -0,0 +1,272 @@
package com.yihu.jw.care.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();
    }
}

+ 0 - 43
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java

@ -841,50 +841,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        // 获取服务次数
        Integer count = 1;//本年服务次数 一年只能1次
        Integer times = 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);
//            //计算扣服务包后应付的服务项费用
//            /*Map<String, Object> map = this.countServerPackagePrice(jsonData, doorServiceOrder.getPatient());
//            BigDecimal cashPrice = this.calculateCash(String.valueOf(map.get("cashPrice")), id, level, times);
//            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = this.doorServiceOrderDao.findOne(id);
//            if(wlyyDoorServiceOrderDO.getTotalFee()!=cashPrice){
//                wlyyDoorServiceOrderDO.setTotalFee(cashPrice);
//                wlyyDoorServiceOrderService.save(wlyyDoorServiceOrderDO);
//            }
//            map.put("cashPrice", cashPrice);
//            doorServiceOrder.setServiceCost(map);*/
//        }
        // 服务工单关联的医护人员
//        List<Map<String, Object>> doorServiceDoctors = this.getDoorServiceDoctor(id);
//        if (null != doorServiceDoctors && doorServiceDoctors.size() > 0) {
//            doorServiceOrder.setDoctors(doorServiceDoctors);
//        }
        // 设置医生出诊费信息,先获取工单出诊医生
        /*List<WlyyDoorDoctorDO> doorDoctorDOList = doorDoctorDao.findByOrderId(id);
        if (doorDoctorDOList != null && doorDoctorDOList.size() > 0) {
            Map<String,String> jobName = new HashMap<>();
            Map<String,String> jobCode = new HashMap<>();
            List<Integer> levels = new ArrayList<>();
            for(WlyyDoorDoctorDO doorDoctorDO : doorDoctorDOList){
                jobName.put(doorDoctorDO.getDoctor(),doorDoctorDO.getDoctorJobName());
                jobName.put(doorDoctorDO.getDoctor(),doorDoctorDO.getDoctorJobCode());
                levels.add(doorDoctorDO.getHospitalLevel());
            }
            List<Map<String, Object>> jobFeeList = dmJobService.getJobFeeList(jobCode, jobName, levels, times);
            doorServiceOrder.setVisitCost(jobFeeList);
        }*/
        //获取咨询 //TODO 获取咨询
//        Consult consult = consultDao.queryByRelationCode(id);
//        if (null != consult) {
//            doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getCode() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
//        }
        // 设置服务小结
        SecurityMonitoringConclusionDO doorConclusion = this.getDoorConclusion(id);

+ 667 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsUtilService.java

@ -0,0 +1,667 @@
package com.yihu.jw.care.service.statistics;
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());
        }else if (SaveModel.doctorLevel.equals(lowLevel)) {
            map.put("code", saveModel.getDoctor());
            map.put("name", saveModel.getDoctorName());
        }
        return map;
    }
    public boolean compareSaveModel(SaveModel saveModel1,SaveModel saveModel2,String lowLevel){
        if (SaveModel.OrgLevel.equals(lowLevel) && saveModel1.getHospital() != null && saveModel2.getHospital() != null) {
            return saveModel1.getHospital().equals(saveModel2.getHospital());
        } else if (SaveModel.townLevel.equals(lowLevel) && saveModel1.getTown() != null && saveModel2.getTown() != null) {
            return saveModel1.getTown().equals(saveModel2.getTown());
        } else if (SaveModel.cityLevel.equals(lowLevel) && saveModel1.getCity() != null && saveModel2.getCity() != null) {
            return saveModel1.getCity().equals(saveModel2.getCity());
        } else if (SaveModel.deptLevel.equals(lowLevel) && saveModel1.getDept() != null && saveModel2.getDept() != null) {
            return saveModel1.getDept().equals(saveModel2.getDept());
        }else if (SaveModel.doctorLevel.equals(lowLevel) && saveModel1.getDoctor() != null && saveModel2.getDoctor() != null) {
            return saveModel1.getDoctor().equals(saveModel2.getDoctor());
        }
        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 ( (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;
            }
        });
    }
    /**
     *  降序
     * @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 ********************************************/
}

+ 95 - 90
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java

@ -3,9 +3,11 @@ package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
import com.yihu.jw.entity.care.lifeCare.LifeCareOrderDO;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
@ -64,96 +66,6 @@ public class MessageUtil {
    //发送微信模板消息
    private  String sendMessageUrl = "http://172.16.100.37:8090/hospitalPortal-sms/sms/sendMessage";
    /**
     * @param wxId
     * @param patient       患者id
     * @param cardNo
     * @param first
     * @param noticeContent
     * @param remark
     * @param redirectUrl
     * @return
     */
    public String sendWXMes(String wxId, String patient, String cardNo, String first, String noticeContent, String remark, String redirectUrl) {
        String msg = "first:" + first + "contentMsg:" + noticeContent + "remark:" + remark;
        logger.info("发送的信息=" + msg);
        JSONObject params = new JSONObject();
        params.put("transType", "sms.hospital.notice");
        params.put("merchId", "3501000014");
        JSONObject p = new JSONObject();
        String openId = "";
        if (StringUtils.isNotBlank(patient)) {
            String sql = "select * from base_patient_wechat where wechat_id='" + wxId + "'and patient_id='" + patient + "' ";
            List<BasePatientWechatDo> paientWechatDos = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BasePatientWechatDo.class));
            if (paientWechatDos != null && paientWechatDos.size() > 0) {
                openId = paientWechatDos.get(0).getOpenid();
                p.put("openId", openId);
            }
        } else {
            p.put("cardNo", cardNo);
        }
        p.put("first", first);
        p.put("noticeTime", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        p.put("noticeContent", noticeContent);
        if (StringUtils.isNotBlank(redirectUrl)) {
            p.put("redirectUrl", redirectUrl);
        }
        p.put("remark", remark);
        params.put("param", p);
        logger.info("params :" + params.toString());
        if (StringUtils.isNotBlank(openId) || StringUtils.isNotBlank(cardNo)) {
            String rs = HttpUtil.sendPost(sendMessageUrl, params.toJSONString());
            JSONObject rsJson = JSON.parseObject(rs);
            String resCode = rsJson.getString("respCode");
            if ("000000".equals(resCode)) {
                return "1";
            }
            return "0";
        } else {
            return "-1";
        }
    }
    public String ehospitalNotice(String userName, String idCard, String phone, String title, String content, String contentString, String url) {
        String msg = "first:" + title + "contentMsg:" + content + "remark:" + contentString;
        logger.info("发送的信息=" + msg);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName", userName);
        jsonObject.put("idCard", idCard);
        jsonObject.put("phone", phone);
        jsonObject.put("title", title);
        jsonObject.put("url", url);
        jsonObject.put("content", content);
        jsonObject.put("contentString", contentString);
        System.out.println(serverUrl);
        String responseMsg = httpClientUtil.sendPost(serverUrl + "/interface/ehospitalNoticePush.htm", jsonObject.toString());
        logger.info("ehospitalNoticePushResult:" + responseMsg);
        return responseMsg;
    }
    //推送模板消息
    public void putTemplateWxMessage(WxTemplateConfigDO newConfig,String openId,Integer type,JSONObject json){
        try {
            WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(newConfig.getWechatId());
            if (wxAccessTokenDO == null) {
                logger.info("wx_access_token表获取为空,wechatId" + newConfig.getWechatId());
                return;
            }
            newConfig = setTemPlateUrl(newConfig,type,openId,json);
            //发起微信消息模板推送
            logger.info("微信模板消息推送前");
            weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), openId, newConfig);
            logger.info("微信模板消息推送后");
        }catch (Exception e){
            logger.info("微信模板推送异常");
            e.printStackTrace();
        }
    }
    //推送模板消息
    /**
     *
@ -356,4 +268,97 @@ public class MessageUtil {
        }
    }
    //上门辅导消息更新
    public void updateDoorCoachMessage(BaseDoorCoachOrderDO doorServiceOrder, String[] type, String toType, String sender, String receiver){
        String orderId=doorServiceOrder.getId();
        List<SystemMessageDO> messages = systemMessageDao.queryByRelationCodeAndTypeIn(orderId,type);
        if (toType.equals("734")){//医生接单
            if (CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
            }else {
                messages.forEach(message->{
                    if (message.getType().equals("703") ) {
                        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doorServiceOrder.getDispatcher());//·
                        String msg=doorServiceOrder.getDispatcherName() + "接受了服务工单"+ doorServiceOrder.getNumber();
                        saveSystemMessage(message.getId(),message.getRelationCode(),"医生接单","734",doorServiceOrder.getDoctor(),doorServiceOrder.getDoctorName(),
                                doorServiceOrder.getDispatcher(),doorServiceOrder.getDispatcherName(),null,msg,message.getOver());
                    }
                    else{
                        message.setOver("0");
                        systemMessageDao.save(message);
                    }
                });
            }
        }
        if (toType.equals("735")) {//医生拒单
            if (CollectionUtils.isEmpty(messages)) {
                logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
            } else {
                SystemMessageDO message = messages.get(0);
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doorServiceOrder.getDispatcher());
                String msg=doorServiceOrder.getDoctorName() + "拒绝了服务工单" + doorServiceOrder.getNumber() + ", 请重新派单";
                saveSystemMessage(message.getId(),message.getRelationCode(),"医生拒单","735",doorServiceOrder.getDoctor(),doorServiceOrder.getDoctorName(),
                        doorServiceOrder.getDispatcher(),doorServiceOrder.getDispatcherName(),null,msg,message.getOver());
            }
        }
        if (toType.equals("731")) {//调度员派单(派给本社区医生)
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有 居民新增预约 消息!!orderId:" + orderId);
            }else{
                // 设置消息处理完毕
                messages.forEach(
                        message -> {
                            String title = "调度员派单(派给本社区医生)";
                            if("system".equals(doorServiceOrder.getUpdateUser())){
                                title = "系统派单(派给服务医生)";
                            }
                            if (message.getType() .equals("730")) {
                                message.setTitle(title);
                                String msg = doorServiceOrder.getDispatcherName() + "已将服务工单" + doorServiceOrder.getNumber() + "指派给" + doorServiceOrder.getDoctorName() + "医生";
                                saveSystemMessage(message.getId(),message.getRelationCode(),title,"731",doorServiceOrder.getUpdateUser(),doorServiceOrder.getUpdateUserName(),
                                        doorServiceOrder.getUpdateUser(),doorServiceOrder.getUpdateUserName(),null,msg,message.getOver());
                            }else{
                                message.setOver("0");
                                systemMessageDao.save(message);
                            }
                        }
                );
            }
        }
        if (toType.equals("732")){//调度员拒单
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有系统消息!!orderId:" + orderId);
            } else {
                // 432 调度员拒单即取消工单-- 李四拒绝了张三的服务工单12345678
                messages.forEach(
                        message -> {
                            if (message.getType() .equals("730")) {
                                String msg=doorServiceOrder.getDispatcherName() + "拒绝了"+ doorServiceOrder.getPatientName() +"的服务工单" + doorServiceOrder.getNumber();
                                saveSystemMessage(message.getId(),message.getRelationCode(),"调度员拒单","732",doorServiceOrder.getDispatcher(),doorServiceOrder.getDispatcherName(),
                                        doorServiceOrder.getDispatcher(),doorServiceOrder.getDispatcherName(),null,msg,message.getOver());
                            }else{
                                message.setOver("0");
                                systemMessageDao.save(message);
                            }
                        }
                );
            }
        }
        if (toType.equals("patientCancel")){//居民取消 消息列表也应该不显示
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前工单没有系统消息!!orderId:" + orderId);
            } else {
                messages.forEach(
                        message -> {
                            message.setOver("0");
                            systemMessageDao.save(message);
                        }
                );
            }
        }
    }
}

+ 42 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/StreamUtil.java

@ -0,0 +1,42 @@
package com.yihu.jw.care.util;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.io.InputStream;
/***
 * @ClassName: StreamUtil
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/1/5 19:40
 */
public class StreamUtil {
    /**
     *   jar包,读取resources配置
     *   /conclusion.mht    :resources下文件路径以及文件名
     * @return
     * @throws IOException
     */
    public static String readResources() throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("/conclusion.mht");
        Resource resource = resources[0];
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
        InputStream stream = resource.getInputStream();
        StringBuilder buffer = new StringBuilder();
        byte[] bytes = new byte[1024];
        try {
            for (int n; (n = stream.read(bytes)) != -1; ) {
                buffer.append(new String(bytes, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}