Forráskód Böngészése

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

wangzhinan 1 éve
szülő
commit
ddd03e58ce
100 módosított fájl, 13776 hozzáadás és 891 törlés
  1. 20 0
      business/base-service/src/main/java/com/yihu/jw/dict/dao/FrequencyDao.java
  2. 4 4
      business/base-service/src/main/java/com/yihu/jw/hospital/HospitalDao.java
  3. 20 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/MessageNoticeSettingDao.java
  4. 18 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SpecialistDynamicMessagesDao.java
  5. 8 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  6. 175 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/service/SystemMessageService.java
  7. 87 0
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/SignPatientLabelInfoDao.java
  8. 29 6
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyyAdminTeamDao.java
  9. 300 4
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java
  10. 962 0
      business/base-service/src/main/java/com/yihu/jw/jw/service/JwArchivesService.java
  11. 1370 0
      business/base-service/src/main/java/com/yihu/jw/jw/service/JwSmjkService.java
  12. 22 0
      business/base-service/src/main/java/com/yihu/jw/order/dao/ConsultTeamOrderDao.java
  13. 18 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientEventDao.java
  14. 256 189
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  15. 40 0
      business/base-service/src/main/java/com/yihu/jw/system/dao/SystemDictDao.java
  16. 148 0
      business/base-service/src/main/java/com/yihu/jw/system/service/SystemDictService.java
  17. 27 0
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  18. 310 309
      business/im-service/src/main/java/com/yihu/jw/im/util/HttpClientUtil.java
  19. 62 53
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  20. 0 43
      common/common-entity/src/db/sql记录
  21. 2 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/dict/BaseFrequencyDictDO.java
  22. 23 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultDo.java
  23. 22 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/system/SystemDictDO.java
  24. 19 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java
  25. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/SignPatientLabelInfo.java
  26. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceApplicationDo.java
  27. 9 6
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java
  28. 53 0
      common/common-entity/src/main/java/com/yihu/jw/entity/followup/FollowupClassDrugs.java
  29. 178 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/MessageNoticeSetting.java
  30. 191 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SpecialistDynamicMessages.java
  31. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  32. 107 78
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamDO.java
  33. 342 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPatientInfoDO.java
  34. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/AesEncryptUtils.java
  35. 66 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/TransforSqlUtl.java
  36. 107 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatPushLog.java
  37. 2 4
      common/common-entity/src/main/java/com/yihu/jw/entity/third/wlyyinfo/WechatTag.java
  38. 107 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTagLog.java
  39. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplate.java
  40. 147 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateConfig.java
  41. 25 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateData.java
  42. 71 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WeixinTemplate.java
  43. 53 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxAccessTokenLog.java
  44. 23 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxOpenidTemp.java
  45. 56 0
      common/common-util/src/main/java/com/yihu/jw/util/DoctorAssistantUtil.java
  46. 14 0
      common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java
  47. 38 0
      common/common-util/src/main/java/com/yihu/jw/util/encrypt/MD5.java
  48. 181 0
      common/common-util/src/main/java/com/yihu/jw/util/fastdfs/FastDFSClientPool.java
  49. 343 0
      common/common-util/src/main/java/com/yihu/jw/util/fastdfs/FastDFSUtil.java
  50. 31 0
      common/common-util/src/main/java/com/yihu/jw/util/html/HtmlUtil.java
  51. 12 1
      common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java
  52. 364 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtils.java
  53. 6 2
      common/common-util/src/main/java/com/yihu/jw/util/wechat/wxhttp/HttpUtil.java
  54. 6 1
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/config/MultipartConfig.java
  55. 25 25
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/config/TomcatConfig.java
  56. 15 1
      gateway/ag-basic/src/main/resources/application.yml
  57. 2 0
      server/svr-authentication/src/main/java/com/yihu/AuthServer.java
  58. 35 0
      server/svr-authentication/src/main/resources/application.yml
  59. 11 1
      server/svr-authentication/src/main/resources/bootstrap.yml
  60. 1 0
      server/svr-configuration/src/main/resources/application.yml
  61. 2 0
      svr/svr-base/src/main/java/com/yihu/SvrBaseApplication.java
  62. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/base/service/user/UserService.java
  63. 59 0
      svr/svr-base/src/main/resources/application.yml
  64. 12 2
      svr/svr-base/src/main/resources/bootstrap.yml
  65. 82 82
      svr/svr-basic/src/main/java/com/yihu/jw/basic/config/ActiveMQConfig.java
  66. 69 69
      svr/svr-basic/src/main/java/com/yihu/jw/basic/redis/controler/ActiveMQEndpoint.java
  67. 99 0
      svr/svr-basic/src/main/resources/application.yml
  68. 9 8
      svr/svr-basic/src/main/resources/bootstrap.yml
  69. 15 0
      svr/svr-visit-behind/pom.xml
  70. 169 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/async/AsynService.java
  71. 0 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/GcTokenController.java
  72. 385 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java
  73. 3509 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  74. 162 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoctorDoorServiceAuditController.java
  75. 1347 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  76. 324 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java
  77. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationDao.java
  78. 28 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationTempDao.java
  79. 30 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceApplicationDao.java
  80. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceConfigureDao.java
  81. 38 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceOrderDao.java
  82. 29 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceVoucherDao.java
  83. 26 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCancelLogDao.java
  84. 28 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDao.java
  85. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDoctorDao.java
  86. 33 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorConclusionDao.java
  87. 40 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorDao.java
  88. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorFeeDictDao.java
  89. 34 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorStatusDao.java
  90. 41 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorFeeDetailDao.java
  91. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorOrderItemDao.java
  92. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPatientConfirmLogDao.java
  93. 30 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDao.java
  94. 19 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDetailDao.java
  95. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDrugDao.java
  96. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorProcessLogDao.java
  97. 51 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorServiceOrderDao.java
  98. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorTransRecordDao.java
  99. 165 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoctorRegistrationTempService.java
  100. 0 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java

+ 20 - 0
business/base-service/src/main/java/com/yihu/jw/dict/dao/FrequencyDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.dict.dao;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by wzn54 on 2019/1/17.
 */
public interface FrequencyDao extends PagingAndSortingRepository<Frequency, Long>, JpaSpecificationExecutor<Frequency> {
    @Query("select f from Frequency f where  f.del=1 and f.code <> 'bid_2-14' ")
    List<Frequency> findByDel();
    @Query("select f from Frequency  f where f.del=1 and f.code=?1 ")
    Frequency findByCode(String code);
}

+ 4 - 4
business/base-service/src/main/java/com/yihu/jw/hospital/HospitalDao.java

@ -2,14 +2,14 @@ package com.yihu.jw.hospital;
import com.yihu.jw.entity.hospital.DmHospitalDO;
import com.yihu.jw.entity.hospital.team.WlyyAdminTeamDO;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;

+ 20 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/MessageNoticeSettingDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.hospital.message.dao;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author yeshijie on 2017/11/27.
 */
public interface MessageNoticeSettingDao extends PagingAndSortingRepository<MessageNoticeSetting, Long>, JpaSpecificationExecutor<MessageNoticeSetting> {
    @Query("from MessageNoticeSetting a where a.user = ?1 and a.type=?2")
    MessageNoticeSetting findByUserAndType(String user, String type);
//    @Query("from MessageNoticeSetting a where a.id = ?1")
//    MessageNoticeSetting findById(Long id);
}

+ 18 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SpecialistDynamicMessagesDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.hospital.message.dao;
import com.yihu.jw.entity.hospital.message.SpecialistDynamicMessages;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by yeshijie on 2023/5/23.
 */
public interface SpecialistDynamicMessagesDao extends PagingAndSortingRepository<SpecialistDynamicMessages, Long>,
        JpaSpecificationExecutor<SpecialistDynamicMessages> {
    @Query("select m from SpecialistDynamicMessages m where m.createTime>?1 and m.createTime<?2 and m.diseaseType=?3 group by m.name,m.code,m.createTime order by m.createTime desc ")
    Page<SpecialistDynamicMessages> findByTime(String createTime, String endTime, String diseaseType, Pageable pageRequest);
}

+ 8 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java

@ -92,4 +92,12 @@ public interface SystemMessageDao extends JpaRepository<SystemMessageDO, String>
    @Modifying
    @Transactional
    int updateMessageByRelationCode(String relationCode, Integer type);
    @Query("update SystemMessageDO a set a.isRead = 0,a.over = '0' where a.receiver = ?1 and a.relationCode = ?2 and a.type=?3 ")
    @Modifying
    void updateByReceiverAndRelationCode(String receiver, String relationCode, Integer type);
    @Query("select a from SystemMessageDO a where a.type in (401,408) and a.del='1' and a.over='1' and a.state=1")
    List<SystemMessageDO> findMessageByRelationCode2();
}

+ 175 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/message/service/SystemMessageService.java

@ -5,10 +5,18 @@ import com.fasterxml.jackson.databind.ObjectMapper;
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.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import com.yihu.jw.entity.hospital.message.SpecialistDynamicMessages;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.hospital.message.dao.MessageNoticeSettingDao;
import com.yihu.jw.hospital.message.dao.SpecialistDynamicMessagesDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.YkyySMSService;
import com.yihu.jw.utils.hibernate.HibenateUtils;
@ -16,10 +24,12 @@ import com.yihu.jw.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.Map;
/**
 * @author zmk
@ -45,6 +55,15 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    @Autowired
    private HibenateUtils hibenateUtils;
    private final String MESSAGE_NOTICESETTING = "wlyy:message:setting:";
    @Autowired
    private MessageNoticeSettingDao messageNoticeSettingDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    SystemDictService systemDictService;
    @Autowired
    SpecialistDynamicMessagesDao specialistDynamicMessagesDao;
    /**
     * 新增线上就诊消息
@ -183,4 +202,160 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    }*/
    /**
     * 获取消息提示开关
     * @param user
     * @param type
     * @param messageType
     * @return (1开,0关)
     */
    public Boolean getMessageNoticeSettingByMessageType(String user,String type,String messageType){
        Integer re = 0;
        com.alibaba.fastjson.JSONObject setting = getMessageNoticSetting(user,type);
        Integer masterSwitch = setting.getInteger("masterSwitch");
        if(masterSwitch==0){
            return false;
        }
        switch (messageType){
            case "masterSwitch":
                //总开关
                re = masterSwitch;
                break;
            case "imSwitch":
                //im消息开关
                re = setting.getInteger("imSwitch");
                break;
            case "familyTopicSwitch":
                //健管师邀请后推送开关
                Integer imSwitch = setting.getInteger("imSwitch");
                if(imSwitch==1){
                    re = setting.getInteger("familyTopicSwitch");
                }
                break;
            case "signSwitch":
                //签约消息开关
                re = setting.getInteger("signSwitch");
                break;
            case "healthSignSwitch":
                //体征消息开关
                re = setting.getInteger("healthSignSwitch");
                break;
            case "systemSwitch":
                //系统消息开关
                re = setting.getInteger("systemSwitch");
                break;
            case "prescriptionSwitch":
                //续方消息开关
                re = setting.getInteger("prescriptionSwitch");
                break;
            case "soundSwitch":
                //铃声提醒开关
                re = setting.getInteger("soundSwitch");
                break;
            case "vibrationSwitch":
                //振动提醒开关
                re = setting.getInteger("vibrationSwitch");
                break;
            case "coordinationSwitch":
                //协同消息开关
                re = setting.getInteger("coordinationSwitch");
                break;
            default:
                break;
        }
        return re==1;
    }
    /**
     * 获取消息提醒设置
     * @param user
     * @param type
     * @return
     */
    public com.alibaba.fastjson.JSONObject getMessageNoticSetting(String user, String type){
        com.alibaba.fastjson.JSONObject re = null;
        String key = MESSAGE_NOTICESETTING+user+":"+type;
        String response = redisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(response)){
            MessageNoticeSetting messageNoticeSetting = messageNoticeSettingDao.findByUserAndType(user,type);
            if(messageNoticeSetting == null){
                messageNoticeSetting = new MessageNoticeSetting();
                messageNoticeSetting.setCreateTime(new Date());
                messageNoticeSetting.setFamilyTopicSwitch(0);
                messageNoticeSetting.setCoordinationSwitch(1);
                messageNoticeSetting.setHealthSignSwitch(1);
                messageNoticeSetting.setImSwitch(1);
                messageNoticeSetting.setMasterSwitch(1);
                messageNoticeSetting.setPrescriptionSwitch(1);
                messageNoticeSetting.setSignSwitch(1);
                messageNoticeSetting.setSoundSwitch(1);
                messageNoticeSetting.setSystemSwitch(1);
                messageNoticeSetting.setType(type);
                messageNoticeSetting.setUser(user);
                messageNoticeSetting.setVibrationSwitch(1);
                messageNoticeSettingDao.save(messageNoticeSetting);
            }
            response = com.alibaba.fastjson.JSONObject.toJSONString(messageNoticeSetting);
            redisTemplate.opsForValue().set(key,response);
        }
        re = com.alibaba.fastjson.JSONObject.parseObject(response);
        return re;
    }
    //添加专科动态消息
    public void addSpecialistDynamicMessages(BasePatientDO patient, BaseDoctorDO specialist, BaseDoctorDO doctor, String result, String disease, String type, SignFamily signFamily){
        try {
            String patientName = patient.getName();
            String doctorName = "";
            String specialistName = specialist.getName();
            SpecialistDynamicMessages specialistDynamicMessages = new SpecialistDynamicMessages();
            specialistDynamicMessages.setAddress(patient.getAddress());
            specialistDynamicMessages.setResult(result);
            specialistDynamicMessages.setName(patientName);
            specialistDynamicMessages.setCode(patient.getId());
            if(doctor!=null){
//                specialistDynamicMessages.setDoctor(doctor.getCode());
//                specialistDynamicMessages.setHospital(doctor.getHospital());
                doctorName = doctor.getName();
            }else if(signFamily!=null){
                specialistDynamicMessages.setDoctor(signFamily.getDoctor());
                specialistDynamicMessages.setHospital(signFamily.getHospital());
                doctorName = signFamily.getDoctorName();
            }
//            specialistDynamicMessages.setSpecialist(specialist.getCode());
//            specialistDynamicMessages.setSpecialistHospital(specialist.getHospital());
            specialistDynamicMessages.setDiseaseType(disease);
            specialistDynamicMessages.setCodeType("2");
            specialistDynamicMessages.setCreateTime(DateUtil.getStringDate());
            specialistDynamicMessages.setType(type);
            Map<String,String> copywritingMap = systemDictService.getDictMap("DynamicMessages"+type);
            //获取文案模板
            String content = copywritingMap.get("doctor");
            content = content.replace("【医生】",specialistName).replace("【居民】",patientName);
            //【医生】专科医生给您下转了居民【居民】
            //您代居民【居民】预约了【医生】专科医生的门诊
            //您向【医生】专科医生的发起了专科协同,居民【居民】
            //您向【医生】专科医生的发起了咨询求助,居民【居民】
            String specialistContent = copywritingMap.get("specialist");
            specialistContent = specialistContent.replace("【医生】",doctorName).replace("【居民】",patientName);
            //您给社区医生【医生】下转了居民【居民】
            //【医生】社区医生代居民【居民】预约了您的门诊
            //【医生】社区医生向您发起了专科协同,居民【居民】
            //【医生】社区医生向您发起了咨询求组,居民【居民】
            specialistDynamicMessages.setContent(content);
            specialistDynamicMessages.setSpecialistContent(specialistContent);
            specialistDynamicMessagesDao.save(specialistDynamicMessages);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

+ 87 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/SignPatientLabelInfoDao.java

@ -0,0 +1,87 @@
package com.yihu.jw.hospital.team.dao;
import com.yihu.jw.entity.door.SignPatientLabelInfo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by lyr on 2016/10/9.
 */
public interface SignPatientLabelInfoDao extends
        PagingAndSortingRepository<SignPatientLabelInfo, Long>,
        JpaSpecificationExecutor<SignPatientLabelInfo> {
//    /**
//     * 查询某个患者的标签
//     *
//     * @param patient 患者
//     * @param status  状态
//     * @return
//     */
//    List<SignPatientLabelInfo> findByPatientAndStatus(String patient, Integer status);
//
//    /**
//     * 查询某个患者的标签
//     *
//     * @param patient 患者
//     * @param status  状态
//     * @return
//     */
//    @Query("select f from SignPatientLabelInfo f,SignPatientLabel l where f.patient = ?1 and f.status = ?2 and f.label = l.labelCode and f.labelType =l.labelType" +
//            " and l.status = ?2 and (l.labelType <> '4' or l.teamCode = ?3 or ( l.labelType = '4' and l.labelCode in (1,2)) )")
//    List<SignPatientLabelInfo> findByPatientAndStatusByTeam(String patient, Integer status, Long teamCode);
    /**
     * 查询某个患者的某个类型标签
     *
     * @param patient   患者
     * @param labelType 标签类型
     * @param status    状态
     * @return
     */
    List<SignPatientLabelInfo> findByPatientAndLabelTypeAndStatus(String patient, String labelType, Integer status);
//    /**
//     * 查询某个患者的某个类型的某个标签
//     *
//     * @param patient   患者
//     * @param labelCode  标签代码
//     * @param labelType 标签类型
//     * @param status    状态
//     * @return
//     */
//    SignPatientLabelInfo findByPatientAndLabelAndLabelTypeAndStatus(String patient, String labelCode, String labelType, Integer status);
    /**
     * 删除患者的某个标签类型的所有指定状态标签
     *
     * @param patient
     * @param labelType
     * @param status
     * @return
     */
    @Modifying
    @Query("update SignPatientLabelInfo set status = 0 where patient = ?1 and labelType = ?2 and status = ?3")
    int deleteByPatientAndLabelTypeAndStatus(String patient, String labelType, Integer status);
//    @Modifying
//    @Query("update SignPatientLabelInfo set status = 0 where label = ?1 and status = 1")
//    int deleteByLabel(String labelCode);
    /**
     * 更新某个标签名称
     *
     * @param labelName
     * @param labelCode
     * @return
     */
//    @Modifying
//    @Query("update SignPatientLabelInfo a set a.labelName = ?1 where a.label= ?2 and a.labelType = '4' ")
//    int updateLabelName(String labelName, String labelCode);
}

+ 29 - 6
business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyyAdminTeamDao.java

@ -1,20 +1,43 @@
package com.yihu.jw.hospital.team.dao;
import com.yihu.jw.entity.hospital.team.WlyyAdminTeamDO;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.jw.entity.hospital.team.*;
import java.util.List;
public interface WlyyAdminTeamDao extends JpaRepository<WlyyAdminTeamDO, Integer>, JpaSpecificationExecutor<WlyyAdminTeamDO> {
    @Query("from WlyyAdminTeamDO  t where t.orgCode=?1 and t.available=1")
    List<WlyyAdminTeamDO> findTeamByOrgCode(String orgCode, Pageable pageRequest);
    @Query("from WlyyAdminTeamDO  t where t.available=1")
////    @Query("from WlyyAdminTeamDO  t where t.orgCode=?1 and t.available=1")
//    @Query("from WlyyAdminTeamDO  t where t.orgCode=?1 ")
//    List<WlyyAdminTeamDO> findTeamByOrgCode(String orgCode, Pageable pageRequest);
//    @Query("from WlyyAdminTeamDO  t where 1=1 and t.available='1' ")
    @Query("from WlyyAdminTeamDO  t where 1=1  ")
    List<WlyyAdminTeamDO> findTeamAndAvailable();
    @Query(value = "select t.id from WlyyAdminTeamDO t " +
            "where t.specialCode=?1 and t.acceptType=?2 and t.orgCode=?3 and t.available=true")
    Long findTeamID(String specialCode, Integer acceptType, String orgCode);
    @Query(value = "select t.leaderCode from WlyyAdminTeamDO t " +
            "where t.specialCode=?1 and t.acceptType=?2 and t.orgCode=?3 and t.available=true")
    String findTeamLeader(String specialCode, Integer acceptType, String orgCode);
    @Query(value = "select count(1) from WlyyAdminTeamDO t " +
            "where t.specialCode=?1 and t.acceptType=?2 and t.orgCode=?3 and t.available=true ")
    Integer findAcceptTeamCount(String specialCode, Integer acceptType, String orgCode);
//    @Query(value = "select t from WlyyAdminTeamDO t where t.id=?1")
//    WlyyAdminTeamDO findAdminTeamById(Long teamId);
//
//    @Query(value = "select t from WlyyAdminTeamDO t where t.orgCode=?1 and t.leaderCode=?2 and t.available=true ")
//    List<WlyyAdminTeamDO> findAdminTeamByLeaderCode(String hospital,String doctor);
}

+ 300 - 4
business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java

@ -1,13 +1,309 @@
package com.yihu.jw.hospital.team.dao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.team.WlyyAdminTeamDO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface WlyySignFamilyDao extends JpaRepository<SignFamily, Integer>, JpaSpecificationExecutor<SignFamily> {
    @Query("select count(*) from SignFamily  t where t.doctor=?1 and t.status=1")
    Integer getCountByDoctorCode(String doctor);
//    @Query("select count(*) from SignFamily  t where t.doctor=?1 and t.status=1")
//    Integer getCountByDoctorCode(String doctor);
//    @Query("select count(1) from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
//    int hasSingStatus(String idcard);
//    @Modifying
//    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1")
//    int updatePatientMobile(String patient, String mobile);
//    @Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
//    SignFamily findByPatientStatus(String idcard, int status);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and status = ?2 and a.type = 2")
//    SignFamily findByPatientCodeStatus(String patient, int status);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and status >= ?2 and a.type = 2")
//    SignFamily findByPatientCodeStatus2(String patient, int status);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
//    SignFamily findByPatientAndType(String patient, int type);
//
//    SignFamily findByCodeAndType(String code, Integer type);
//
//    SignFamily findByTeamCode(String TeamCode);
//
//    @Query("select a from SignFamily a where a.teamCode = ?1 and a.type = 2 and a.code=?2")
//    List<SignFamily> findByTeamCodeIsValid(String teamCode, String code);
//
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0")
//    SignFamily findByDoctorPatient(String doctor, String patient);
//
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and (a.type = 2 or a.type=1) and a.status >= 0")
//    List<SignFamily> findSSandFamilyByDoctorPatient(String doctor, String patient);
//
//    @Query("select a from SignFamily a where a.doctorHealth = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0 ")
//    SignFamily findByDoctorHealthPatient(String doctor, String patient);
//    @Query("select p from BasePatientDO p,SignFamily a where a.doctorHealth = ?1  and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
//    List<BasePatientDO> findByDoctorHealthPatient(String doctor, Long team);
//
//    @Query("select p from BasePatientDO p,SignFamily a where a.doctor = ?1 and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
//    List<BasePatientDO> findByDoctorPatient(String doctor, Long team);
//    @Query("select a from SignFamily a,DoctorTeamMember w " +
//            "where a.teamCode = w.team and w.del = '1' and w.memberCode = ?1 and a.patient = ?2 and a.status > 0 ")
//    List<SignFamily> findByDoctorAndPatient(String doctor, String patient);
//    @Query(value = "select a from SignFamily a where a.doctor =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
//    List<SignFamily> findByDoctorAndPatientIsValid(String doctor, String patient, String signYear);
//
//    @Query(value = "select a from SignFamily a where a.doctorHealth =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
//    List<SignFamily> findByDoctorHealthAndPatientIsValid(String doctorHealth, String patient, String signYear);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 2")
    SignFamily findByFamilyDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 1")
    SignFamily findBySanshiDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status > 0 and a.expensesStatus ='1'")
    SignFamily getExpensesSignByIdcard(String idcard);
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type =1 and a.status >= 0")
//    SignFamily findSSByIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 ")
//    List<SignFamily> findAllByIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.status >= 0")
//    List<SignFamily> findSSandJTByIdcard(String idcard);
//    // 拒绝解约
//    @Modifying
//    @Query("update SignFamily a set a.status = 1 where a.patient = ?1 and a.status = 2 and a.type = 2")
//    int refuseSurrender(String patient);
//
//    // 查询患者已生效的家庭签约
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status > 0")
//    SignFamily findSignByPatient(String patient);
//
//    @Modifying
//    @Query("update SignFamily a set a.openid = ?1 where a.patient = ?2")
//    int updateOpenidByPatient(String openid, String patient);
    // 查询已签约的总数
//    @Query("select count(1) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and (a.status = 1 or a.status = 2) and a.type = 2")
//    int countAmountSignedByDoctor(String doctor);
    // 查询待签约总数
//    @Query("select count(1) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and a.status = 0 and a.type = 2")
//    int countAmountUnsignByDoctor(String doctor);
    @Query("select a from SignFamily a where a.mobile = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByMobile(String mobile);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 1")
//    SignFamily findBySanshiPatient(String code);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 0")
//    SignFamily findBySsPatient(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 1")
    SignFamily findByjiatingPatient(String code);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status = 1")
//    SignFamily findByjiatingPatientYes(String code);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status = 1")
//    SignFamily findBySanshiPatientYes(String id);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status in (0,1,2,3)")
//    SignFamily findByPatientSanshiSignInfo(String idCard);
//
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status in (0,1,2,3)")
//    SignFamily findByPatientFamilySignInfo(String idCard);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >=0")
//    SignFamily findByjiatingPatientStatus0(String patient);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 1 and a.status in (0,1,2)")
//    SignFamily findSanshiSignByPatient(String patientCode);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status in (0,1,2)")
//    SignFamily findFamilySignByPatient(String patientCode);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status =-4 and a.signYear =?2")
//    SignFamily findFamilySignByPatientOverDue(String patientCode, String signYear);
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatients(String doctor);
//
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and p.name like ?2 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsLikeName(String doctor, String name);
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsBySignType(String doctor, int type);
//
//    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and p.name like ?3 and a.patient = p.code and a.status in (1,2,3)")
//    List<Object> findDoctorSignPatientsByTypeName(String doctor, int type, String name);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 0")
    SignFamily findByPatient(String patient);
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.signYear =?2 and a.status in (-4,1,2,3) order by a.id desc ")
//    List<SignFamily> findByPatientsLastYear(String patient, String signYear);
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status >= 0")
//    SignFamily findBySanshiIdcard(String idcard);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status > 0")
//    SignFamily findSignByPatient(String patient, int type);
    SignFamily findByCode(String code);
//    @Query(" from SignFamily a where a.patient = ?1 and a.type = ?2 and (a.status=-3 or a.status=-4)  order by a.id desc")
//    List<SignFamily> findLastJySignByPatient(String patient, int type);
//    @Query(" from SignFamily a where  a.type =1 and unix_timestamp(a.czrq)=unix_timestamp( ?1 )  ")
//    List<SignFamily> findByDate(String s);
//    @Modifying
//    @Query("update SignFamily set expenses_type = ?1 where patient = ?2 and status > 0 and type = 2")
//    int updateExpensesType(String expensesType, String patient);
//
//    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 1")
//    int countPatientSsSign(String patient);
//
//    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 2")
//    int countPatientJtSign(String patient);
    // 查询患者已生效的家庭签约
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status = 0")
    SignFamily findSigningByPatient(String patient);
    //找出家庭签约中 团队是空的值
    @Query("select a from SignFamily a where a.type = 2 and a.status = 1 and a.adminTeamId is null")
    List<SignFamily> findBySignTypeAndTeamCode();
    //找出没有健康管理师的签约数据
    @Query("select a from SignFamily a where a.type = 2 and a.status >= 1 and a.doctorHealth is null and a.adminTeamId = ?1 order by a.czrq desc")
    List<SignFamily> findNoHealthSignFamilyNum(Long teamCode);
//
//    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 order by a.id")
//    Page<SignFamily> findByTypeAndSignSource(Integer type, String signSource, Pageable pageable);
//
//    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 and a.id >= ?3 and a.id <= ?4 order by a.id")
//    Page<SignFamily> findByTypeAndSignSourceAndId(Integer type, String signSource, Long start, Long end, Pageable pageable);
//
//    @Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
//    List<SignFamily> findAllSignByPatient(String patient);
    /**
     * 获取所有有效的签约信息(不包含-1 -2)
     *
     * @param patient
     * @return
     */
//    @Query("select a from SignFamily a where a.patient = ?1 and a.status <> -1 and a.status <> -2 order by a.czrq")
//    List<SignFamily> findAllActiveSignByPatient(String patient);
//
//    @Query("select a.patient from SignFamily a where a.doctor = ?1 and a.type = 2 and a.status > 0 and a.doctorHealth is null")
//    List<String> findNohealthByDoctor(String doctor);
    /**
     * 获取团队中有效的患者
     *
     * @param teamCode
     * @param status
     * @return
     */
//    @Query("select count(f) from SignFamily f where f.adminTeamId = ?1 and f.status >= ?2 ")
//    int findByAdminTeamIdAndStatus(long teamCode, int status);
//
//    @Query("select f from SignFamily f where f.patient = ?1 and f.adminTeamId = ?2 and f.status > 0 and f.type = ?3")
//    SignFamily findByPatientAndAdminTeamId(String patient, Long teamCode, Integer type);
//
//    @Query(value = " select a.*  from wlyy_sign_family a where a.patient = ?1  and a.status = -4 order by a.apply_date desc limit 0,1", nativeQuery = true)
//    SignFamily findOutTimeSigningByPatient(String patient);
    //      完成缴费后更新签约开始时间begin 缴费状态expensesStatus 医保流水号medical_insurance_num  扣费时间expenses_time
//    @Modifying
//    @Query("update SignFamily a set a.begin = ?2 ,a.medicalInsuranceNum=?3,a.expensesStatus = ?4,a.expensesTime = ?2,a.signPaySource = ?5 where a.code = ?1 ")
//    int updatePatientBegin(String code, Date begin, String medicalInsuranceNum, String expensesStatus, int signPaySource );
//
//    //查询65岁以上一年内未体检且未系统提醒的签约居民
//    @Query(value = "SELECT DISTINCT t1.* FROM wlyy_sign_family t1 LEFT JOIN wlyy_physical_examination_records r ON r.patient_code=t1.patient WHERE r.patient_code IS NULL " +
//            " AND t1.STATUS>0 AND t1.hospital=?1 AND(YEAR(curdate())-IF(length(idcard)=18,substring(idcard,7,4),IF(length(idcard)=15,concat('19',substring(idcard,7,2)),NULL)))>=65 " +
//            " AND t1.idcard NOT IN(SELECT DISTINCT s.idcard FROM wlyy_sign_family s,wlyy_old_people_physical_examination o WHERE s.hospital=?1 AND s.`status`>0 AND s.idcard=o.id_card " +
//            " AND o.medical_time>?2 )ORDER BY t1.openid DESC,CONVERT(t1.NAME USING gbk) ",nativeQuery = true)
//    List<SignFamily> findExaminationByHospital(String hospital,Date examinationTime);
//
//    //查询wlyy_sign_family有续签却未同步到wlyy_sign_family_renew_log数据
//    @Query(value = "SELECT f.* FROM wlyy_sign_family f LEFT JOIN wlyy_sign_family_renew_log r ON f.`code` = r.sign_code WHERE r.sign_code IS NULL  " +
//            " AND f.renew_flag IN (1, 2) AND f.`status` IN (1, 2)  ",nativeQuery = true)
//    List<SignFamily> findRenew();
//
//    //根据身份证号查询最近的已到期签约数据
//    @Query(value = "SELECT f.* FROM wlyy_sign_family f WHERE f.idcard = ?1 and f.`status` = -4 ORDER BY sign_year desc LIMIT 0,1 ",nativeQuery = true)
//    SignFamily findLatelyRenew(String idcard);
//
//    //查询wlyy_sign_family有效签约且居民的医疗保险号为空的数据
//    @Query(value = "select a.idcard from wlyy_sign_family a left join wlyy_patient b on a.idcard = b.idcard where a.hospital = ?1 and (a.type = 2 or a.type = 1) " +
//            "and a.status = 1 and a.expenses_status = 1 and (b.medicare_number is null or b.medicare_number = '')", nativeQuery = true)
//    List<String> findIdcardByStatus(String hospital);
//
//    /**
//     * 判断是否已存在待处理签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status = 0")
//    SignFamily findByIdcardPre(String idcard);
//
//    /**
//     * 判断是否存在去年签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.signYear=?2 and a.type = 2 and (a.status= -4 or a.status>0) and a.expensesStatus = '1'")
//    SignFamily findOldSign(String idcard,String signYear);
//
//    /**
//     * 【临时】清洗
//     */
//    List<SignFamily> findByRenewFlag(String renewflag);
//
//    /**
//     * 【临时】清洗未扣费
//     */
//    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='0' and a.signYear='2017'")
//    List<SignFamily> findNoExpenses(Pageable pageable);
//
//    /**
//     * 【临时】退费
//     */
//    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='3' and a.signYear='2017'")
//    List<SignFamily> findReCharge();
//
//    /**
//     * 通过医生原有团队是否有签约
//     */
//    @Query("select a from SignFamily a where a.doctor = ?1 and a.adminTeamId =?2 and a.status > 0")
//    List<SignFamily> findByDoctorAndAdminTeamCode(String doctor,Long adminTeamCode);
//
//    /**
//     * 判断是否三师签约
//     */
//    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status > 0")
//    SignFamily findSanshiByIdcard(String idcard);
}

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 962 - 0
business/base-service/src/main/java/com/yihu/jw/jw/service/JwArchivesService.java


A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 1370 - 0
business/base-service/src/main/java/com/yihu/jw/jw/service/JwSmjkService.java


+ 22 - 0
business/base-service/src/main/java/com/yihu/jw/order/dao/ConsultTeamOrderDao.java

@ -1,6 +1,8 @@
package com.yihu.jw.order.dao;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
@ -26,4 +28,24 @@ public interface ConsultTeamOrderDao extends JpaRepository<ConsultTeamDo, String
	@Query("select count(id) from  ConsultTeamDo a where a.type = ?1 and a.doctor = ?2 and a.czrq >=?3 and a.czrq <=?4")
	Integer  countByTime(int type, String doctor, Date startTime, Date endTime);
	ConsultTeamDo queryByRelationCode(String relationCode);
	//名医咨询 -我咨询的 带symptoms 根据status
	@Query("select a from ConsultTeamDo a, ConsultTeamDoctorDo b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2 and a.id < ?3 and a.symptoms like ?4 and a.del = '1' and b.del = '1' and b.from is null")
	Page<ConsultTeamDo> findMyFamousDoctorListByStatus(String uid, int status, long id, String title, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms 根据status
	@Query("select a from ConsultTeamDo a, ConsultTeamDoctorDo b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.symptoms like ?3 and a.del = '1' and b.del = '1' and b.from is null")
	Page<ConsultTeamDo> findMyFamousDoctorListByStatus(String uid, int status, String title, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms根据status
	@Query("select a from ConsultTeamDo a, ConsultTeamDoctorDo b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.id < ?3 and  a.del = '1' and b.del = '1' and b.from is null")
	Page<ConsultTeamDo> findMyFamousDoctorListByStatus(String uid, int status, long id, Pageable pageRequest);
	//名医咨询 -我咨询的 带symptoms根据status
	@Query("select a from ConsultTeamDo a, ConsultTeamDoctorDo b where a.consult = b.consult and (a.type=6 or a.type=7 ) and a.patient = ?1 and a.status=?2  and a.del = '1' and b.del = '1' and b.from is null")
	Page<ConsultTeamDo> findMyFamousDoctorListByStatus(String uid, int status, Pageable pageRequest);
}

+ 18 - 0
business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientEventDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.patient.dao;
import com.yihu.jw.entity.patient.PatientEvent;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientEventDao extends PagingAndSortingRepository<PatientEvent, Long>, JpaSpecificationExecutor<PatientEvent> {
      @Query("select a from PatientEvent a where a.patient = ?1 order by a.eventDate desc")
      List<PatientEvent> findByPatient(String patient) throws Exception;
      @Query("select a from PatientEvent a where a.patient = ?1 and a.eventType = ?2 order by a.eventDate desc")
      List<PatientEvent> findByPatientAndEventType(String patient, String type) throws Exception;
}

+ 256 - 189
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -14,6 +14,7 @@ import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.dao.WlyyInspectionDao;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.jw.service.JwArchivesService;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientGroupDao;
@ -45,11 +46,9 @@ import java.io.IOException;
import java.util.*;
/**
 * 
 * 居民基础信息服务service
 * 
 * @version 
 * <pre>
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * litaohong    1.0  2018年08月31日 Created
 *
@ -62,67 +61,79 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BasePatientMedicardCardService basePatientMedicardCardService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private YkyyService ykyyService;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private OutpatientDao outpatientDao;
    @Value("${demo.flag}")
    private boolean demoFlag;
    @Value("${wechat.flag}")
    private boolean flag;
    @Autowired
    private WlyyInspectionDao wlyyInspectionDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private HealthCareService healthCareService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private BasePatientGroupDao basePatientGroupDao;
    @Autowired
    private BasePatientGroupDictDao basePatientGroupDictDao;
    @Autowired
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private HealthCareService healthCareService;
    JwArchivesService jwArchivesService;
    @Value("${wechat.id}")
    private String wxId;
    @Value("${demo.flag}")
    private boolean demoFlag;
    @Value("${wechat.flag}")
    private boolean flag;
    /**
     * 居民id
     *
     * @param patientId
     * @return
     */
    public BasePatientDO findPatientById(String patientId) throws Exception{
    public BasePatientDO findPatientById(String patientId) throws Exception {
        return basePatientDao.findById(patientId).orElse(null);
    }
    public boolean findByIdCard(String idcard){
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard,"1");
    public boolean findByIdCard(String idcard) {
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard, "1");
        if (patientDO != null) {
            return true;
        }
        return false;
    }
    public BasePatientDO findInfoByIdCard(String idcard) {
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard, "1");
        return patientDO;
    }
    /**
     * 居民id
     *
     * @param patientId
     * @return
     */
    public Map getPatientById(String patientId) throws Exception{
    public Map getPatientById(String patientId) throws Exception {
        Map result = new HashMap();
        if(StringUtils.isEmpty(patientId)){
            result.put("result","parameter patientId is null");
        if (StringUtils.isEmpty(patientId)) {
            result.put("result", "parameter patientId is null");
            return result;
        }
        BasePatientDO basePatientDO = basePatientDao.findById(patientId).orElse(null);
@ -134,27 +145,28 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        result.put("patient", basePatientDO);
        List<PatientMedicareCardDO> cards = basePatientMedicardCardService.findPatientCardByCode(patientId);
        if (cards==null||cards.size()==0){
        if (cards == null || cards.size() == 0) {
            System.out.println("new一个list");
            PatientMedicareCardDO patientMedicareCardDO = new PatientMedicareCardDO();
            cards.add(patientMedicareCardDO);
        }
        result.put("medicareCard",cards);
        result.put("medicareCard", cards);
        return result;
    }
    /**
     * 获取用户基础信息,参数为空查全部
     *
     * @param nameOrIdcard
     * @param page
     * @param size
     * @param sorts
     * @return
     */
    public MixEnvelop queryPatientBaseInfo(String nameOrIdcard, int page, int size, String sorts)throws Exception{
    public MixEnvelop queryPatientBaseInfo(String nameOrIdcard, int page, int size, String sorts) throws Exception {
        List<Map<String, Object>> result = new ArrayList<>();
        String param = null == nameOrIdcard ? "": nameOrIdcard;
        String param = null == nameOrIdcard ? "" : nameOrIdcard;
        String sql = "SELECT\n" +
                "\tID AS \"id\",\n" +
                "\tidcard AS \"idcard\",\n" +
@ -177,24 +189,24 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
                " address AS \"address\"\n" +
                "FROM\n" +
                "\tbase_patient\n";
        if (StringUtils.isNotEmpty(nameOrIdcard)){
            sql+="WHERE\n" +
                    "\tNAME LIKE '%"+nameOrIdcard+"%'\n" +
                    "OR idcard LIKE '%"+nameOrIdcard+"%'\n";
        if (StringUtils.isNotEmpty(nameOrIdcard)) {
            sql += "WHERE\n" +
                    "\tNAME LIKE '%" + nameOrIdcard + "%'\n" +
                    "OR idcard LIKE '%" + nameOrIdcard + "%'\n";
        }
        sql+="ORDER BY\n" +
        sql += "ORDER BY\n" +
                "\tcreate_time DESC";
        String condition ="";
        if (StringUtils.isNoneBlank(param)){
        String condition = "";
        if (StringUtils.isNoneBlank(param)) {
            condition = "where name like '%" + param + "%' or idcard like '%" + param + "%'";
        }
        String countSql = "select count(id) from base_patient "+condition;
        Long count  = jdbcTemplate.queryForObject(countSql,Long.class);
        if(count <= 0){
        String countSql = "select count(id) from base_patient " + condition;
        Long count = jdbcTemplate.queryForObject(countSql, Long.class);
        if (count <= 0) {
            return null;
        }
        MixEnvelop envelop = new MixEnvelop();
        result = hibenateUtils.createSQLQuery(sql,page,size);
        result = hibenateUtils.createSQLQuery(sql, page, size);
        envelop.setDetailModelList(result);
        envelop.setTotalCount(count.intValue());
        envelop.setCurrPage(page);
@ -204,6 +216,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    /**
     * 新增居民
     *
     * @param jsonData
     * @return
     */
@ -212,14 +225,14 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        JSONArray patientMedicareCards = jsonObject.getJSONArray("medicareCard");
        if(null == patient || CollectionUtils.isEmpty(patientMedicareCards)){
        if (null == patient || CollectionUtils.isEmpty(patientMedicareCards)) {
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(), BasePatientDO.class);
        List<PatientMedicareCardDO> list = new ArrayList<>();
        patientMedicareCards.forEach((card)->{
        patientMedicareCards.forEach((card) -> {
            try {
                list.add(objectMapper.readValue(card.toString(),PatientMedicareCardDO.class));
                list.add(objectMapper.readValue(card.toString(), PatientMedicareCardDO.class));
            } catch (IOException e) {
                e.printStackTrace();
            }
@ -231,6 +244,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    /**
     * 新增档案
     *
     * @param jsonData
     * @return
     */
@ -238,27 +252,28 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    public String createArchive(String jsonData) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        if(null == patient){
        if (null == patient) {
            return ConstantUtils.FAIL;
        }
        BasePatientDO patientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        BasePatientDO patientDO = objectMapper.readValue(patient.toJSONString(), BasePatientDO.class);
        this.save(patientDO);
        return ConstantUtils.SUCCESS;
    }
    /**
     * 修改档案
     *
     * @param jsonData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateArchive(String jsonData) throws Exception {
        BasePatientDO basePatientDO = objectMapper.readValue(jsonData,BasePatientDO.class);
        if(StringUtils.isEmpty(basePatientDO.getId())){
        BasePatientDO basePatientDO = objectMapper.readValue(jsonData, BasePatientDO.class);
        if (StringUtils.isEmpty(basePatientDO.getId())) {
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO1 = basePatientDao.findById(basePatientDO.getId()).orElse(null);
        if (null!=basePatientDO1){
        if (null != basePatientDO1) {
            basePatientDO1.setName(basePatientDO.getName());
            basePatientDO1.setMobile(basePatientDO.getMobile());
@ -284,15 +299,15 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
            basePatientDO1.setAddress(basePatientDO.getAddress());
            basePatientDO1.setPhoto(basePatientDO.getPhoto());
            basePatientDO1.setArchiveStatus(basePatientDO.getArchiveStatus());
            if("hz_yyyzh_wx".equalsIgnoreCase(wxId)){//杭州医养头像初始化
                if (org.apache.commons.lang3.StringUtils.isBlank(basePatientDO1.getPhoto())){
                    String hzPhoto= getHzAvatar(1,null,basePatientDO1.getArchiveType()+"",null==basePatientDO1.getSex()?"":basePatientDO1.getSex()+"",basePatientDO1.getIdcard());
            if ("hz_yyyzh_wx".equalsIgnoreCase(wxId)) {//杭州医养头像初始化
                if (org.apache.commons.lang3.StringUtils.isBlank(basePatientDO1.getPhoto())) {
                    String hzPhoto = getHzAvatar(1, null, basePatientDO1.getArchiveType() + "", null == basePatientDO1.getSex() ? "" : basePatientDO1.getSex() + "", basePatientDO1.getIdcard());
                    basePatientDO1.setPhoto(hzPhoto);
                }else{
                    String sql = " select count(id) from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_value='"+basePatientDO1.getPhoto()+"' ";
                    Integer defaultAvatar =  jdbcTemplate.queryForObject(sql,Integer.class);
                    if (defaultAvatar>0){
                        String hzPhoto= getHzAvatar(1,null,basePatientDO1.getArchiveType()+"",null==basePatientDO1.getSex()?"":basePatientDO1.getSex()+"",basePatientDO1.getIdcard());
                } else {
                    String sql = " select count(id) from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_value='" + basePatientDO1.getPhoto() + "' ";
                    Integer defaultAvatar = jdbcTemplate.queryForObject(sql, Integer.class);
                    if (defaultAvatar > 0) {
                        String hzPhoto = getHzAvatar(1, null, basePatientDO1.getArchiveType() + "", null == basePatientDO1.getSex() ? "" : basePatientDO1.getSex() + "", basePatientDO1.getIdcard());
                        basePatientDO1.setPhoto(hzPhoto);
                    }
                }
@ -305,6 +320,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    /**
     * 修改居民
     *
     * @param jsonData
     * @return
     */
@ -313,15 +329,15 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        JSONObject patient = jsonObject.getJSONObject("patient");
        JSONArray patientMedicareCards = jsonObject.getJSONArray("medicareCard");
        if(null == patient || CollectionUtils.isEmpty(patientMedicareCards)){
        if (null == patient || CollectionUtils.isEmpty(patientMedicareCards)) {
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        if(StringUtils.isEmpty(basePatientDO.getId())){
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(), BasePatientDO.class);
        if (StringUtils.isEmpty(basePatientDO.getId())) {
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO1 = basePatientDao.findById(basePatientDO.getId()).orElse(null);
        if (null!=basePatientDO1){
        if (null != basePatientDO1) {
            basePatientDO1.setName(basePatientDO.getName());
            basePatientDO1.setSex(basePatientDO.getSex());
            basePatientDO1.setIdcard(basePatientDO.getIdcard());
@ -346,18 +362,18 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
            basePatientDO1.setResidentialArea(basePatientDO.getResidentialArea());
            basePatientDO1.setCommitteeCode(basePatientDO.getCommitteeCode());
            basePatientDO1.setCommitteeName(basePatientDO.getCommitteeName());
            if(StringUtils.isNotBlank(basePatientDO.getYktId())){
            if (StringUtils.isNotBlank(basePatientDO.getYktId())) {
                basePatientDO1.setYktId(basePatientDO.getYktId());
            }
            if("hz_yyyzh_wx".equalsIgnoreCase(wxId)){//杭州医养头像初始化
                if (org.apache.commons.lang3.StringUtils.isBlank(basePatientDO1.getPhoto())){
                    String hzPhoto= getHzAvatar(1,null,basePatientDO1.getArchiveType()+"",null==basePatientDO1.getSex()?"":basePatientDO1.getSex()+"",basePatientDO1.getIdcard());
            if ("hz_yyyzh_wx".equalsIgnoreCase(wxId)) {//杭州医养头像初始化
                if (org.apache.commons.lang3.StringUtils.isBlank(basePatientDO1.getPhoto())) {
                    String hzPhoto = getHzAvatar(1, null, basePatientDO1.getArchiveType() + "", null == basePatientDO1.getSex() ? "" : basePatientDO1.getSex() + "", basePatientDO1.getIdcard());
                    basePatientDO1.setPhoto(hzPhoto);
                }else{
                    String sql = " select count(id) from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_value='"+basePatientDO1.getPhoto()+"' ";
                    Integer defaultAvatar =  jdbcTemplate.queryForObject(sql,Integer.class);
                    if (defaultAvatar>0){
                        String hzPhoto= getHzAvatar(1,null,basePatientDO1.getArchiveType()+"",null==basePatientDO1.getSex()?"":basePatientDO1.getSex()+"",basePatientDO1.getIdcard());
                } else {
                    String sql = " select count(id) from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_value='" + basePatientDO1.getPhoto() + "' ";
                    Integer defaultAvatar = jdbcTemplate.queryForObject(sql, Integer.class);
                    if (defaultAvatar > 0) {
                        String hzPhoto = getHzAvatar(1, null, basePatientDO1.getArchiveType() + "", null == basePatientDO1.getSex() ? "" : basePatientDO1.getSex() + "", basePatientDO1.getIdcard());
                        basePatientDO1.setPhoto(hzPhoto);
                    }
                }
@ -373,13 +389,13 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
            PatientMedicareCardDO card = objectMapper.readValue(obj.toString(), PatientMedicareCardDO.class);
            card.setPatientCode(basePatientDO.getId());
            card.setDel("1");
            if(cardIdList.contains(card.getId())){
            if (cardIdList.contains(card.getId())) {
                cardIdList.remove(card.getId());
            }
            basePatientMedicardCardService.save(card);
        }
        // 有些卡可能是删除的
        if(cardIdList.size() > 0){
        if (cardIdList.size() > 0) {
            basePatientMedicardCardService.delete(cardIdList.toArray());
        }
        return ConstantUtils.SUCCESS;
@ -387,30 +403,31 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    /**
     * 根据patient的id获取居民信息
     *
     * @param patient
     * @return
     */
    public BasePatientDO findByIdAndDel(String patient) throws Exception{
    public BasePatientDO findByIdAndDel(String patient) throws Exception {
        BasePatientDO basePatientDO = basePatientDao.findById(patient).orElse(null);
        if(basePatientDO==null){
        if (basePatientDO == null) {
            throw new Exception("用户不存在");
        }
        Boolean flag = healthCareService.isHospitalFlag();
        if (flag){
            if(wxId.equalsIgnoreCase("xm_xzzx_wx")){
        if (flag) {
            if (wxId.equalsIgnoreCase("xm_xzzx_wx")) {
                String result = healthCareService.authorizedToEntrace(basePatientDO.getId());
                JSONObject object = JSONObject.parseObject(result);
                if (object.getString("flag").equalsIgnoreCase("1")){
                if (object.getString("flag").equalsIgnoreCase("1")) {
                    JSONObject encryptData = object.getJSONObject("encrypt_data");
                    String state = encryptData.getString("state");
                    String auth_date = encryptData.getString("auth_date");
                    basePatientDO.setMedicalState(state);
                    basePatientDO = basePatientDao.save(basePatientDO);
                }
            }else {
            } else {
                String result = healthCareService.authorized(basePatientDO.getId());
                JSONObject object = JSONObject.parseObject(result);
                if (object.getString("flag").equalsIgnoreCase("1")){
                if (object.getString("flag").equalsIgnoreCase("1")) {
                    JSONObject encryptData = object.getJSONObject("encrypt_data");
                    String state = encryptData.getString("state");
                    String auth_date = encryptData.getString("auth_date");
@ -424,29 +441,30 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    /**
     * 根据patient的id获取居民信息
     *
     * @param mobile
     * @return
     */
    public BasePatientDO findByMobileAndDel(String mobile) throws Exception{
        List<BasePatientDO> list = basePatientDao.findByMobileAndDel(mobile,"1");
        if(list.size()<=0){
    public BasePatientDO findByMobileAndDel(String mobile) throws Exception {
        List<BasePatientDO> list = basePatientDao.findByMobileAndDel(mobile, "1");
        if (list.size() <= 0) {
            return null;
        }
        return list.get(0);
    }
    public Boolean updatePatientPw(String id,String pw,String orgPw){
    public Boolean updatePatientPw(String id, String pw, String orgPw) {
        BasePatientDO patientDO = basePatientDao.findById(id).orElse(null);
        if (!"xm_ykyy_wx".equalsIgnoreCase(wxId)){
        if (!"xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            String orgPwMd5 = MD5.md5Hex(orgPw + "{" + patientDO.getSalt() + "}");
            if(!orgPwMd5.equals(patientDO.getPassword())){
            if (!orgPwMd5.equals(patientDO.getPassword())) {
                return false;
            }
        }
        //认证信息设置
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            String response =ykyyService.updatePatientPassword(patientDO.getMobile(),pw,"");
            if (StringUtils.isNoneBlank(response)&&response.contains("10000")){
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            String response = ykyyService.updatePatientPassword(patientDO.getMobile(), pw, "");
            if (StringUtils.isNoneBlank(response) && response.contains("10000")) {
                String salt = randomString(5);
                patientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                patientDO.setSalt(salt);
@ -468,19 +486,21 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        saveDoctorPwlimitDate(id);*/
        return true;
    }
    public Map<String,Object> getPatientCountByDoctor(String doctor,String patient) throws  Exception{
        List<WlyyOutpatientDO> fzList = outpatientDao.findByDoctorAndOutpatientType(doctor,"1",patient);
        List<WlyyOutpatientDO> xtList = outpatientDao.findByDoctorAndOutpatientType(doctor,"2",patient);
        List<WlyyOutpatientDO> zxList = outpatientDao.findByDoctorAndOutpatientType(doctor,"3",patient);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("fzNum",fzList==null?0:fzList.size());
        resultMap.put("xtNum",xtList==null?0:xtList.size());
        resultMap.put("zxNum",zxList==null?0:zxList.size());
    public Map<String, Object> getPatientCountByDoctor(String doctor, String patient) throws Exception {
        List<WlyyOutpatientDO> fzList = outpatientDao.findByDoctorAndOutpatientType(doctor, "1", patient);
        List<WlyyOutpatientDO> xtList = outpatientDao.findByDoctorAndOutpatientType(doctor, "2", patient);
        List<WlyyOutpatientDO> zxList = outpatientDao.findByDoctorAndOutpatientType(doctor, "3", patient);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fzNum", fzList == null ? 0 : fzList.size());
        resultMap.put("xtNum", xtList == null ? 0 : xtList.size());
        resultMap.put("zxNum", zxList == null ? 0 : zxList.size());
        return resultMap;
    }
    //查询电子病历
        public MixEnvelop findEmrByPatientId(String patient,String doctor,Integer page ,Integer pageSize){
        String sql ="select e.id as \"id\"," +
    public MixEnvelop findEmrByPatientId(String patient, String doctor, Integer page, Integer pageSize) {
        String sql = "select e.id as \"id\"," +
                " e.prescription_id as \"prescriptionId\"," +
                " e.complaint as \"complaint\"," +
                " e.medical_history as \"medicalHistory\"," +
@ -496,15 +516,15 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
                " from wlyy_prescription_emr e " +
                " left join  wlyy_prescription p on e.prescription_id = p.id" +
                " where p.status >= 20";
        if (StringUtils.isNoneBlank(patient)){
            sql+=" and p.patient_code ='"+patient+"'";
        if (StringUtils.isNoneBlank(patient)) {
            sql += " and p.patient_code ='" + patient + "'";
        }
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and p.doctor ='"+doctor+"'";
        if (StringUtils.isNoneBlank(doctor)) {
            sql += " and p.doctor ='" + doctor + "'";
        }
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, pageSize);
        MixEnvelop mixEnvelop = new MixEnvelop();
        mixEnvelop.setTotalCount(list==null?0:list.size());
        mixEnvelop.setTotalCount(list == null ? 0 : list.size());
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setDetailModelList(list);
@ -552,6 +572,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        mixEnvelop.setDetailModelList(list);
        return mixEnvelop;
    }*/
    /**
     * 查询患者所有处方信息
     *
@ -559,36 +580,36 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
     * @param size
     * @return
     */
    public PageEnvelop findPatientAllPrescription(String doctor,String keyName, String status, Integer page, Integer size,String patient,String isSelectDrug) {
    public PageEnvelop findPatientAllPrescription(String doctor, String keyName, String status, Integer page, Integer size, String patient, String isSelectDrug) {
        BasePatientDO patientDO = basePatientDao.findById(patient).orElse(null);
        if (patientDO==null){
            return PageEnvelop.getError("找不到该患者",-1);
        if (patientDO == null) {
            return PageEnvelop.getError("找不到该患者", -1);
        }
        StringBuffer sql = new StringBuffer(" SELECT DISTINCT b.*, c.oneself_pickup_flg,f.job_title_code,f.job_title_name  FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        StringBuffer countSql = new StringBuffer("select COUNT(DISTINCT b.id) count FROM (SELECT a.* FROM wlyy_prescription a left join wlyy_outpatient o ON o.id=a.outpatient_id  WHERE o.consumer = '");
        sql.append(patient).append("') b  LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        countSql.append(patient).append("') b  LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        if (StringUtils.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
        if (StringUtils.isNoneBlank(isSelectDrug)) {
            if ("0".equalsIgnoreCase(isSelectDrug)) {
                sql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
                countSql.append(" left join wlyy_inspection m on b.outpatient_id =m.outpatient_id");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
            if ("1".equalsIgnoreCase(isSelectDrug)) {
                sql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
                countSql.append(" left join wlyy_prescription_info m on b.id =m.prescription_id");
            }
        }
        if (StringUtils.isNotEmpty(status)) {
            status = status.substring(1, status.length() - 1);
            if (StringUtils.isNoneBlank(isSelectDrug)){
                if("0".equalsIgnoreCase(isSelectDrug)){
            if (StringUtils.isNoneBlank(isSelectDrug)) {
                if ("0".equalsIgnoreCase(isSelectDrug)) {
                    sql.append(" where b.status IN( 9,").append(status).append(")");
                    countSql.append(" where b.status IN( 9,").append(status).append(")");
                }else {
                } else {
                    sql.append(" where b.status IN(").append(status).append(")");
                    countSql.append(" where b.status IN(").append(status).append(")");
                }
            }else{
            } else {
                sql.append(" where b.status IN(").append(status).append(")");
                countSql.append(" where b.status IN(").append(status).append(")");
            }
@ -596,12 +617,12 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
            sql.append("  where b.status IN(20,21,30,31,32,100,101)");
            countSql.append(" where b.status IN(20,21,30,31,32,100,101) ");
        }
        if (StringUtils.isNoneBlank(isSelectDrug)){
            if("0".equalsIgnoreCase(isSelectDrug)){
        if (StringUtils.isNoneBlank(isSelectDrug)) {
            if ("0".equalsIgnoreCase(isSelectDrug)) {
                sql.append(" and m.del =1 ");
                countSql.append(" and m.del =1 ");
            }
            if ("1".equalsIgnoreCase(isSelectDrug)){
            if ("1".equalsIgnoreCase(isSelectDrug)) {
                sql.append(" and m.del =1");
                countSql.append(" and m.del =1");
            }
@ -624,8 +645,8 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
                    ")");
        }
        if (StringUtils.isNotEmpty(doctor)) {
            sql.append(" and  b.doctor ='" +doctor+"'");
            countSql.append(" and  b.doctor ='" +doctor+"'");
            sql.append(" and  b.doctor ='" + doctor + "'");
            countSql.append(" and  b.doctor ='" + doctor + "'");
        }
        sql.append(" order by b.prescribe_time DESC ");
@ -649,11 +670,11 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= " + (page - 1) * size;
            if (flag){
            if (flag) {
                sql.append("  limit ").append((page - 1) * size).append(",").append(size);
                logger.info("MySql=" + sql.toString());
                list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }else {
            } else {
                logger.info("oracleSql=" + oracleSql);
                list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            }
@ -663,15 +684,15 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
            logger.info("MySql=" + sql.toString());
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        }
        for (WlyyPrescriptionVO singlePre:list){
            List<WlyyPrescriptionInfoDO> infoDOs = prescriptionInfoDao.findByPrescriptionId(singlePre.getId(),1);
            logger.info("singlePreId===="+singlePre.getId());
            logger.info("infoDOs"+infoDOs);
        for (WlyyPrescriptionVO singlePre : list) {
            List<WlyyPrescriptionInfoDO> infoDOs = prescriptionInfoDao.findByPrescriptionId(singlePre.getId(), 1);
            logger.info("singlePreId====" + singlePre.getId());
            logger.info("infoDOs" + infoDOs);
            List<WlyyPrescriptionInfoVO> infoVOS = new ArrayList<>();
            convertToModels(infoDOs, infoVOS, WlyyPrescriptionInfoVO.class);
            logger.info("infoVOS"+infoVOS);
            logger.info("infoVOS" + infoVOS);
            singlePre.setInfoVOs(infoVOS);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(singlePre.getId(),1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(singlePre.getId(), 1);
            List<WlyyInspectionVO> inspectionVOS = new ArrayList<>();
            convertToModels(inspectionDOS, inspectionVOS, WlyyInspectionVO.class);
            //BeanUtils.copyProperties(inspectionDOS,inspectionVOS);
@ -683,148 +704,194 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
        long count = Long.parseLong(mapList.get(0).get("count").toString());
        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find, list, page, size, count);
    }
    public Map<String,Object>  findPatientInfoById(String patientId,String doctor){
    public Map<String, Object> findPatientInfoById(String patientId, String doctor) {
        String sql = "select b.id as \"id\"," +
                "  b.group_code as \"groupCode\"," +
                "  b.group_name as \"groupName\"" +
                "  from base_patient_group t " +
                " left join base_patient_group_dict b on t.group_id = b.id" +
                " where b.del = '1' and t.patient ='"+patientId+"' and t.doctor ='"+doctor+"'";
        sql+=" group by b.id,b.group_code,b.group_name";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        String patientSql= "select t.id as \"id\"," +
                " where b.del = '1' and t.patient ='" + patientId + "' and t.doctor ='" + doctor + "'";
        sql += " group by b.id,b.group_code,b.group_name";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        String patientSql = "select t.id as \"id\"," +
                " t.name as \"name\"," +
                " t.idcard as \"idcard\"," +
                " t.disease as \"disease\"" +
                "  from base_patient t where t.del = '1' and t.id='"+patientId+"'";
        List<Map<String,Object>> patientInfo = hibenateUtils.createSQLQuery(patientSql);
        if (patientInfo!=null&&patientInfo.size()>0){
            Map<String,Object> patient = patientInfo.get(0);
                "  from base_patient t where t.del = '1' and t.id='" + patientId + "'";
        List<Map<String, Object>> patientInfo = hibenateUtils.createSQLQuery(patientSql);
        if (patientInfo != null && patientInfo.size() > 0) {
            Map<String, Object> patient = patientInfo.get(0);
            String sex = IdCardUtil.getSexForIdcard_new(patient.get("idcard").toString());
            Integer age = IdCardUtil.getAgeForIdcard(patient.get("idcard").toString());
            patient.put("sex",sex);
            patient.put("age",age);
            patient.put("groupList",list);
            patient.put("sex", sex);
            patient.put("age", age);
            patient.put("groupList", list);
            return patient;
        }
        return null;
    }
    public PageEnvelop pageByCondition(String name, Integer archiveType, Integer archiveStatus,int page,int size){
        List<Map<String ,Object>> list;
        if (page>0){
    public PageEnvelop pageByCondition(String name, Integer archiveType, Integer archiveStatus, int page, int size) {
        List<Map<String, Object>> list;
        if (page > 0) {
//            page--;
        }else{
            page=0;
        } else {
            page = 0;
        }
        String sqlCount = "select count(*) as \"total\" from base_patient where 1=1 ";
        String sql = "select * from base_patient where 1=1 ";
        String sqlCondition = "";
        if (StringUtils.isNotBlank(name)){
            sqlCondition += " and (name like '%"+name+"%' or idcard like '%"+name+"%' or mobile like '%"+name+"%') ";
        if (StringUtils.isNotBlank(name)) {
            sqlCondition += " and (name like '%" + name + "%' or idcard like '%" + name + "%' or mobile like '%" + name + "%') ";
        }
        if (archiveType!=null){
            sqlCondition += " and archive_type ="+archiveType;
        if (archiveType != null) {
            sqlCondition += " and archive_type =" + archiveType;
        }
        if (archiveStatus!=null){
            sqlCondition += " and archive_status ="+archiveStatus;
        if (archiveStatus != null) {
            sqlCondition += " and archive_status =" + archiveStatus;
        }
        List<Map<String ,Object>> count = hibenateUtils.createSQLQuery(sqlCount+sqlCondition);
        Long cou=0l;
        if (count!=null&&count.size()>0){
            cou= Long.valueOf(count.get(0).get("total").toString());
        List<Map<String, Object>> count = hibenateUtils.createSQLQuery(sqlCount + sqlCondition);
        Long cou = 0l;
        if (count != null && count.size() > 0) {
            cou = Long.valueOf(count.get(0).get("total").toString());
        }
        list = hibenateUtils.createSQLQuery(sql+sqlCondition,page,size);
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,cou);
        list = hibenateUtils.createSQLQuery(sql + sqlCondition, page, size);
        return PageEnvelop.getSuccessListWithPage("success", list, page, size, cou);
    }
    /**
     *
     * 获取医养默认头像
     * @param user 1居民2员工(医生、助老员等)
     *
     * @param user        1居民2员工(医生、助老员等)
     * @param doctorLevel
     * @param archiveType
     * @param sex
     * @param idcard
     * @return
     */
    public String getHzAvatar(Integer user,String doctorLevel,String archiveType,String sex,String idcard){
    public String getHzAvatar(Integer user, String doctorLevel, String archiveType, String sex, String idcard) {
        String avatar = null;
        String flag = "";
        if (org.apache.commons.lang3.StringUtils.isBlank(sex)&& org.apache.commons.lang3.StringUtils.isNotBlank(idcard)){
        if (org.apache.commons.lang3.StringUtils.isBlank(sex) && org.apache.commons.lang3.StringUtils.isNotBlank(idcard)) {
            sex = IdCardUtil.getSexForIdcard_new(idcard);
        }
        if (1==user){
            if (org.apache.commons.lang3.StringUtils.isNotBlank(archiveType)){
                flag = "1"+"-"+archiveType;
        if (1 == user) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(archiveType)) {
                flag = "1" + "-" + archiveType;
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sex)&&!"3".equals(sex)){
                flag += "-"+sex;
            }else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sex) && !"3".equals(sex)) {
                flag += "-" + sex;
            } else {
                flag += "-1";
            }
        }
        else if (2==user){
            if (org.apache.commons.lang3.StringUtils.isNotBlank(doctorLevel)){
                flag = "2"+"-"+doctorLevel;
        } else if (2 == user) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(doctorLevel)) {
                flag = "2" + "-" + doctorLevel;
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sex)&&!"3".equals(sex)){
                flag += "-"+sex;
            }else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sex) && !"3".equals(sex)) {
                flag += "-" + sex;
            } else {
                flag += "-1";
            }
        }
        String dictName="";
        switch (flag){
        String dictName = "";
        switch (flag) {
            case "1-1-1"://老人男
                dictName="laorennan";
                dictName = "laorennan";
                break;
            case "1-1-2"://老人女
                dictName="laorennv";
                dictName = "laorennv";
                break;
            case "1-2-1"://新生儿男
                dictName="xinshengernan";
                dictName = "xinshengernan";
                break;
            case "1-2-2"://新生儿女
                dictName="xinshengernv";
                dictName = "xinshengernv";
                break;
            case "1-3-1"://家属男
                dictName="jiashunan";
                dictName = "jiashunan";
                break;
            case "1-3-2"://家属女
                dictName="jiashunv";
                dictName = "jiashunv";
                break;
            case "2-1-1"://医生男
                dictName="yishengnan";
                dictName = "yishengnan";
                break;
            case "2-1-2"://医生女
                dictName="yishengnv";
                dictName = "yishengnv";
                break;
            case "2-2-1"://社工男
                dictName="shegongnan";
                dictName = "shegongnan";
                break;
            case "2-2-2"://社工女
                dictName="shegongnv";
                dictName = "shegongnv";
                break;
            case "2-3-1"://教师男
                dictName="jiaoshinan";
                dictName = "jiaoshinan";
                break;
            case "2-3-2"://教师女
                dictName="jiaoshinv";
                dictName = "jiaoshinv";
                break;
            case "2-4-1"://助老员男
                dictName="zhulaoyuannan";
                dictName = "zhulaoyuannan";
                break;
            case "2-4-2"://助老员女
                dictName="zhulaoyuannv";
                dictName = "zhulaoyuannv";
                break;
            default:
                dictName="zhulaoyuannan";
                dictName = "zhulaoyuannan";
                break;
        }
        String sql = " select dict_value from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_code='"+dictName+"' ";
        avatar = jdbcTemplate.queryForObject(sql,String.class);
        String sql = " select dict_value from wlyy_hospital_sys_dict where dict_name='hz_default_avatar' and dict_code='" + dictName + "' ";
        avatar = jdbcTemplate.queryForObject(sql, String.class);
        return avatar;
    }
    /**
     * 根据身份证添加居民
     *
     * @param idcard
     * @return
     */
    public BasePatientDO addPaitentByIdcard(String idcard) {
        try {
            org.json.JSONArray jsonArray = jwArchivesService.getSickArchiveRecord(idcard);
            if (jsonArray.length() > 0) {
                org.json.JSONObject json = jsonArray.getJSONObject(0);
                BasePatientDO patient = new BasePatientDO();
//                patient.setCode(getCode());
                patient.setName(json.getString("sickName"));
                patient.setIdcard(idcard);
                patient.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                patient.setSsc(json.getString("ssc"));
                String salt = UUID.randomUUID().toString().replace("-", "");
                String password = idcard.substring(idcard.length() - 6, idcard.length());
                password = MD5.GetMD5Code("a" + password + "*" + salt);
                patient.setSalt(salt);
                patient.setPassword(password);
                //统一身份认证状态
//                patient.setIsCertified(0);
//                patient.setStatus(1);
//                patient.setCzrq(new Date());
//                patient.setSicardStatus(0);
                patientDao.save(patient);
                //同步居民签约记录
//                try {
//                    jwSignService.LoadSignFamilyByIdcard(idcard);
//                } catch (ServiceException se){
//                    se.printStackTrace();
//                } catch (Exception e){
//                    e.printStackTrace();
//                }
                return patient;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

+ 40 - 0
business/base-service/src/main/java/com/yihu/jw/system/dao/SystemDictDao.java

@ -0,0 +1,40 @@
package com.yihu.jw.system.dao;
import com.yihu.jw.entity.base.system.SystemDictDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
public interface SystemDictDao extends PagingAndSortingRepository<SystemDictDO, Long>, JpaSpecificationExecutor<SystemDictDO> {
    @Query("from SystemDictDO s where s.dictName=?1 order by s.sort asc ")
    List<SystemDictDO> findByDictName(String name);
    @Query("select s.name from SystemDictDO s where s.dictName=?1 and s.code =?2")
    String findByDictNameAndCode(String dictName, String code);
    @Query(" from SystemDictDO s where s.dictName=?1 and s.name =?2")
    SystemDictDO findByDictNameAndValue(String dictName, String value);
    @Query(" from SystemDictDO s where s.pyCode=?1 ")
    SystemDictDO findByPyCode(String pyCode);
    @Query("select s from SystemDictDO s where s.name like ?1 ")
    List<SystemDictDO> findByLikeName(String name);
    @Query("select s from SystemDictDO s where s.dictName like ?1 ")
    List<SystemDictDO> findByLikeDictName(String name);
    @Modifying
    @Query("delete SystemDictDO s where s.dictName = ?1")
    int delete(String dictName);
    @Query(" from SystemDictDO s where s.code=?1 and s.dictName=?2 ")
    SystemDictDO findByCodeAndName(String code, String dictName);
}

+ 148 - 0
business/base-service/src/main/java/com/yihu/jw/system/service/SystemDictService.java

@ -0,0 +1,148 @@
package com.yihu.jw.system.service;
import com.yihu.jw.entity.base.system.SystemDictDO;
import com.yihu.jw.system.dao.SystemDictDao;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * Created by Administrator on 2016/8/13.
 */
@Service
@Transactional
public class SystemDictService {
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    public Map<String,String> getDictMap(String dictName){
        List<SystemDictDO> dictList = systemDictDao.findByDictName(dictName);
//        Map<String,String> map = dictList.stream().collect(Collectors.toMap(SystemDictDO::getCode,SystemDict::getValue));
        Map<String,String> map = dictList.stream().collect(Collectors.toMap(SystemDictDO::getCode,SystemDictDO::getName));
        return map;
    }
    public List<SystemDictDO> getDictByDictName(String name) {
        return systemDictDao.findByDictName(name);
    }
    private String dictName = "SYSTEM_PARAMS";
    public String getDictValueNoRedis(String dictName, String code) {
        String re = systemDictDao.findByDictNameAndCode(dictName, code);
        return re;
    }
    /**
     * 字典转译
     *
     * @param dictName
     * @param code
     * @return
     */
    public String getDictValue(String dictName, String code) {
        String re = "";
        try {
            if (!StringUtils.isEmpty(code)) {
                //判断该字典redis是否存在
                String exit = redisTemplate.opsForValue().get("systemDict:" + dictName);
                if (!StringUtils.isEmpty(exit)) {
                    re = redisTemplate.opsForValue().get("systemDict:" + dictName + ":" + code);
                    if(StringUtils.isEmpty(re)){
                        re = systemDictDao.findByDictNameAndCode(dictName,code);
//                        if (!StringUtils.isEmpty(re)) {
//                            redisTemplate.opsForValue().set("systemDict:" + dictName + ":" + code, re);
//                        }
                    }
                } else {
                    List<SystemDictDO> list = systemDictDao.findByDictName(dictName);
                    if (list != null && list.size() > 0) {
                        redisTemplate.opsForValue().set("systemDict:" + dictName, "1");
                        for (SystemDictDO item : list) {
//                            redisTemplate.opsForValue().set("systemDict:" + dictName + ":" + item.getCode(), item.getValue());
                            redisTemplate.opsForValue().set("systemDict:" + dictName + ":" + item.getCode(), item.getName());
                            if (code.equals(item.getCode())) {
//                                re = item.getValue();
                                re = item.getName();
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            re = systemDictDao.findByDictNameAndCode(dictName, code);
        }
        return re;
    }
    /************************************** 其他参数 ****************************************/
    /**
     * http_log是否记录成功消息
     *
     * @return
     */
    public Boolean getSaveSuccessLog() {
        try {
            String re = systemDictDao.findByDictNameAndCode(dictName, "SAVE_SUCCESS_LOG");
            if ("1".equals(re)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    public int delete(String dictName) {
        return systemDictDao.delete(dictName);
    }
    /**
     * 保存健康教育设置字典
     * @param dictName
     * @param isComment
     */
//    public void save(String dictName, String isComment) {
//        SystemDict systemDict = new SystemDict();
//        systemDict.setDictName(dictName);
//        systemDict.setCode(isComment);
//        if (isComment.equals("0")) {
//            systemDict.setValue("不允许");
//        } else if (isComment.equals("1")) {
//            systemDict.setValue("允许");
//        }
//        systemDict.setSort(1);
//        systemDictDao.save(systemDict);
//    }
//    public void saveJkeduNotDisturb(String dictName, String json) {
//        JSONArray jsonArray = new JSONArray(json);
//        List<SystemDict> list = new ArrayList<>();
//        int code = 1;
//        for (Object object : jsonArray){
//            SystemDict systemDict = new SystemDict();
//            systemDict.setDictName(dictName);
//            systemDict.setCode(code + "");
//            systemDict.setValue(((JSONObject)object).toString());
//            systemDict.setSort(code);
//            list.add(systemDict);
//            code ++;
//        }
//        systemDictDao.save(list);
//    }
}

+ 27 - 0
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -187,6 +187,14 @@ public class ImService {
    @Value("${wechat.flag}")
    private boolean flag;
    public static String im_host;
//    @Value("${im-service.im_service_url}")
    @Value("${im.im_list_get}")
    public void setIm_host(String im_host) {
        ImService.im_host = im_host;
    }
    public String getSender(){
        WlyyHospitalSysDictDO dictDO = hospitalSysDictDao.findById("customer").orElse(null);
        if(dictDO==null){
@ -439,6 +447,25 @@ public class ImService {
        return participants;
    }
    /**
     *
     * @param user_id
     * @param business_type 1会话不包含患者,2会话包含含患者
     * @param status
     * @param page
     * @param size
     * @return
     */
//    public org.json.JSONArray getSessions(String user_id, String business_type, String status, String page, String size){
//        String url = im_host + "api/v2/sessions?user_id="+user_id+"&business_type="+business_type+"&status="+status+"&page="+page+"&size="+size;
//        try {
//            String ret = HttpClientUtil.get(url, "utf-8");
//            return new org.json.JSONArray(ret);
//        } catch (Exception e) {
//            throw new RuntimeException("获取议题失败!");
//        }
//    }
    /**
     * 根据会话ID获取消息记录
     *

+ 310 - 309
business/im-service/src/main/java/com/yihu/jw/im/util/HttpClientUtil.java

@ -1,309 +1,310 @@
package com.yihu.jw.im.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
 * IM http 工具类
 * @author huangwenjie
 */
public class HttpClientUtil {
	/**
	 * 发送post请求
	 *
	 * @param url     请求地址
	 * @param params  请求参数
	 * @param chatSet 编码格式
	 * @return
	 */
	public  String post(String url, List<NameValuePair> params, String chatSet) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	/**
	 * 发送get请求
	 *
	 * @param url     请求地址
	 * @param chatSet 编码格式
	 * @return
	 */
	public  String get(String url, String chatSet) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * http调用方法,(健康之路开放平台)
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public  String httpPost(String url, Map<String, String> params) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
		
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			if (params != null && params.size() > 0) {
				List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
					valuePairs.add(nameValuePair);
				}
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
				httpPost.setEntity(formEntity);
			}
			CloseableHttpResponse resp = httpclient.execute(httpPost);
			try {
				HttpEntity entity = resp.getEntity();
				String respContent = EntityUtils.toString(entity, "UTF-8").trim();
				return respContent;
			} finally {
				resp.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		} finally {
			httpclient.close();
		}
	}
	
	/**
	 * 获取加密后参数集合(健康之路开放平台)
	 *
	 * @param params
	 * @return
	 */
	public  Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
		String timestamp = Long.toString(System.currentTimeMillis());
		params.put("timestamp", timestamp);
		StringBuilder stringBuilder = new StringBuilder();
		
		// 对参数名进行字典排序  
		String[] keyArray = params.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);
		// 拼接有序的参数名-值串  
		stringBuilder.append(appId);
		for (String key : keyArray) {
			stringBuilder.append(key).append(params.get(key));
		}
		String codes = stringBuilder.append(secret).toString();
		String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
		// 添加签名,并发送请求  
		params.put("appId", appId);
		params.put("sign", sign);
		
		return params;
	}
	
	
	public  String postBody(String url, JSONObject params) {
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	
	public  void putBody(String url, JSONObject params) {
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		restTemplate.put(url, formEntity, String.class);
	}
	
	
	/**
	 * 发送post请求
	 *
	 * @param url     请求地址
	 * @param params  请求参数
	 * @return
	 */
	public String iotPostBody(String url, String params) {
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	/**
	 * 发送post请求
	 *
	 * @param url     请求地址
	 * @param params  请求参数
	 * @param chatSet 编码格式
	 * @param headerMap 请求头
	 * @return
	 */
	public  String headerPost(String url, List<NameValuePair> params, String chatSet,Map<String,Object> headerMap) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			for(String str:headerMap.keySet()){
				httppost.addHeader(str,headerMap.get(str).toString());
			}
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public  String get(String url, String chatSet,Map<String,Object> headerMap) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			url= url.replaceAll(" ", "%20");
			HttpGet httpget = new HttpGet(url);
			for(String str:headerMap.keySet()){
				httpget.addHeader(str,headerMap.get(str).toString());
			}
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
//package com.yihu.jw.im.util;
//
//import com.alibaba.fastjson.JSONObject;
//import org.apache.http.HttpEntity;
//import org.apache.http.NameValuePair;
//import org.apache.http.ParseException;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.entity.UrlEncodedFormEntity;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.message.BasicNameValuePair;
//import org.apache.http.util.EntityUtils;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Component;
//import org.springframework.web.client.RestTemplate;
//
//import java.io.IOException;
//import java.io.UnsupportedEncodingException;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Map;
//
///**
// * IM http 工具类
// * @author huangwenjie
// */
//@Component
//public class HttpClientUtil {
//	/**
//	 * 发送post请求
//	 *
//	 * @param url     请求地址
//	 * @param params  请求参数
//	 * @param chatSet 编码格式
//	 * @return
//	 */
//	public static String post(String url, List<NameValuePair> params, String chatSet) {
//		// 创建默认的httpClient实例.
//		CloseableHttpClient httpclient = HttpClients.createDefault();
//		// 创建httppost
//		HttpPost httppost = new HttpPost(url);
//		UrlEncodedFormEntity uefEntity;
//		try {
//			uefEntity = new UrlEncodedFormEntity(params, chatSet);
//			httppost.setEntity(uefEntity);
//			CloseableHttpResponse response = httpclient.execute(httppost);
//			try {
//				HttpEntity entity = response.getEntity();
//				if (entity != null) {
//					return EntityUtils.toString(entity, chatSet);
//				}
//			} finally {
//				response.close();
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 关闭连接,释放资源
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return null;
//	}
//
//
//	/**
//	 * 发送get请求
//	 *
//	 * @param url     请求地址
//	 * @param chatSet 编码格式
//	 * @return
//	 */
//	public  String get(String url, String chatSet) {
//		CloseableHttpClient httpclient = HttpClients.createDefault();
//		try {
//			// 创建httpget.
//			HttpGet httpget = new HttpGet(url);
//			// 执行get请求.
//			CloseableHttpResponse response = httpclient.execute(httpget);
//			try {
//				// 获取响应实体
//				HttpEntity entity = response.getEntity();
//				if (entity != null) {
//					return EntityUtils.toString(entity, chatSet);
//				}
//			} finally {
//				response.close();
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 关闭连接,释放资源
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return null;
//	}
//
//	/**
//	 * http调用方法,(健康之路开放平台)
//	 *
//	 * @param url
//	 * @param params
//	 * @return
//	 * @throws Exception
//	 */
//	public  String httpPost(String url, Map<String, String> params) throws Exception {
//		CloseableHttpClient httpclient = HttpClients.createDefault();
//		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
//
//		try {
//			HttpPost httpPost = new HttpPost(url);
//			httpPost.setConfig(requestConfig);
//			if (params != null && params.size() > 0) {
//				List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
//				for (Map.Entry<String, String> entry : params.entrySet()) {
//					NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
//					valuePairs.add(nameValuePair);
//				}
//				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
//				httpPost.setEntity(formEntity);
//			}
//			CloseableHttpResponse resp = httpclient.execute(httpPost);
//			try {
//				HttpEntity entity = resp.getEntity();
//				String respContent = EntityUtils.toString(entity, "UTF-8").trim();
//				return respContent;
//			} finally {
//				resp.close();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return e.getMessage();
//		} finally {
//			httpclient.close();
//		}
//	}
//
//	/**
//	 * 获取加密后参数集合(健康之路开放平台)
//	 *
//	 * @param params
//	 * @return
//	 */
//	public  Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
//		String timestamp = Long.toString(System.currentTimeMillis());
//		params.put("timestamp", timestamp);
//		StringBuilder stringBuilder = new StringBuilder();
//
//		// 对参数名进行字典排序  
//		String[] keyArray = params.keySet().toArray(new String[0]);
//		Arrays.sort(keyArray);
//		// 拼接有序的参数名-值串  
//		stringBuilder.append(appId);
//		for (String key : keyArray) {
//			stringBuilder.append(key).append(params.get(key));
//		}
//		String codes = stringBuilder.append(secret).toString();
//		String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
//		// 添加签名,并发送请求  
//		params.put("appId", appId);
//		params.put("sign", sign);
//
//		return params;
//	}
//
//
//	public  String postBody(String url, JSONObject params) {
//		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//		headers.setContentType(type);
//		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
//		String ret = restTemplate.postForObject(url, formEntity, String.class);
//		return ret;
//	}
//
//	public  void putBody(String url, JSONObject params) {
//		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//		headers.setContentType(type);
//		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
//		restTemplate.put(url, formEntity, String.class);
//	}
//
//
//	/**
//	 * 发送post请求
//	 *
//	 * @param url     请求地址
//	 * @param params  请求参数
//	 * @return
//	 */
//	public String iotPostBody(String url, String params) {
//		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//		headers.setContentType(type);
//		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
//		String ret = restTemplate.postForObject(url, formEntity, String.class);
//		return ret;
//	}
//	/**
//	 * 发送post请求
//	 *
//	 * @param url     请求地址
//	 * @param params  请求参数
//	 * @param chatSet 编码格式
//	 * @param headerMap 请求头
//	 * @return
//	 */
//	public  String headerPost(String url, List<NameValuePair> params, String chatSet,Map<String,Object> headerMap) {
//		// 创建默认的httpClient实例.
//		CloseableHttpClient httpclient = HttpClients.createDefault();
//		// 创建httppost
//		HttpPost httppost = new HttpPost(url);
//		UrlEncodedFormEntity uefEntity;
//		try {
//			uefEntity = new UrlEncodedFormEntity(params, chatSet);
//			httppost.setEntity(uefEntity);
//			for(String str:headerMap.keySet()){
//				httppost.addHeader(str,headerMap.get(str).toString());
//			}
//			CloseableHttpResponse response = httpclient.execute(httppost);
//			try {
//				HttpEntity entity = response.getEntity();
//				if (entity != null) {
//					return EntityUtils.toString(entity, chatSet);
//				}
//			} finally {
//				response.close();
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 关闭连接,释放资源
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return null;
//	}
//
//	public  String get(String url, String chatSet,Map<String,Object> headerMap) {
//		CloseableHttpClient httpclient = HttpClients.createDefault();
//		try {
//			// 创建httpget.
//			url= url.replaceAll(" ", "%20");
//			HttpGet httpget = new HttpGet(url);
//			for(String str:headerMap.keySet()){
//				httpget.addHeader(str,headerMap.get(str).toString());
//			}
//			// 执行get请求.
//			CloseableHttpResponse response = httpclient.execute(httpget);
//			try {
//				// 获取响应实体
//				HttpEntity entity = response.getEntity();
//				if (entity != null) {
//					return EntityUtils.toString(entity, chatSet);
//				}
//			} finally {
//				response.close();
//			}
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			// 关闭连接,释放资源
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return null;
//	}
//}

+ 62 - 53
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -3,6 +3,7 @@ package com.yihu.jw.im.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
@ -20,14 +21,14 @@ import java.util.List;
 */
@Component
public class ImUtil {
	
	@Autowired
	private HttpClientUtil HttpClientUtil;
	
	@Value("${im.im_list_get}")
	private String im_host;
	
	
	public enum ContentType {
		plainText("信息", "1"),
		image("图片信息", "2"),
@ -62,19 +63,19 @@ public class ImUtil {
			this.name = name;
			this.value = value;
		}
		
		public String getName() {
			return name;
		}
		
		public void setName(String name) {
			this.name = name;
		}
		
		public String getValue() {
			return value;
		}
		
		public void setValue(String value) {
			this.value = value;
		}
@ -125,7 +126,7 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 获取医生统计数据
	 * status reply 为空值是是该医生总咨询量
@ -151,7 +152,7 @@ public class ImUtil {
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	public void updateTopics(String topicId, String jsonValue) {
		String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
		JSONObject params = new JSONObject();
@ -159,7 +160,7 @@ public class ImUtil {
		params.put("data", jsonValue);
		HttpClientUtil.putBody(imAddr, params);
	}
	
	/**
	 * 当前医生下当前团队列表接口
	 * 获取团队内医生的健康咨询状况
@ -188,7 +189,7 @@ public class ImUtil {
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 列表接口
	 * 获取团队内医生的健康咨询状况
@ -213,7 +214,7 @@ public class ImUtil {
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 咨询列表
	 * @param user
@ -248,7 +249,7 @@ public class ImUtil {
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 咨询列表总数
	 * @param user
@ -281,7 +282,7 @@ public class ImUtil {
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 发送消息给IM
	 *
@ -311,8 +312,12 @@ public class ImUtil {
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendImMsg(String from, String fromName, String sessionId, String contentType, String content, String businessType) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages";
	public static  String sendImMsg(String from, String fromName, String sessionId, String contentType, String content, String businessType) {
//		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages";//原本的
		String host = ImService.im_host ;
		String imAddr = host + "api/v2/sessions/" + sessionId + "/messages";
		System.out.println("im地址"+imAddr);
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
@ -322,10 +327,11 @@ public class ImUtil {
		params.put("session_id", sessionId);
		params.put("business_type", businessType);
		params.put("extend",null);
		String response = HttpClientUtil.postBody(imAddr, params);
//		String response = HttpClientUtil.postBody(imAddr, params);
		String response = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
		return response;
	}
	
	/**
	 * 更新会话状态
	 *
@ -338,7 +344,7 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 更新会话状态
	 *
@ -371,7 +377,7 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	/**
	 * 发送消息给IM
	 *
@ -394,7 +400,7 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	/**
	 * 发送进入im消息
	 * IM: ParticipantUpdate:'/:session_id/participant/update'
@ -415,8 +421,8 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	
	/**
	 * 更新会话成员(新增或删除)
	 * @param sessionId 会话id
@ -450,7 +456,7 @@ public class ImUtil {
		}
		return HttpClientUtil.postBody(imAddr, params);
	}
	
	/**
	 * 更新消息内容
	 * @param sessionId 会话id
@ -467,7 +473,7 @@ public class ImUtil {
		params.put("content", content );
		return HttpClientUtil.postBody(imAddr, params);
	}
	
	/**
	 * 结束议题
	 *
@ -492,8 +498,8 @@ public class ImUtil {
		}
		return obj;
	}
	
	
	/**
	 * 议题邀请人员
	 *
@ -506,7 +512,7 @@ public class ImUtil {
		params.put("user", user + ":" + 0);
		HttpClientUtil.putBody(imAddr, params);
	}
	
	/**
	 * 创建议题
	 *
@ -532,7 +538,7 @@ public class ImUtil {
		}
		return obj;
	}
	
	/**
	 * 判断会话是否存在
	 */
@ -576,18 +582,21 @@ public class ImUtil {
		}
		return null;
	}
	
	/**
	 * 创建会话(system)
	 */
	public JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
		String imAddr = im_host + "api/v2/sessions";
	public static JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
//		String imAddr = im_host + "api/v2/sessions";
		String imAddr = ImService.im_host + "/sessions";
		JSONObject params = new JSONObject();
		params.put("participants", participants.toString());
		params.put("session_name", sessionName);
		params.put("session_type", sessionType);
		params.put("session_id", sessionId);
		String ret = HttpClientUtil.postBody(imAddr, params);
//		String ret = HttpClientUtil.postBody(imAddr, params);
		String ret = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
@ -596,7 +605,7 @@ public class ImUtil {
		}
		return obj;
	}
	
	/**
	 * 获取会话实例的消息对象
	 *
@ -618,7 +627,7 @@ public class ImUtil {
		messages.put("agent", agent);
		return messages;
	}
	
	public JSONObject getTopicMessage(String topicId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
@ -634,9 +643,9 @@ public class ImUtil {
		} catch (Exception e) {
			return null;
		}
		
	}
	
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
		try {
@ -647,7 +656,7 @@ public class ImUtil {
			return null;
		}
	}
	
	/**
	 * 删除对应的成员信息在MUC模式中
	 *
@ -684,7 +693,7 @@ public class ImUtil {
	 */
	public JSONObject deleteParticipants(String sessionId,String participants){
		String url  = im_host+"api/v2/sessions/"+sessionId+"/participants/"+participants;
		String rs = HttpClientUtil.doDelete(url,null,null);
		String rs = com.yihu.jw.util.http.HttpClientUtil.doDelete(url,null,null);
		JSONObject obj = JSONObject.parseObject(rs);
		if (obj.getInteger("status")==-1){
			throw new RuntimeException("删除会话人员失败!");
@ -692,8 +701,8 @@ public class ImUtil {
			return obj;
		}
	}
	
	
	/**
	 * 获取议题
	 *
@ -714,7 +723,7 @@ public class ImUtil {
			throw new RuntimeException("获取议题失败!");
		}
	}
	
	/**
	 * 获取会话成员
	 *
@ -731,7 +740,7 @@ public class ImUtil {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
	
	/**
	 * 获取会话成员
	 *
@ -748,7 +757,7 @@ public class ImUtil {
			throw new RuntimeException("获取议题失败!");
		}
	}
	
	public JSONObject cleanMessageToRedis(String sessionId){
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		try {
@ -758,7 +767,7 @@ public class ImUtil {
			throw new RuntimeException("操作失败!");
		}
	}
	
	public JSONObject cleanMessageLastFetchTime(String sessionId,String userId){
		String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
		try {
@ -768,8 +777,8 @@ public class ImUtil {
			throw new RuntimeException("操作失败!");
		}
	}
	
	
	/**
	 * 根据session和userid获取单个会话
	 * @param sessionId
@ -785,7 +794,7 @@ public class ImUtil {
			throw new RuntimeException("操作失败!");
		}
	}
	
	/**
	 * 发送消息给IM
	 *
@ -804,8 +813,8 @@ public class ImUtil {
		String response = HttpClientUtil.post(imAddr, params, "UTF-8");
		return response;
	}
	
	
	public static final String SESSION_TYPE_MUC = "1";
	public static final String SESSION_TYPE_P2P = "2";
	public static final String SESSION_TYPE_GROUP = "3";
@ -830,8 +839,8 @@ public class ImUtil {
	public static final String SESSION_TYPE_HealthConsult = "25";//老人在线咨询
	public static final String CONTENT_TYPE_TEXT = "1";
	
	
	/**
	 *按会话类型获取会话总数
	 * @param userid

+ 0 - 43
common/common-entity/src/db/sql记录

@ -2300,47 +2300,3 @@ ALTER TABLE `base`.`base_service_item_config`
ADD COLUMN `frequency_code` varchar(100) NULL COMMENT '频次' AFTER `pricing_units_name`;
====================================结束==============================================
====================================开始==============================================
CREATE TABLE `wlyy_rehabilitation_patient_info` (
  `id` int(50) NOT NULL AUTO_INCREMENT,
  `code` varchar(50) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL COMMENT '姓名',
  `idcard` varchar(50) DEFAULT NULL COMMENT '身份证',
  `sex` tinyint(2) DEFAULT NULL COMMENT '性别1男2女0未知',
  `age` tinyint(3) DEFAULT NULL COMMENT '年龄',
  `ssc` varchar(50) DEFAULT NULL COMMENT '社保卡',
  `mobile` varchar(50) DEFAULT NULL COMMENT '电话',
  `address` varchar(255) DEFAULT NULL COMMENT '住址',
  `kid` tinyint(2) DEFAULT NULL COMMENT '是否儿科:1是 0否,4岁以下儿童',
  `kid_parents` varchar(50) DEFAULT NULL COMMENT '患者家属',
  `diagnosis` varchar(50) DEFAULT NULL COMMENT '诊断code',
  `diagnosis_name` varchar(255) DEFAULT NULL COMMENT '出院诊断',
  `treatment` varchar(2000) DEFAULT NULL COMMENT '主要病情摘要及诊疗经过',
  `result` text COMMENT '出院前检查结果',
  `guidance` text COMMENT '后续治疗康复指导建议',
  `summary` varchar(2000) DEFAULT NULL COMMENT '出院小结',
  `crzq` varchar(100) DEFAULT NULL COMMENT '转诊日期',
  `hospital_code` varchar(50) DEFAULT NULL COMMENT '医院CODE',
  `hospital_name` varchar(100) DEFAULT NULL COMMENT '医院名称',
  `jw_hospital_code` varchar(50) DEFAULT NULL COMMENT '社区医院CODE',
  `jw_hospital_name` varchar(255) DEFAULT NULL COMMENT '社区医院名称',
  `hospital_doctor` varchar(255) DEFAULT NULL COMMENT '转诊医生',
  `create_time` datetime DEFAULT NULL COMMENT '请求时间',
  `status` int(11) DEFAULT NULL COMMENT '是否分配下转:0未分配,1已分配(已下转列表),2创建计划过程失败,3患者无住院病历信息(等待重新下转),4不支持该医院自动下转,5同步居民失败,6下转列表(未下转)',
  `problem_code` varchar(50) DEFAULT NULL COMMENT '问题代码1001肺癌,1002慢性胃肠病,1003冠心病,1004慢性前列腺疾病,1005慢性乳腺疾病,1006慢性阻塞性肺病,1007慢性肝病,1008慢性妇科炎症,1009脑卒中,1010慢性肾病',
  `diagnose_doctor` varchar(255) DEFAULT NULL COMMENT '诊断医生',
  `diagnose_time` datetime DEFAULT NULL COMMENT '诊断时间',
  `org_code` varchar(50) DEFAULT NULL COMMENT '接收社区医院code',
  `org_name` varchar(50) DEFAULT NULL COMMENT '接收社区医院名称',
  `doctor` varchar(50) DEFAULT NULL COMMENT '接收医生code',
  `doctor_name` varchar(50) DEFAULT NULL COMMENT '接收医生姓名',
  `receive_time` datetime DEFAULT NULL COMMENT '接收时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=150484 DEFAULT CHARSET=utf8mb4 COMMENT='出院小结的居民[需要下转居民信息]';
====================================结束==============================================

+ 2 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/dict/BaseFrequencyDictDO.java

@ -18,6 +18,8 @@ public class BaseFrequencyDictDO extends UuidIdentityEntityWithCreateTime {
    private String is_op_ip;
    private String is_del;
    private String status;
    @Column(name = "freq_code")
    public String getFreq_code() {
        return freq_code;

+ 23 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultDo.java

@ -14,6 +14,11 @@ import java.util.Date;
@Entity
@Table(name = "wlyy_consult")
public class ConsultDo extends UuidIdentityEntity {
	// 咨询标识
	private String code;
	// 患者标识
	private String patient;
	// 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,
@ -40,6 +45,24 @@ public class ConsultDo extends UuidIdentityEntity {
	private Integer payStatus;
	//来源
	private String source;
	//签约表Code
	private String signCode;
	public String getSignCode() {
		return signCode;
	}
	public void setSignCode(String signCode) {
		this.signCode = signCode;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getSource() {
		return source;

+ 22 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/system/SystemDictDO.java

@ -31,6 +31,28 @@ public class SystemDictDO implements Serializable {
	//类型
	private Type type;
	@Column(name = "dict_name")
	private String dictName;
	@Column(name = "sort")
	private String sort;
	public String getDictName() {
		return dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	@Id
	@GeneratedValue(generator = "generator")
	@GenericGenerator(name = "generator", strategy = "assigned")

+ 19 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java

@ -21,6 +21,25 @@ public class WxAccessTokenDO extends UuidIdentityEntity implements java.io.Seria
	private Long expiresIn;//凭证有效时间(秒)
	private Date czrq;//操作时间
	private String code;
	private String acc_id;
	public void setAddTimestamp(Long addTimestamp) {
		this.addTimestamp = addTimestamp;
	}
	public void setExpiresIn(Long expiresIn) {
		this.expiresIn = expiresIn;
	}
	public String getAcc_id() {
		return acc_id;
	}
	public void setAcc_id(String acc_id) {
		this.acc_id = acc_id;
	}
	/** default constructor */
	public WxAccessTokenDO() {
	}

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

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

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

@ -19,6 +19,8 @@ import java.util.List;
@Table(name = "wlyy_door_service_application")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_door_service_application")
public class WlyyDoorServiceApplicationDo extends BaseIdentityEntity {
    private String code;
    /**居民code*/
    private String patient;
    /**居民姓名*/
@ -69,6 +71,14 @@ public class WlyyDoorServiceApplicationDo extends BaseIdentityEntity {
    @LastModifiedBy
    protected String updateUserName;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPatient() {
        return patient;
    }

+ 9 - 6
common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java

@ -566,8 +566,11 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    private String serviceStatus;//服务类型 1-预约项目 2-即时项目
    private String orderInfo;//工单详情 0-未推送 1-未确认 2-已确认
    private List<WlyyPrescriptionDO> prescriptionDOList;//上门前开的方
    private List<WlyyPrescriptionDO> afterPrescriptionList;//上门后开的方
//    private List<WlyyPrescriptionDO> prescriptionDOList;//上门前开的方
//    private List<WlyyPrescriptionDO> afterPrescriptionList;//上门后开的方
    private List<WlyyDoorPrescriptionDO> prescriptionDOList;//上门前开的方
    private List<WlyyDoorPrescriptionDO> afterPrescriptionList;//上门后开的方
    private List<Followup> followupList;//上门随访
    private String followupDate;//随访时间
@ -578,20 +581,20 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    private String shortcutType;
    @Transient
    public List<WlyyPrescriptionDO> getPrescriptionDOList() {
    public List<WlyyDoorPrescriptionDO> getPrescriptionDOList() {
        return prescriptionDOList;
    }
    public void setPrescriptionDOList(List<WlyyPrescriptionDO> prescriptionDOList) {
    public void setPrescriptionDOList(List<WlyyDoorPrescriptionDO> prescriptionDOList) {
        this.prescriptionDOList = prescriptionDOList;
    }
    @Transient
    public List<WlyyPrescriptionDO> getAfterPrescriptionList() {
    public List<WlyyDoorPrescriptionDO> getAfterPrescriptionList() {
        return afterPrescriptionList;
    }
    public void setAfterPrescriptionList(List<WlyyPrescriptionDO> afterPrescriptionList) {
    public void setAfterPrescriptionList(List<WlyyDoorPrescriptionDO> afterPrescriptionList) {
        this.afterPrescriptionList = afterPrescriptionList;
    }

+ 53 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/followup/FollowupClassDrugs.java

@ -0,0 +1,53 @@
package com.yihu.jw.entity.followup;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 疾病关联用药
 * @author hzp add 2016-12-07
 *
 */
@Entity
@Table(name = "wlyy_followup_class_drugs")
public class FollowupClassDrugs extends IdEntity {
	//随访类别:1.高血压 2.糖尿病
	private String followupClass;
	//药品代码
	private String drugsCode;
	//创建时间
	private Date createTime;
	public String getFollowupClass() {
		return followupClass;
	}
	public void setFollowupClass(String followupClass) {
		this.followupClass = followupClass;
	}
	public String getDrugsCode() {
		return drugsCode;
	}
	public void setDrugsCode(String drugsCode) {
		this.drugsCode = drugsCode;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
}

+ 178 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/MessageNoticeSetting.java

@ -0,0 +1,178 @@
package com.yihu.jw.entity.hospital.message;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 消息提醒设置
 * @author yeshijie on 2017/11/27.
 *
 */
@Entity
@Table(name = "wlyy_message_notice_setting")
public class MessageNoticeSetting extends IdEntity {
    private String user;//'用户code'
    private String type;// '类型(1医生,2居民)'
    private Integer masterSwitch;// '总开关' (1开,0关)
    private Integer imSwitch;//'im消息开关'(1开,0关)
    private Integer familyTopicSwitch;// '健管师邀请后推送开关'(1开,0关)
    private Integer signSwitch;// '签约消息开关'(1开,0关)
    private Integer healthSignSwitch;// '体征消息开关'(1开,0关)
    private Integer systemSwitch;// '系统消息开关'(1开,0关)
    private Integer prescriptionSwitch;// '续方消息开关'(1开,0关)
    private Integer soundSwitch;// '铃声提醒开关'(1开,0关)
    private Integer vibrationSwitch;// '振动提醒开关'(1开,0关)
    private Integer coordinationSwitch;// '协同消息开关'(1开,0关)
    private Date createTime;// '创建时间'
    //状态枚举
    public enum MessageTypeEnum {
        masterSwitch("总开关","masterSwitch"),
        imSwitch("im消息开关","imSwitch"),
        familyTopicSwitch("健管师邀请后推送开关","familyTopicSwitch"),
        signSwitch("签约消息开关","signSwitch"),
        healthSignSwitch("体征消息开关","healthSignSwitch"),
        systemSwitch("系统消息开关","systemSwitch"),
        prescriptionSwitch("续方消息开关","prescriptionSwitch"),
        soundSwitch("铃声提醒开关","soundSwitch"),
        vibrationSwitch("振动提醒开关","vibrationSwitch"),
        coordinationSwitch("协同消息开关","coordinationSwitch");
        private String name;
        private String value;
        MessageTypeEnum(String name, String value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Integer getMasterSwitch() {
        return masterSwitch;
    }
    public void setMasterSwitch(Integer masterSwitch) {
        this.masterSwitch = masterSwitch;
    }
    public Integer getImSwitch() {
        return imSwitch;
    }
    public void setImSwitch(Integer imSwitch) {
        this.imSwitch = imSwitch;
    }
    public Integer getFamilyTopicSwitch() {
        return familyTopicSwitch;
    }
    public void setFamilyTopicSwitch(Integer familyTopicSwitch) {
        this.familyTopicSwitch = familyTopicSwitch;
    }
    public Integer getSignSwitch() {
        return signSwitch;
    }
    public void setSignSwitch(Integer signSwitch) {
        this.signSwitch = signSwitch;
    }
    public Integer getHealthSignSwitch() {
        return healthSignSwitch;
    }
    public void setHealthSignSwitch(Integer healthSignSwitch) {
        this.healthSignSwitch = healthSignSwitch;
    }
    public Integer getSystemSwitch() {
        return systemSwitch;
    }
    public void setSystemSwitch(Integer systemSwitch) {
        this.systemSwitch = systemSwitch;
    }
    public Integer getPrescriptionSwitch() {
        return prescriptionSwitch;
    }
    public void setPrescriptionSwitch(Integer prescriptionSwitch) {
        this.prescriptionSwitch = prescriptionSwitch;
    }
    public Integer getSoundSwitch() {
        return soundSwitch;
    }
    public void setSoundSwitch(Integer soundSwitch) {
        this.soundSwitch = soundSwitch;
    }
    public Integer getVibrationSwitch() {
        return vibrationSwitch;
    }
    public void setVibrationSwitch(Integer vibrationSwitch) {
        this.vibrationSwitch = vibrationSwitch;
    }
    public Integer getCoordinationSwitch() {
        return coordinationSwitch;
    }
    public void setCoordinationSwitch(Integer coordinationSwitch) {
        this.coordinationSwitch = coordinationSwitch;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name="create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 191 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SpecialistDynamicMessages.java

@ -0,0 +1,191 @@
package com.yihu.jw.entity.hospital.message;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
/***
 * @Description: 专病分级诊疗实时动态
 * @Auther: yeshijie
 * @Date: 2023-05-23
 */
@Entity
@Table(name = "wlyy_specialist_dynamic_messages")
public class SpecialistDynamicMessages extends IdEntity {
    private String name;//居民姓名
    private String address;//居民地址
    private String result;//执行结果
    private String createTime;//创建时间yyyy-MM-dd HH:mm:ss
    private String code;//居民code
    private String codeType;//用户code类型 2居民
    private String hospital;//社区医院
    private String doctor;//全科
    private String diseaseType;//专病类型
    private String specialist;//专科
    private String specialistHospital;//专科医院
    private String content;//全科文案
    private String specialistContent;//专科文案
    private String type;//类型1康复计划 2代预约 3咨询求助 4专科协同
    private String photo;//头像
    private String doctorName;//全科医生姓名
    private String specialistName;//专科医生姓名
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "address")
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Column(name = "result")
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    @Column(name = "createTime")
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "code_type")
    public String getCodeType() {
        return codeType;
    }
    public void setCodeType(String codeType) {
        this.codeType = codeType;
    }
    @Column(name = "disease_type")
    public String getDiseaseType() {
        return diseaseType;
    }
    public void setDiseaseType(String diseaseType) {
        this.diseaseType = diseaseType;
    }
    @Column(name = "hospital")
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "specialist")
    public String getSpecialist() {
        return specialist;
    }
    public void setSpecialist(String specialist) {
        this.specialist = specialist;
    }
    @Column(name = "specialist_hospital")
    public String getSpecialistHospital() {
        return specialistHospital;
    }
    public void setSpecialistHospital(String specialistHospital) {
        this.specialistHospital = specialistHospital;
    }
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Column(name = "specialist_content")
    public String getSpecialistContent() {
        return specialistContent;
    }
    public void setSpecialistContent(String specialistContent) {
        this.specialistContent = specialistContent;
    }
    @Column(name = "type")
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Transient
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    @Transient
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Transient
    public String getSpecialistName() {
        return specialistName;
    }
    public void setSpecialistName(String specialistName) {
        this.specialistName = specialistName;
    }
}

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

@ -127,6 +127,7 @@ public class SystemMessageDO extends UuidIdentityEntity {
    private String prescriptionStatus;//type=6续方审核状态 0待审核,1审核通过,2审核失败,3居民取消|type=7续方状态 0待取药,1已取药
    @Column(name = "audio_url")
    public String getAudioUrl() {
        return audioUrl;

+ 107 - 78
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamDO.java

@ -1,115 +1,93 @@
package com.yihu.jw.entity.hospital.team;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import com.yihu.jw.entity.IdEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.stereotype.Component;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
 * Created by yww on 2016/11/15.
 * 医生行政团队。
 *
 * @author Sand
 */
@Component
@Entity
@Table(name = "wlyy_admin_team")
@EntityListeners(AuditingEntityListener.class)
public class WlyyAdminTeamDO implements Serializable {
    private Integer id;
    private static final long serialVersionUID = 1L;
    private String name;            //团队名称
    private Date createTime;              //创建时间
    private Integer available;
public class WlyyAdminTeamDO extends IdEntity {
    private String name;
    private Date createTime;
    private String leaderCode;
    private boolean available;
    private String orgCode;
    private String orgName;
    private String leaderCode;
    private String leaderName;
    private String townCode;
    private String townName;
    private String mappingCode;
    private String mappingName;
    private Date lastModified;
    private String memberCount;
    @Id
    @Column(name = "id")
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getMemberCount() {
        return memberCount;
    }
    public void setMemberCount(String memberCount) {
        this.memberCount = memberCount;
    }
    //不对应表中字段
    private List<WlyyAdminTeamMemberDO> memberList = new ArrayList<>();
    private String specialCode;
    private String specialName;
    private String phone;//团队电话
    private String phoneStatus;//是否对外开放电话 1是0否
    private Integer acceptType;//是否接受下转 0接受 1拒绝
    private String signLimit;//签约上限
    public String getName() {
        return name;
    }
    @Column(name = "name")
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    @Column(name = "create_time")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getAvailable() {
        return available;
    }
    public void setAvailable(Integer available) {
        this.available = available;
    }
    @Column(name = "org_code")
    public String getOrgCode() {
        return orgCode;
    }
    @Column(name = "org_code")
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    @Transient
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    @Column(name = "leader_code")
    public String getLeaderCode() {
        return leaderCode;
    }
    @Column(name = "leader_id")
    public void setLeaderCode(String leaderCode) {
        this.leaderCode = leaderCode;
    }
    @Column(name = "leader_name")
    public String getLeaderName() {
        return leaderName;
    public boolean isAvailable() {
        return available;
    }
    public void setLeaderName(String leaderName) {
        this.leaderName = leaderName;
    @Column(name = "available")
    public void setAvailable(boolean available) {
        this.available = available;
    }
    @Column(name = "mapping_code")
    public String getMappingCode() {
        return mappingCode;
@ -118,30 +96,81 @@ public class WlyyAdminTeamDO implements Serializable {
    public void setMappingCode(String mappingCode) {
        this.mappingCode = mappingCode;
    }
    @Transient
    public String getMappingName() {
        return mappingName;
    public String getOrgName() {
        return orgName;
    }
    public void setMappingName(String mappingName) {
        this.mappingName = mappingName;
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    @Column(name = "last_modified")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getLastModified() {
        return lastModified;
    @Transient
    public String getTownCode() {
        return townCode;
    }
    public void setLastModified(Date lastModified) {
        this.lastModified = lastModified;
    public void setTownCode(String townCode) {
        this.townCode = townCode;
    }
    @Transient
    public List<WlyyAdminTeamMemberDO> getMemberList() {
        return memberList;
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    public String getSpecialCode() {
        return specialCode;
    }
    public void setSpecialCode(String specialCode) {
        this.specialCode = specialCode;
    }
    public String getSpecialName() {
        return specialName;
    }
    public void setSpecialName(String specialName) {
        this.specialName = specialName;
    }
    @Column(name = "accept_type")
    public Integer getAcceptType() {
        return acceptType;
    }
    public void setAcceptType(Integer acceptType) {
        this.acceptType = acceptType;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Column(name = "phone_status")
    public String getPhoneStatus() {
        return phoneStatus;
    }
    public void setPhoneStatus(String phoneStatus) {
        this.phoneStatus = phoneStatus;
    }
    @Column(name = "sign_limit")
    public String getSignLimit() {
        return signLimit;
    }
    public void setMemberList(List<WlyyAdminTeamMemberDO> memberList) {
        this.memberList = memberList;
    public void setSignLimit(String signLimit) {
        this.signLimit = signLimit;
    }
}

+ 342 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPatientInfoDO.java

@ -0,0 +1,342 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * create by hmf on 2020/06/01 康复下转居民信息
 */
@Entity
@Table(name = "wlyy_rehabilitation_patient_info")
public class RehabilitationPatientInfoDO extends IdEntity {
    private String code;
    private String name;//姓名
    private String idcard;//身份证
    private String ssc;//社保卡
    private Integer sex;//性别1男2女0未知
    private Integer age;//年龄
    private String mobile;//电话
    private String address;//住址
    private Integer kid;//是否儿科:1是 0否,4岁以下儿童
    private String kidParents;//患者家属
    private String diagnosis;//出院诊断code
    private String diagnosisName;//出院诊断
    private String treatment;//主要病情摘要及诊疗经过
    private String result;//出院前检查结果
    private String guidance;//后续治疗康复指导建议
    private String summary;//出院小结
    private String crzq;//转诊日期
    private String hospitalCode;//医院CODE
    private String hospitalName;//医院名称
    private String jwHospitalCode;//社区医院CODE
    private String jwHospitalName;//社区医院名称
    private String hospitalDoctor;//转诊医生
    private Date createTime;//请求时间
    private Integer status;//是否分配下转:0未分配,1已分配(已下转列表),2创建计划过程失败,3患者无住院病历信息(等待重新下转),4不支持该医院自动下转,5同步居民失败,6下转列表(未下转-未签约)
    private String statusName;//是否分配下转:0未分配,1已分配(已下转列表),2创建计划过程失败,3患者无住院病历信息(等待重新下转),4不支持该医院自动下转,5同步居民失败,6下转列表(未下转)
    private String problemCode;//问题代码1001肺癌,1002慢性胃肠病,1003冠心病,1004慢性前列腺疾病,1005慢性乳腺疾病,
                               // 1006慢性阻塞性肺病,1007脂肪肝,1008慢性妇科炎症,1009脑卒中,1010慢性肾病
    private String diagnoseDoctor;//诊断医生
    private Date diagnoseTime;//诊断时间
    private String orgCode;
    private String orgName;//接收社区医院
    private String doctor;
    private String doctorName;//接收医生
    private Date receiveTime;//接收时间
    private Integer archiveStatus;//档案状态
    private String archiveStatusName;//档案状态
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getKid() {
        return kid;
    }
    public void setKid(Integer kid) {
        this.kid = kid;
    }
    public String getKidParents() {
        return kidParents;
    }
    public void setKidParents(String kidParents) {
        this.kidParents = kidParents;
    }
    public String getDiagnosis() {
        return diagnosis;
    }
    public void setDiagnosis(String diagnosis) {
        this.diagnosis = diagnosis;
    }
    public String getDiagnosisName() {
        return diagnosisName;
    }
    public void setDiagnosisName(String diagnosisName) {
        this.diagnosisName = diagnosisName;
    }
    public String getTreatment() {
        return treatment;
    }
    public void setTreatment(String treatment) {
        this.treatment = treatment;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String getGuidance() {
        return guidance;
    }
    public void setGuidance(String guidance) {
        this.guidance = guidance;
    }
    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }
    public String getCrzq() {
        return crzq;
    }
    public void setCrzq(String crzq) {
        this.crzq = crzq;
    }
    public String getHospitalCode() {
        return hospitalCode;
    }
    public void setHospitalCode(String hospitalCode) {
        this.hospitalCode = hospitalCode;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getJwHospitalCode() {
        return jwHospitalCode;
    }
    public void setJwHospitalCode(String jwHospitalCode) {
        this.jwHospitalCode = jwHospitalCode;
    }
    public String getJwHospitalName() {
        return jwHospitalName;
    }
    public void setJwHospitalName(String jwHospitalName) {
        this.jwHospitalName = jwHospitalName;
    }
    public String getHospitalDoctor() {
        return hospitalDoctor;
    }
    public void setHospitalDoctor(String hospitalDoctor) {
        this.hospitalDoctor = hospitalDoctor;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getProblemCode() {
        return problemCode;
    }
    public void setProblemCode(String problemCode) {
        this.problemCode = problemCode;
    }
    public String getDiagnoseDoctor() {
        return diagnoseDoctor;
    }
    public void setDiagnoseDoctor(String diagnoseDoctor) {
        this.diagnoseDoctor = diagnoseDoctor;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getDiagnoseTime() {
        return diagnoseTime;
    }
    public void setDiagnoseTime(Date diagnoseTime) {
        this.diagnoseTime = diagnoseTime;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    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;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getReceiveTime() {
        return receiveTime;
    }
    public void setReceiveTime(Date receiveTime) {
        this.receiveTime = receiveTime;
    }
    @Transient
    public String getStatusName() {
        return statusName;
    }
    public void setStatusName(String statusName) {
        this.statusName = statusName;
    }
    @Transient
    public Integer getArchiveStatus() {
        return archiveStatus;
    }
    public void setArchiveStatus(Integer archiveStatus) {
        this.archiveStatus = archiveStatus;
    }
    @Transient
    public String getArchiveStatusName() {
        return archiveStatusName;
    }
    public void setArchiveStatusName(String archiveStatusName) {
        this.archiveStatusName = archiveStatusName;
    }
}

+ 9 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/util/AesEncryptUtils.java

@ -39,6 +39,7 @@ public class AesEncryptUtils {
        return decryptMysqlNo(name)+" as "+alias+" ";
    }
    /**
     * 针对 GROUP_CONCAT 函数,逗号分隔符进行解密
     * @param str
@ -98,6 +99,14 @@ public class AesEncryptUtils {
        }
    }
    public static String encrypt1(String content) throws Exception {
        return encrypt(content, KEY);
    }
    public static String decrypt1(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }
    /**
     * 解密
     * @param encryptStr 解密的字符串

+ 66 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/util/TransforSqlUtl.java

@ -1,5 +1,12 @@
package com.yihu.jw.entity.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
/***
 * @ClassName: TransforSqlUtl
 * @Description:
@ -10,6 +17,7 @@ public class TransforSqlUtl {
    private static final boolean dbEncrypt=false; //不需要加密时 改为false即可,实体类注释需同时处理
    public static String wlyySpecialistPatientRelationLike(String sql,String ...replaceName){
        for (String tmp :replaceName){
            String str = "AES_DECRYPT(from_base64("+tmp+"),'jkzl2021ZJXL*#%a')";
@ -179,4 +187,62 @@ public class TransforSqlUtl {
        }
        return sql;
    }
    private static final String DBKEY = "jkzl2021ZJXL*#%a";
    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    public static String encrypt(String content, String encryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
            byte[] b = cipher.doFinal(content.getBytes("utf-8"));
            // 采用base64算法进行转码,避免出现中文乱码
            return Base64.encodeBase64String(b);
        }catch (Exception e){
            e.printStackTrace();
            return content;
        }
    }
    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
            // 采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(encryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            e.printStackTrace();
            return encryptStr;
        }
    }
    public static String encryptContent(String content){
        if(content == null){
            return content;
        }
        if (dbEncrypt){
            content = encrypt(content, DBKEY);
        }
        return content  ;
    }
    public static String decryptContent(String encryptStr){
        if(StringUtils.isEmpty(encryptStr)){
            return encryptStr;
        }
        if (dbEncrypt){
            encryptStr = decrypt(encryptStr, DBKEY);
        }
        return encryptStr;
    }
}

+ 107 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatPushLog.java

@ -0,0 +1,107 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 微信模板推送日志
 * Created by yeshijie on 2017/10/18.
 * modify by wujunjie 原type=11-18统一为11  19更新为12  20更新为13  21更新为14 version v1.4.3
 */
@Entity
@Table(name = "wlyy_wx_push_log")
public class WechatPushLog extends IdEntity {
    private Integer type;// '推送类型',
    //1:template_sign_success  2:template_sign_failed  3:template_consult_notice  4:template_health_notice  5:template_termination
    // 6:template_appoint_success 7:template_appoint_failed 8 template_expenses_remind 9 template_healthy_article  10 template_doctor_change
    //11-18:template_doctor_survey
    //19:template_doctor_audit 20:template_doctor_service 21:template_physical_examination
    //91.医生助手 92.医生助手项目gcMessageController发送
    //15:doctor_invitel_template(签约单独使用) 16:template_deal_with(第三方使用)
    //26: template_birthday_wishes(生日祝福)
    private String scene;//模板使用场景
    private String openid;
    private String patient;//'居民code',
    private String name;//'居民姓名',
    private String request;//'请求入参',
    private String response;// '返回值',
    private Integer status;//'状态(0失败,1成功)',
    private Date createTime;
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRequest() {
        return request;
    }
    public void setRequest(String request) {
        this.request = request;
    }
    public String getResponse() {
        return response;
    }
    public void setResponse(String response) {
        this.response = response;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 2 - 4
common/common-entity/src/main/java/com/yihu/jw/entity/third/wlyyinfo/WechatTag.java

@ -1,8 +1,6 @@
package com.yihu.jw.entity.third.wlyyinfo;
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;

+ 107 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTagLog.java

@ -0,0 +1,107 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by chenweida on 2017/8/4.
 */
@Entity
@Table(name = "wx_tag_log")
public class WechatTagLog extends IdEntity {
    private Integer tagId;
    private String tagName;
    private Date createTime;
    private String townCode;//区code
    private String townName;//区名称
    private String patient;//患者名称
    private String patientName;//患者名称
    private String openId;//患者名称
    private String message;//信息
    private Integer type;// 1新增 2取消
    public Integer getTagId() {
        return tagId;
    }
    public void setTagId(Integer tagId) {
        this.tagId = tagId;
    }
    public String getTagName() {
        return tagName;
    }
    public void setTagName(String tagName) {
        this.tagName = tagName;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getTownCode() {
        return townCode;
    }
    public void setTownCode(String townCode) {
        this.townCode = townCode;
    }
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    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 getOpenId() {
        return openId;
    }
    public void setOpenId(String openId) {
        this.openId = openId;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
}

+ 91 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplate.java

@ -0,0 +1,91 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import java.util.Map;
/**
 * 微信消息模板推送内容
 * @author George
 */
public class WechatTemplate extends IdEntity {
	private static final long serialVersionUID = 3877107913397496785L;
	/**
     * 模板消息id
     */
    private String template_id;
    /**
     * 用户openId
     */
    private String touser;
    /**
     * URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)
     */
    private String url;
    /**
     * 标题颜色
     */
    private String topcolor;
    /**
     * 详细内容
     */
    private Map<String,WechatTemplateData> data;
    /**
     * 所需跳转到的小程序appid
     */
    private String appId;
    /**
     * 所需跳转到小程序的具体页面路径,支持带参数
     */
    private String pagePath;
    public String getTemplate_id() {
        return template_id;
    }
    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }
    public String getTouser() {
        return touser;
    }
    public void setTouser(String touser) {
        this.touser = touser;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getTopcolor() {
        return topcolor;
    }
    public void setTopcolor(String topcolor) {
        this.topcolor = topcolor;
    }
    public Map<String, WechatTemplateData> getData() {
        return data;
    }
    public void setData(Map<String, WechatTemplateData> data) {
        this.data = data;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getPagePath() {
        return pagePath;
    }
    public void setPagePath(String pagePath) {
        this.pagePath = pagePath;
    }
}

+ 147 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateConfig.java

@ -0,0 +1,147 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 微信消息模板按场景区分消息内容
 * @author WuJunjie
 */
@Entity
@Table(name = "weixin_template_config")
public class WechatTemplateConfig extends IdEntity {
	private static final long serialVersionUID = -7399054549159698617L;
	private String templateName;//'自定义模板名称'
    private String scene;//使用场景值
    private String sceneDescription;//'使用场景描述'
    private String first;
    private String url;//模板消息'跳转链接'
    private String remark;
    private String keyword1;
    private String keyword2;
    private String keyword3;
    private String keyword4;
    private String keyword5;
    private String keyword6;
    private String keyword7;
    private Integer status;//状态 1:正常 0:删除
    public static long getSerialVersionUID() {
        return serialVersionUID;
    }
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    public String getSceneDescription() {
        return sceneDescription;
    }
    public void setSceneDescription(String sceneDescription) {
        this.sceneDescription = sceneDescription;
    }
    public String getFirst() {
        return first;
    }
    public void setFirst(String first) {
        this.first = first;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getKeyword1() {
        return keyword1;
    }
    public void setKeyword1(String keyword1) {
        this.keyword1 = keyword1;
    }
    public String getKeyword2() {
        return keyword2;
    }
    public void setKeyword2(String keyword2) {
        this.keyword2 = keyword2;
    }
    public String getKeyword3() {
        return keyword3;
    }
    public void setKeyword3(String keyword3) {
        this.keyword3 = keyword3;
    }
    public String getKeyword4() {
        return keyword4;
    }
    public void setKeyword4(String keyword4) {
        this.keyword4 = keyword4;
    }
    public String getKeyword5() {
        return keyword5;
    }
    public void setKeyword5(String keyword5) {
        this.keyword5 = keyword5;
    }
    public String getKeyword6() {
        return keyword6;
    }
    public void setKeyword6(String keyword6) {
        this.keyword6 = keyword6;
    }
    public String getKeyword7() {
        return keyword7;
    }
    public void setKeyword7(String keyword7) {
        this.keyword7 = keyword7;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 25 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateData.java

@ -0,0 +1,25 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
/**
 * 微信消息模板
 * @author George
 */
public class WechatTemplateData extends IdEntity {
	private static final long serialVersionUID = -7399054549159698617L;
	private String value; 
    private String color;
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
}

+ 71 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WeixinTemplate.java

@ -0,0 +1,71 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * @Description: 记录各公众号模板详情及自定义类型
 * @Author: WuJunjie
 * @Date: Created in 2018/2/24 17:38
 */
@Entity
@Table(name = "weixin_template")
public class WeixinTemplate  extends IdEntity {
    private String accId;//'微信公众号原始ID'
    private String templateName;//'自定义模板名称'
    private String templateTitle;//'模板标题'
    private Integer type;//'自定义模板类型'
    private String format;//'模板内容格式'
    private Integer status;//'模板状态 1:正常  0:删除'
    public String getAccId() {
        return accId;
    }
    public void setAccId(String accId) {
        this.accId = accId;
    }
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    public String getTemplateTitle() {
        return templateTitle;
    }
    public void setTemplateTitle(String templateTitle) {
        this.templateTitle = templateTitle;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getFormat() {
        return format;
    }
    public void setFormat(String format) {
        this.format = format;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 53 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxAccessTokenLog.java

@ -0,0 +1,53 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 获取微信accesstoken日志log
 * Created by yeshijie on 2020/11/9.
 */
@Entity
@Table(name = "wx_access_token_log")
public class WxAccessTokenLog extends IdEntity {
    private String accid;
    private String accessToken;
    private String expiresIn;
    private Date createTime;
    public String getAccid() {
        return accid;
    }
    public void setAccid(String accid) {
        this.accid = accid;
    }
    public String getAccessToken() {
        return accessToken;
    }
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    public String getExpiresIn() {
        return expiresIn;
    }
    public void setExpiresIn(String expiresIn) {
        this.expiresIn = expiresIn;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 23 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxOpenidTemp.java

@ -0,0 +1,23 @@
package com.yihu.jw.entity.wechat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Trick on 2018/6/28.
 */
@Entity
@Table(name = "wx_openid_temp")
public class WxOpenidTemp extends IdEntity {
    private String openid;
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
}

+ 56 - 0
common/common-util/src/main/java/com/yihu/jw/util/DoctorAssistantUtil.java

@ -0,0 +1,56 @@
package com.yihu.jw.util;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
 * 医生助手工具类
 * Created by yeshijie on 2021/7/9.
 */
@Component
public class DoctorAssistantUtil {
    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    /**
     * 发送医生助手通用方法
     * @param type
     * @param openId
     * @param first
     * @param remark
     * @param keywords
     */
    public void sendWXTemplate(int type,String openId,String cid,String first,String remark,String ... keywords){
        try{
            String doctorAssistantUrl = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("type", type+""));
            params.add(new BasicNameValuePair("openId", openId));
            params.add(new BasicNameValuePair("cid", cid));
            params.add(new BasicNameValuePair("url", targetUrl));
            params.add(new BasicNameValuePair("first", first));
            params.add(new BasicNameValuePair("remark", remark));
            params.add(new BasicNameValuePair("keywords", String.join(",",keywords)));
            httpClientUtil.post(doctorAssistantUrl, params, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

+ 14 - 0
common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java

@ -1632,4 +1632,18 @@ public class DateUtil {
        int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
        return monthsDiff;
    }
    /**
     * 根据数组返回若干天后的时间
     * @return 返回yyyy-MM-dd格式集合
     */
    public static List<String> getDaysByNow(int[] dayArray){
        List<String> list = new ArrayList<>();
        Date date = new Date();
        for (int i : dayArray) {
            Date preDays = DateUtil.getPreDays(date, i);
            list.add(DateUtil.dateToStrShort(preDays));
        }
        return list;
    }
}

+ 38 - 0
common/common-util/src/main/java/com/yihu/jw/util/encrypt/MD5.java

@ -16,6 +16,10 @@ import java.security.PrivilegedAction;
 */
public class MD5 {
    // 全局数组
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    public static String md5Hex(String data) {
        return DigestUtils.md5Hex(data);
    }
@ -178,4 +182,38 @@ public class MD5 {
    public static boolean md5CheckSum(String path, String toBeCheckSum) throws NoSuchAlgorithmException, IOException {
        return getMD5(path).equals(toBeCheckSum);
    }
    public static String GetMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }
    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }
    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }
}

+ 181 - 0
common/common-util/src/main/java/com/yihu/jw/util/fastdfs/FastDFSClientPool.java

@ -0,0 +1,181 @@
package com.yihu.jw.util.fastdfs;
import org.csource.fastdfs.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
 * Created by szx on 2015/9/19.
 */
public class FastDFSClientPool {
    private static volatile FastDFSClientPool pool;
    private Map<StorageClient, Boolean> map;
    private Map<Integer, StorageClient> pathIndexMap;
    private Map<Integer, StorageClient> pathIndexMapUsed;
    private int maxPoolSize = 20;
    private int waitTime = 500;
    private int initPoolSize = 5;
    static {
        try {
            
            String basePath = FastDFSClientPool.class.getResource("/").getPath();
           
            ClientGlobal.init(FastDFSUtil.class.getResource("/config/fdfs_client.conf").getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private FastDFSClientPool() {
        init();
    }
    public static FastDFSClientPool getInstance() {
        if (pool == null) {
            synchronized (FastDFSClientPool.class) {
                if(pool == null) {
                    pool = new FastDFSClientPool();
                }
            }
        }
        System.out.println("FastDFSClientPool:"+pool.toString());
        return pool;
    }
    private void init() {
        try {
            map = new HashMap<StorageClient, Boolean>();
            pathIndexMap = new HashMap<>();
            pathIndexMapUsed = new HashMap<>();
            //不做初始缓存
//            for (int i = 0; i < initPoolSize; i++) {
//                map.put(getNewStorageClient(), true);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public TrackerServer getTrackerServer(){
        try {
            TrackerClient tracker = new TrackerClient();
            return tracker.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    private StorageClient getNewStorageClient(Integer storePath) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer =null;
            if (storePath !=null ){
                storageServer = tracker.getStoreStorage(trackerServer);
                String storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
                Integer port = storageServer.getSocket().getPort();
                storageServer = new StorageServer(storageIp, port, storePath);
            }
            StorageClient client = new StorageClient(trackerServer, storageServer);
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void releaseStorageClient(StorageClient client) {
        if (client == null) {
            return;
        }
        try {
            if(map.containsKey(client)) {
                    map.put(client, true);
            } else {
                for (Entry entry : pathIndexMapUsed.entrySet()) {
                   if (entry.getValue()==client){
                       pathIndexMap.put((Integer) entry.getKey(),client);
                       pathIndexMapUsed.put((Integer) entry.getKey(),null);
                    }
                }
                client = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public synchronized StorageClient getStorageClient() {
        StorageClient client = null;
        try {
            for (Entry<StorageClient, Boolean> entry : map.entrySet()) {
                if (entry.getValue()) {
                    client = entry.getKey();
                    System.out.println("从缓存中获得fastdfs client");
                    map.put(client, false);
                    break;
                }
            }
            if (client == null) {
                if(map.size()<maxPoolSize) {
                    System.out.println("创建新fastdfs client:");
                    client = getNewStorageClient(null);
                    map.put(client, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
    /**
     * 上传指定上传路径
     * @return
     */
    public synchronized StorageClient getStorageClientByPath(Integer storePath) {
        StorageClient client = null;
        try {
            for (Entry entry : pathIndexMap.entrySet()) {
                if (entry.getKey()==storePath){
                    if (null!=entry.getValue()){
                        client = (StorageClient) entry.getValue();
                        System.out.println("从缓存中获得fastdfs client");
                        pathIndexMap.put(storePath, null);
                        pathIndexMapUsed.put(storePath, client);
                        break;
                    }
                }
            }
            if (client == null) {
                if(pathIndexMap.size()<maxPoolSize) {
                    System.out.println("创建新fastdfs client:");
                    client = getNewStorageClient(storePath);
                    pathIndexMap.put(storePath, client);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
}

+ 343 - 0
common/common-util/src/main/java/com/yihu/jw/util/fastdfs/FastDFSUtil.java

@ -0,0 +1,343 @@
package com.yihu.jw.util.fastdfs;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
/**
 * FastDFS 客户端工具.
 *
 * @author szx
 */
public class FastDFSUtil {
    public final static String GroupField = "groupName";
    public final static String RemoteFileField = "remoteFileName";
    public final static String FileIdField = "fid";
    public final static String FileUrlField = "fileUrl";
    final static int BUFFER_SIZE = 4096;
    /**
     * 以输入流的方式上传文件
     * InputStream in = new FileInputStream("C://Desert.jpg");
     * ObjectNode msg = FileUtil.upload(in,"jpg", "沙漠");
     * in.close();
     *
     * @param in                输入流
     * @param fileExtension   文件扩展名,不要带“.”
     * @param description             文件名称(中文)
     * @return 返回值的格式如下:
     * {
     *      "groupName": "healthArchiveGroup",
     *      "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     *      "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     *      "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * }
     *
     * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
     * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
     * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
     * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
     *
     * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
     *
     * @throws Exception
     */
    public static ObjectNode upload(InputStream in, String fileExtension,
                                    String description) throws Exception {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClient();
        try {
            NameValuePair[] fileMetaData;
            fileMetaData = new NameValuePair[1];
            fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode message = objectMapper.createObjectNode();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[BUFFER_SIZE]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = in.read(buff, 0, BUFFER_SIZE)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] fileBuffer = swapStream.toByteArray(); //in_b为转换之后的结果
            TrackerServer trackerServer = FastDFSClientPool.getInstance().getTrackerServer();
            String[] results = client.upload_file(fileBuffer, fileExtension, fileMetaData);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileURl;
                InetSocketAddress socketAddress;
                String groupName = results[0];
                String remoteFile = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFile);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
                message.put(FileIdField, fileId);
                socketAddress = trackerServer.getInetSocketAddress();
                fileURl = "http://" + socketAddress.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileURl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileURl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileURl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileURl);
                
                return message;
            } else {
                return null;
            }
        }finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     * 文件上传指定上传路径
     * @param in
     * @param fileExtension
     * @param description
     * @return
     * @throws Exception
     */
    public static ObjectNode uploadByStorage(InputStream in, String fileExtension,
                                             String description, Integer storePath) throws Exception {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClientByPath(storePath);
        try {
            NameValuePair[] fileMetaData;
            fileMetaData = new NameValuePair[1];
            fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode message = objectMapper.createObjectNode();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[BUFFER_SIZE]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = in.read(buff, 0, BUFFER_SIZE)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] fileBuffer = swapStream.toByteArray(); //in_b为转换之后的结果
            TrackerServer trackerServer = FastDFSClientPool.getInstance().getTrackerServer();
            String[] results = client.upload_file(fileBuffer, fileExtension, fileMetaData);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileURl;
                InetSocketAddress socketAddress;
                String groupName = results[0];
                String remoteFile = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFile);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
                message.put(FileIdField, fileId);
                socketAddress = trackerServer.getInetSocketAddress();
                fileURl = "http://" + socketAddress.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileURl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileURl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileURl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileURl);
                return message;
            } else {
                return null;
            }
        }finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     * 上传本地文件
     * ObjectNode  a = FileUtil.upload("C://Desert.jpg", "沙漠");
     * System.out.println(a.toString());
     *
     * @param fileName 本地文件的绝对路径,如 C://Desert.jpg
     * @param description    文件备注, 可以为空
     * @return {"groupName":"group1","remoteFileName":"/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * {
     *      "groupName": "healthArchiveGroup",
     *      "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     *      "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     *      "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * }
     *
     * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
     * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
     * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
     * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
     *
     * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
     *
     * @throws Exception
     */
    public static ObjectNode upload(String fileName, String description) throws Exception {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClient();
        try {
            NameValuePair[] meta_list;
            meta_list = new NameValuePair[1];
            meta_list[0] = new NameValuePair("description", description == null ? "" : description);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode message = objectMapper.createObjectNode();
            String fileExtName = "";
            if (fileName.contains(".")) {
                fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
            } else {
                throw new RuntimeException("上传失败, 文件缺失扩展名.");
            }
            TrackerServer trackerServer = FastDFSClientPool.getInstance().getTrackerServer();
            String[] results = client.upload_file(fileName, fileExtName, meta_list);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileUrl;
                InetSocketAddress inetSockAddr;
                String groupName = results[0];
                String remoteFileName = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFileName);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFileName;
                message.put(FileIdField, fileId);
                inetSockAddr = trackerServer.getInetSocketAddress();
                fileUrl = "http://" + inetSockAddr.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileUrl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileUrl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileUrl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileUrl);
                
                return message;
            } else {
                return null;
            }
        }finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     * 下载文件, 返回文件字节数组.
     *
     * @param groupName      在fastdfs上的卷名
     * @param remoteFileName 在fastdfs上的路径
     * @return 文件的字节码
     * @throws Exception
     */
    public static byte[] download(String groupName, String remoteFileName) throws Exception {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClient();
        try {
            byte[] b = client.download_file(groupName, remoteFileName);
            return b;
        }
        finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     * 下载文件到本地路径上.
     *
     * @param groupName          在 fastDFS 上的卷名
     * @param remoteFileName    在 fastDFS 上的路径
     * @param localPath          本地路径
     *
     * @return 是否下载成功
     */
    public static String download(String groupName, String remoteFileName, String localPath) throws IOException, MyException {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClient();
        try {
            String localFileName = localPath + "\\" + remoteFileName.replaceAll("/", "_");
            client.download_file(groupName, remoteFileName, 0, 0, localFileName);
            return localFileName;
        }finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     * 删除文件。
     *
     * @param groupName 组名 如:group1
     * @param remoteFileName 不带组名的路径名称 如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     */
    public static void delete(String groupName, String remoteFileName) throws IOException, MyException {
        StorageClient client = FastDFSClientPool.getInstance().getStorageClient();
        try {
            client.delete_file(groupName, remoteFileName);
        }finally {
            FastDFSClientPool.getInstance().releaseStorageClient(client);
        }
    }
    /**
     *
     * @param storagePath 文件的全部路径 如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @throws IOException
     * @throws MyException
     */
    public static void delete(String storagePath) throws Exception {
        if(!storagePath.startsWith("group")){
            throw new Exception();
        }
        String[] temp = storagePath.split("/");
        String groupName = temp[0];
        String remoteFileName = storagePath.substring(storagePath.indexOf("/")+1);
        delete(groupName, remoteFileName);
    }
}

+ 31 - 0
common/common-util/src/main/java/com/yihu/jw/util/html/HtmlUtil.java

@ -0,0 +1,31 @@
package com.yihu.jw.util.html;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by liub on 2020/12/10.
 */
@Component
public class HtmlUtil {
    public static List<String> getTagContent(String source, String regString) {
        List<String> result = new ArrayList<String>();
        Matcher m = Pattern.compile(regString).matcher(source);
        while (m.find()) {
            try {
                String r = StringEscapeUtils.unescapeHtml3(URLDecoder.decode(m.group(1),"utf-8"));
                result.add(r);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

+ 12 - 1
common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java

@ -359,7 +359,18 @@ public class HttpClientUtil {
        return buffer.toString();
    }
    
    public static   String postBody(String url, com.alibaba.fastjson.JSONObject params) {
    public  String postBody(String url, com.alibaba.fastjson.JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public  static String postBodyStatic(String url, com.alibaba.fastjson.JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");

+ 364 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtils.java

@ -0,0 +1,364 @@
package com.yihu.jw.util.http;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component
public class HttpClientUtils {
	/**
	 * 发送post请求
	 *
	 * @param url     请求地址
	 * @param params  请求参数
	 * @param chatSet 编码格式
	 * @return
	 */
	public  String httpPost(String url, List<NameValuePair> params, String chatSet) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 发送post请求
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String post(String url, List<NameValuePair> params, String chatSet) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * http调用方法,(健康之路开放平台)
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public  String httpPost(String url, Map<String, String> params) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(10000).build();//设置请求和传输超时时间
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			if (params != null && params.size() > 0) {
				List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
					valuePairs.add(nameValuePair);
				}
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
				httpPost.setEntity(formEntity);
			}
			CloseableHttpResponse resp = httpclient.execute(httpPost);
			try {
				HttpEntity entity = resp.getEntity();
				String respContent = EntityUtils.toString(entity, "UTF-8").trim();
				return respContent;
			} finally {
				resp.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			httpclient.close();
		}
	}
	/**
	 * http调用方法
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public  String post(String url, Map<String, Object> params) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(10000).build();//设置请求和传输超时时间
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			if (params != null && params.size() > 0) {
				List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
					valuePairs.add(nameValuePair);
				}
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
				httpPost.setEntity(formEntity);
			}
			CloseableHttpResponse resp = httpclient.execute(httpPost);
			try {
				HttpEntity entity = resp.getEntity();
				String respContent = EntityUtils.toString(entity, "UTF-8").trim();
				return respContent;
			} finally {
				resp.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			httpclient.close();
		}
	}
	/**
	 * 发送get请求
	 * @param url 请求地址
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String get(String url, String chatSet) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public  String get(String url, List<NameValuePair> params, String chatSet) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			String entityString = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			HttpGet httpget = new HttpGet(url+"?"+entityString);
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public static String postBody(String url, JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	public static void putBody(String url, JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		restTemplate.put(url, formEntity, String.class);
	}
	public static String postBody(String url){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	/**
	 * 获取加密后参数集合(健康之路开放平台)
	 *
	 * @param params
	 * @return
	 */
	public  Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
		String timestamp = Long.toString(System.currentTimeMillis());
		params.put("timestamp", timestamp);
		StringBuilder stringBuilder = new StringBuilder();
		// 对参数名进行字典排序  
		String[] keyArray = params.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);
		// 拼接有序的参数名-值串  
		stringBuilder.append(appId);
		for (String key : keyArray) {
			stringBuilder.append(key).append(params.get(key));
		}
		String codes = stringBuilder.append(secret).toString();
		String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
		// 添加签名,并发送请求  
		params.put("appId", appId);
		params.put("sign", sign);
		return params;
	}
	public String postBodyRawForm(String url, String params) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		List<NameValuePair> pairs = new ArrayList<>(0);
		pairs.add(new BasicNameValuePair("object",params));
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(formEntity);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String ret = EntityUtils.toString(entity);
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Accept", MediaType.ALL_VALUE.toString());
//        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
//        String str = "object=UlTrAcqBvZs9AS2IDMigquTqBcE64vxGqSvFLSe+a4VYYs4nbv3UX26NMA+ECNHJGL5RqAMvwP6aO/Wzf++fV9RYGgfvQVmleCZsSXsY/tw=";
//        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<>(str, headers);
//        String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	public String getBodyRawForm(String url, String params) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		List<NameValuePair> pairs = new ArrayList<>(0);
		pairs.add(new BasicNameValuePair("object",params));
		String entityString = EntityUtils.toString(new UrlEncodedFormEntity(pairs, Consts.UTF_8));
//        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
		HttpGet httpGet = new HttpGet(url+"?"+entityString);
		CloseableHttpResponse response = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		String ret = EntityUtils.toString(entity);
		return ret;
	}
}

+ 6 - 2
common/common-util/src/main/java/com/yihu/jw/util/wechat/wxhttp/HttpUtil.java

@ -1,6 +1,6 @@
package com.yihu.jw.util.wechat.wxhttp;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
@ -13,7 +13,8 @@ import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import java.io.*;
@ -25,6 +26,7 @@ import java.security.KeyStore;
/**
 * Created by Trick on 2018/8/21.
 */
@Component
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
@ -278,4 +280,6 @@ public class HttpUtil {
        }
    }
}

+ 6 - 1
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/config/MultipartConfig.java

@ -6,9 +6,10 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
import java.io.*;
import java.io.File;
/**
 * Created by liub on 2020/9/10.
 */
@ -28,6 +29,10 @@ public class MultipartConfig {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        //单个文件最大
        factory.setMaxFileSize(DataSize.ofMegabytes(10)); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(100));
        return factory.createMultipartConfig();
    }

+ 25 - 25
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/config/TomcatConfig.java

@ -1,25 +1,25 @@
package com.yihu.jw.gateway.config;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
/**
 * Created by Trick on 2018/12/18.
 */
@Configuration
public class TomcatConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize(DataSize.ofMegabytes(10)); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(100));
        return factory.createMultipartConfig();
    }
}
//package com.yihu.jw.gateway.config;
//
//import org.springframework.boot.web.servlet.MultipartConfigFactory;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.util.unit.DataSize;
//
//import javax.servlet.MultipartConfigElement;
//
///**
// * Created by Trick on 2018/12/18.
// */
//@Configuration
//public class TomcatConfig {
//
//    @Bean
//    public MultipartConfigElement multipartConfigElement() {
//        MultipartConfigFactory factory = new MultipartConfigFactory();
//        //单个文件最大
//        factory.setMaxFileSize(DataSize.ofMegabytes(10)); //KB,MB
//        /// 设置总上传数据总大小
//        factory.setMaxRequestSize(DataSize.ofMegabytes(100));
//        return factory.createMultipartConfig();
//    }
//}

+ 15 - 1
gateway/ag-basic/src/main/resources/application.yml

@ -435,4 +435,18 @@ spring:
  redis:
    host: 127.0.0.1
    port: 6380
    password: Kb6wKDQP1W4
    password: Kb6wKDQP1W4
---
spring:
  profiles: native
  datasource:
    url: jdbc:mysql://59.61.92.90:8079/query-base?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: xilari
    password: '&}H89@a7&AspSq@'
  redis:
    host: 59.61.92.90
    port: 9054
    password: o!a1#B74&m
fastDFS:
  fastdfs_file_url: https://www.xmtyw.cn/

+ 2 - 0
server/svr-authentication/src/main/java/com/yihu/AuthServer.java

@ -6,6 +6,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@ -13,6 +14,7 @@ import org.springframework.web.client.RestTemplate;
 * Created by progr1mmer on 2018/8/29.
 */
@EnableDiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class AuthServer extends SpringBootServletInitializer {

+ 35 - 0
server/svr-authentication/src/main/resources/application.yml

@ -797,6 +797,41 @@ testPattern:
wechat:
  id: xm_mlwyy_wx  # base库中,wx_wechat 的id字段
im:
  im_list_get: http://172.26.0.105:3000/
kick:
  ##互踢 1开通 0关闭
  eachOther: 0
---
spring:
  profiles: native
  datasource:
    url: jdbc:mysql://59.61.92.90:8079/query-base?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: xilari
    password: '&}H89@a7&AspSq@'
  redis:
    host: 59.61.92.90
    port: 9054
    password: o!a1#B74&m
## i健康用户信息接口,开放出来给互联网医院登录同步用户信息用
iHealth:
  user-info-uri: http://ehr.yihu.com/wlyy/iHealth/userInfo
zhongshanHospital:
  user-info-uri: http://laptop-u738dn2p:10023/mqsdk/getUserInfoByOpenid
fastDFS:
  fastdfs_file_url: http://172.26.0.110:8888/
wlyy:
  url: http://www.xmtyw.cn/wlyy/
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream
wechat:
  id: xm_mlwyy_wx  # base库中,wx_wechat 的id字段
im:
  im_list_get: http://172.26.0.105:3000/
kick:

+ 11 - 1
server/svr-authentication/src/main/resources/bootstrap.yml

@ -209,4 +209,14 @@ spring:
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.153:1221}
      label: ${wlyy.spring.config.label:master}
      label: ${wlyy.spring.config.label:master}
---
spring:
  cloud:
    config:
      uri: ${wlyy-spring.config.uri:http://127.0.0.1:1221}
      label: ${wlyy-spring.config.label:master}
  config:
    activate:
      on-profile: native

+ 1 - 0
server/svr-configuration/src/main/resources/application.yml

@ -23,6 +23,7 @@ eureka:
#      defaultZone: http://jw:jkzl@172.16.100.63:8761/eureka  # 心脏中心外网
#      defaultZone: http://jw:jkzl@192.168.120.210:8761/eureka  # 心脏中心外网
#      defaultZone: http://jw:jkzl@192.168.33.199:8761/eureka  # 眼科医院
#      defaultZone: http://jw:jkzl@192.168.120.96:8761/eureka  #i健康191服务器
  instance:
    #eurika使用IP不使用host
    prefer-ip-address: true

+ 2 - 0
svr/svr-base/src/main/java/com/yihu/SvrBaseApplication.java

@ -6,6 +6,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableAsync;
@ -19,6 +20,7 @@ import javax.servlet.MultipartConfigElement;
 */
@SpringBootApplication
@EnableJpaAuditing
@EnableEurekaClient
@EnableAsync
public class SvrBaseApplication extends SpringBootServletInitializer {

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/service/user/UserService.java

@ -278,7 +278,7 @@ public class UserService extends BaseJpaService<UserDO, UserDao> {
        com.alibaba.fastjson.JSONObject valueJson = null;
        if(org.apache.commons.lang3.StringUtils.isNotBlank(authPw)){
            
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue").orElse(null);;
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue").orElse(null);
            String code[] = wlyyHospitalSysDictDO.getDictCode().split(",");
            Integer maxDateInt = Integer.parseInt(code[0]);
            Integer remainDateInt = Integer.parseInt(code[1]);

+ 59 - 0
svr/svr-base/src/main/resources/application.yml

@ -1110,6 +1110,65 @@ wechat:
pay:
  flag: false
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: 1
---
spring:
  profiles: native
  datasource:
    url: jdbc:mysql://59.61.92.90:8079/query-base?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: xilari
    password: '&}H89@a7&AspSq@'
  elasticsearch:
    cluster-name: jkzl #集群名 默认elasticsearch
    cluster-nodes: 172.19.103.45:9300,172.19.103.68:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    client-transport-sniff: false
    jest:
      uris: http://172.19.103.45:9200,http://172.19.103.68:9200
      connection-timeout: 60000 # Connection timeout in milliseconds.
      multi-threaded: true # Enable connection requests from multiple execution threads.
  activemq:
    broker-url: tcp://172.19.103.87:61616
    user: admin
    password: admin
  redis:
    host: 59.61.92.90
    port: 9054
    password: o!a1#B74&m
#basedb: #base数据基础数据数据源,用于跨库查询
#  name: base
#base:
#  url: http://172.17.110.212:10020/
fastDFS:
  fastdfs_file_url: http://10.172.0.61:80/
demo:
  flag: true
basedb:
  name: base
base:
  url: http://172.17.110.212:10020/
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
wlyy:
  url: http://ehr.yihu.com/wlyy/
wechat:
  id: hz_yyyzh_wx
  url: https://zhyzh.gongshu.gov.cn/
  flag: false
pay:
  flag: false
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream

+ 12 - 2
svr/svr-base/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name: svr-base---
    name: svr-base
  cloud:
    config:
      failFast: true
@ -180,4 +180,14 @@ spring:
  cloud:
    config:
      uri: ${wlyy.pring.config.uri:http://127.0.0.1:1221}
      label: ${wlyy.spring.config.label:master}
      label: ${wlyy.spring.config.label:master}
---
spring:
  cloud:
    config:
      uri: ${wlyy-spring.config.uri:http://127.0.0.1:1221}
      label: ${wlyy-spring.config.label:master}
  config:
    activate:
      on-profile: native

+ 82 - 82
svr/svr-basic/src/main/java/com/yihu/jw/basic/config/ActiveMQConfig.java

@ -1,82 +1,82 @@
package com.yihu.jw.basic.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import javax.jms.ConnectionFactory;
/**
 * Created by chenweida on 2017/9/9.
 * 生产者配置
 */
@EnableJms
@Configuration
public class ActiveMQConfig {
    @Value("${activemq.username}")
    private String username;
    @Value("${activemq.password}")
    private String password;
    @Value("${activemq.url}")
    private String url;
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
        //设置异步发送
        activeMQConnectionFactory.setUseAsyncSend(true);
        return activeMQConnectionFactory;
    }
    /**
     * 缓存session链接
     */
    @Bean
    @Primary
    public CachingConnectionFactory CachingConnectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        //Session缓存数量,这里属性也可以直接在这里配置
        cachingConnectionFactory.setSessionCacheSize(100);
        return cachingConnectionFactory;
    }
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory( CachingConnectionFactory());
        return jmsTemplate;
    }
    @Bean
    public JmsMessagingTemplate jmsMessageTemplate(){
        return new JmsMessagingTemplate(CachingConnectionFactory());
    }
    // 在Queue模式中,对消息的监听需要对containerFactory进行配置
    @Bean("queueListener")
    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(false);
        return factory;
    }
    //在Topic模式中,对消息的监听需要对containerFactory进行配置
    @Bean("topicListener")
    public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true);
        return factory;
    }
}
//package com.yihu.jw.basic.config;
//
//import org.apache.activemq.ActiveMQConnectionFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Primary;
//import org.springframework.jms.annotation.EnableJms;
//import org.springframework.jms.config.JmsListenerContainerFactory;
//import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
//import org.springframework.jms.connection.CachingConnectionFactory;
//import org.springframework.jms.core.JmsMessagingTemplate;
//import org.springframework.jms.core.JmsTemplate;
//
//import javax.jms.ConnectionFactory;
//
///**
// * Created by chenweida on 2017/9/9.
// * 生产者配置
// */
//@EnableJms
//@Configuration
//public class ActiveMQConfig {
//    @Value("${activemq.username}")
//    private String username;
//    @Value("${activemq.password}")
//    private String password;
//    @Value("${activemq.url}")
//    private String url;
//
//    @Bean
//    public ActiveMQConnectionFactory activeMQConnectionFactory() {
//        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
//        //设置异步发送
//        activeMQConnectionFactory.setUseAsyncSend(true);
//        return activeMQConnectionFactory;
//    }
//
//    /**
//     * 缓存session链接
//     */
//    @Bean
//    @Primary
//    public CachingConnectionFactory CachingConnectionFactory() {
//        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
//        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
//        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
//        //Session缓存数量,这里属性也可以直接在这里配置
//        cachingConnectionFactory.setSessionCacheSize(100);
//        return cachingConnectionFactory;
//    }
//
//    @Bean
//    public JmsTemplate jmsTemplate() {
//        JmsTemplate jmsTemplate = new JmsTemplate();
//        jmsTemplate.setConnectionFactory( CachingConnectionFactory());
//        return jmsTemplate;
//    }
//
//    @Bean
//    public JmsMessagingTemplate jmsMessageTemplate(){
//        return new JmsMessagingTemplate(CachingConnectionFactory());
//    }
//
//    // 在Queue模式中,对消息的监听需要对containerFactory进行配置
//    @Bean("queueListener")
//    public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
//        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory);
//        factory.setPubSubDomain(false);
//        return factory;
//    }
//
//    //在Topic模式中,对消息的监听需要对containerFactory进行配置
//    @Bean("topicListener")
//    public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
//        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory);
//        factory.setPubSubDomain(true);
//        return factory;
//    }
//}

+ 69 - 69
svr/svr-basic/src/main/java/com/yihu/jw/basic/redis/controler/ActiveMQEndpoint.java

@ -1,69 +1,69 @@
package com.yihu.jw.basic.redis.controler;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by yeshijie on 2022/9/15.
 */
@RestController
@Api( tags = {"ActiveMQ--消息队列接口"})
public class ActiveMQEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @PostMapping("/queue/test")
    public String sendQueue(String str,String queue) {
        this.sendMessage(queue, str);
        return "success";
    }
    @PostMapping("/topic/test")
    public String sendTopic(String str,String topic) {
        jmsMessagingTemplate.convertAndSend(new ActiveMQTopic(topic), str);
        return "success";
    }
    // 发送消息,destination是发送到的队列,message是待发送的消息
    private void sendMessage(String queue, final String message){
        jmsMessagingTemplate.convertAndSend(queue, message);
    }
    //queue模式的消费者
    @JmsListener(destination="queue1", containerFactory="queueListener")
    public void readActiveQueue1(String message) {
        System.out.println("queue1接受到:" + message);
    }
    //queue模式的消费者
    @JmsListener(destination="queue2", containerFactory="queueListener")
    public void readActiveQueue2(String message) {
        System.out.println("queue2接受到:" + message);
    }
    //queue模式的消费者
    @JmsListener(destination="topic1", containerFactory="queueListener")
    public void readActiveQueue3(String message) {
        System.out.println("queue3接受到:" + message);
    }
    //topic模式的消费者
    @JmsListener(destination="topic1", containerFactory="topicListener")
    public void readActiveTopic1(String message) {
        System.out.println("topic1接受到:" + message);
    }
    //topic模式的消费者
    @JmsListener(destination="topic2", containerFactory="topicListener")
    public void readActiveTopic2(String message) {
        System.out.println("topic2接受到:" + message);
    }
}
//package com.yihu.jw.basic.redis.controler;
//
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import io.swagger.annotations.Api;
//import org.apache.activemq.command.ActiveMQTopic;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.jms.annotation.JmsListener;
//import org.springframework.jms.core.JmsMessagingTemplate;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RestController;
//
///**
// * Created by yeshijie on 2022/9/15.
// */
//@RestController
//@Api( tags = {"ActiveMQ--消息队列接口"})
//public class ActiveMQEndpoint extends EnvelopRestEndpoint {
//
//    @Autowired
//    private JmsMessagingTemplate jmsMessagingTemplate;
//
//    @PostMapping("/queue/test")
//    public String sendQueue(String str,String queue) {
//        this.sendMessage(queue, str);
//        return "success";
//    }
//
//    @PostMapping("/topic/test")
//    public String sendTopic(String str,String topic) {
//        jmsMessagingTemplate.convertAndSend(new ActiveMQTopic(topic), str);
//        return "success";
//    }
//
//    // 发送消息,destination是发送到的队列,message是待发送的消息
//    private void sendMessage(String queue, final String message){
//        jmsMessagingTemplate.convertAndSend(queue, message);
//    }
//
//    //queue模式的消费者
//    @JmsListener(destination="queue1", containerFactory="queueListener")
//    public void readActiveQueue1(String message) {
//        System.out.println("queue1接受到:" + message);
//    }
//
//    //queue模式的消费者
//    @JmsListener(destination="queue2", containerFactory="queueListener")
//    public void readActiveQueue2(String message) {
//        System.out.println("queue2接受到:" + message);
//    }
//
//    //queue模式的消费者
//    @JmsListener(destination="topic1", containerFactory="queueListener")
//    public void readActiveQueue3(String message) {
//        System.out.println("queue3接受到:" + message);
//    }
//
//
//    //topic模式的消费者
//    @JmsListener(destination="topic1", containerFactory="topicListener")
//    public void readActiveTopic1(String message) {
//        System.out.println("topic1接受到:" + message);
//    }
//
//    //topic模式的消费者
//    @JmsListener(destination="topic2", containerFactory="topicListener")
//    public void readActiveTopic2(String message) {
//        System.out.println("topic2接受到:" + message);
//    }
//}

+ 99 - 0
svr/svr-basic/src/main/resources/application.yml

@ -8,6 +8,10 @@ info:
    version: 1.0.0
spring:
  cloud:
    loadbalancer:
      ribbon:
        enabled: false
  data:
    redis:
      repositories:
@ -225,6 +229,101 @@ im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
#消息队列
activemq:
  username: admin
  password: admin
  url: tcp://172.26.0.116:61616
url:
  svr_quota: http://172.26.0.153:10031
---
spring:
  profiles: native
  datasource:
    url: jdbc:mysql://59.61.92.90:8079/query-base?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: xilari
    password: '&}H89@a7&AspSq@'
#hibernate 配置
hibernate:
  dialect: org.hibernate.dialect.MySQL5Dialect
  show_sql: true
  ejb:
    naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
  physical_naming_strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
  implicit_naming_strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
  # -- unknown use --
  ldap:
    host: 172.19.103.87
    port: 389
    bindDn: cn=admin,dc=ehr,dc=jkzl
    password: jkzl
    root: dc=ehr,dc=jkzl
  # -- unknown use --
  redis:
    host: 59.61.92.90
    port: 9054
    password: o!a1#B74&m
  data:
    mongodb:
      host: 192.168.1.220
      port: 27017
      username: admin
      password: admin
      authenticationDatabase: admin
      database: ehr
    solr:
      zk-host: node1.hde.h3c.com,node2.hde.h3c.com,node3.hde.h3c.com:2181/solr
  elasticsearch:
    jest:
      uris: http://172.19.103.68:9200
fastDFS:
  fastdfs_file_url: http://127.0.0.1:8888/
fast-dfs:
  tracker-server: 172.26.0.200:22122
  public-server: http://172.26.0.200:80
elasticsearch:
  cluster-name: jkzl
  cluster-nodes: 172.26.0.112:9300
deploy:
  region: 3502
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.112:9200
  tHost: 172.26.0.112:9300
  clusterName: jkzl
  securityUser: jkzl:jkzlehr
  user: jkzl
  password: jkzlehr
wechat:
  id: xm_mlw_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
  url: http://172.16.100.37:8090/hospitalPortal-sms/sms/sendMessage
wlyy:
  url: http://
demo:
  flag: true
#支付支付
pay:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
express:
  sf_url: https://mr
  sf_code: JKZL
  sf_check_word: Qke
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
#消息队列
activemq:
  username: admin
  password: admin

+ 9 - 8
svr/svr-basic/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name: svr-basic-ysj
    name: svr-basic
  cloud:
    config:
      failFast: true
@ -17,17 +17,18 @@ spring:
---
spring:
  profiles: prod
  profiles: mlwTest
  cloud:
    config:
      uri: ${spring.config.uri}
      label: ${spring.config.label}
      uri: ${spring.config.uri:http://172.26.0.153:1221}
      label: ${spring.config.label:dev}
---
spring:
  profiles: mlwTest
  cloud:
    config:
      uri: ${spring.config.uri:http://172.26.0.153:1221}
      label: ${spring.config.label:dev}
      uri: ${wlyy-spring.config.uri:http://127.0.0.1:1221}
      label: ${wlyy-spring.config.label:master}
  config:
    activate:
      on-profile: native

+ 15 - 0
svr/svr-visit-behind/pom.xml

@ -16,6 +16,21 @@
    <version>${project.parent.version}</version>
    <dependencies>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>${version.wlyy-common}</version>
        </dependency>
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
            <version>4.2.3-GA</version>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>

+ 169 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/async/AsynService.java

@ -0,0 +1,169 @@
package com.yihu.jw.hospital.async;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPatientInfoDO;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.json.JSONObject;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
 * 异步方法
 * Created by yeshijie on 2022/8/8.
 */
@Service
public class AsynService {
    private Logger logger = LoggerFactory.getLogger(AsynService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtil imUtill;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    /**
     * 创建随访计划job
     * @param jsonArray
     */
    @Async
    public void createFollowJob(JSONArray jsonArray, String planId, SignFamily signFamily){
        //创建过期job
        StringBuilder insertSql = new StringBuilder("INSERT into wlyy_followup_job(followup_id,expired_time,status,type)VALUES ");
        boolean bl = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
            String time = "";
            if("6".equals(jsonObject.get("hospitalServiceItemId").toString()) && "1".equals(jsonObject.get("followupDetailType")!=null?jsonObject.get("followupDetailType").toString():"0")){
                if(!bl){
                    bl = true;
                    time=DateUtil.dateToStrLong(DateUtil.getPreDays(DateUtil.strToDate(jsonObject.get("executeTime").toString()), 5));
                }else {
                    time=DateUtil.dateToStrLong(DateUtil.getPreDays(DateUtil.strToDate(jsonObject.get("executeTime").toString()), 7));
                }
                insertSql.append("('"+jsonObject.get("id")+"','"+time+"',1,0),");
            }
            //厦心自动创建新增社区随访表单
            if("6".equals(jsonObject.get("hospitalServiceItemId").toString())){
                //创建康复随访
                JSONObject data = new JSONObject();
                data.put("date",jsonObject.get("executeTime").toString());
                data.put("type","2");
                data.put("doctor",signFamily.getDoctor());
                data.put("followupClass","21");
                data.put("type1","1");
                data.put("id",jsonObject.get("id")+"");
                JSONObject dataJson = new JSONObject();
                //dataJson: {"rehabilitationDetailId":"808080eb827bb19601827bfb355b0039","patientCode":"6ce60381c5b14ea0884ead2af1c2063a","patientName":"黄金坤"
                // ,"doctorCode":"1b9fa6e86c5e468cbd0f2aabade30c35","doctorName":"王清秀","relationRecordType":5,"relationRecordCode":"","status":0}
                dataJson.put("rehabilitationDetailId",jsonObject.get("id")+"");
                dataJson.put("patientCode",signFamily.getPatient());
                dataJson.put("patientName",signFamily.getName());
                dataJson.put("doctorCode",signFamily.getDoctor());
                dataJson.put("doctorName",signFamily.getDoctorName());
                dataJson.put("relationRecordType",5);
                dataJson.put("relationRecordCode","");
                dataJson.put("status",0);
                try {
                    followUpService.addFollowupPlanNew(signFamily.getDoctor(),signFamily.getPatient(),data,dataJson.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(bl){
            jdbcTemplate.execute(insertSql.substring(0,insertSql.length()-1)+";");
        }
        //创建提醒job
        //创建一条随访计划提醒
        String preDayStr = "";
        Date afterDate =DateUtil.strToDate(DateUtil.getStringDateShort()+" 10:00:00");
        if(afterDate.before(afterDate)){
            //早于上午十点
            preDayStr = DateUtil.dateToStrLong(afterDate);
        }else {
            //晚于上午十点
            preDayStr = DateUtil.dateToStrLong(DateUtil.getPreDays(afterDate,1));
        }
        String sql = "INSERT into wlyy_followup_job(followup_id,expired_time,status,type) VALUES ('"+planId+"','"+preDayStr+"',1,1)";
        jdbcTemplate.execute(sql);
    }
    /**
     * 发送消息
     */
    @Async
    public void sendMsg(String planId, SignFamily signFamily, BasePatientDO patient, BaseDoctorDO doctor, PatientMedicalRecordsDO patientMedicalRecordsDO1, RehabilitationPatientInfoDO re){
        try {
            org.json.JSONArray serverDoctorList = rehabilitationManageService.selectPlanServerDoctor(planId,signFamily.getDoctor());
            int length = serverDoctorList.length();
            BaseDoctorDO signDoctor = doctorDao.findById(signFamily.getDoctor()).orElse(null);
            for (int i=0;i<length;i++){
                JSONObject serverJson = serverDoctorList.getJSONObject(i);
                if (serverJson.getString("type").equals("4")){
                    String sessionId = serverJson.getString("sessionId");
                    JSONObject messageJson = new JSONObject();
                    String message= signDoctor.getName()+"医生您好,住院患者"+patient.getName()+"已出院,请您及时接收管理,保持联系,谢谢。";
                    messageJson.put("message",message);
                    messageJson.put("patientCode",patient.getId());
                    messageJson.put("patientName",patient.getName());
                    messageJson.put("medicalRecordDo", JSON.toJSONString(patientMedicalRecordsDO1));
                    ImUtil.sendImMsg(doctor.getId(),doctor.getName(),sessionId,"3101",messageJson.toString(),"1");
                }
            }
        } catch (RuntimeException se) {
            se.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
        //厦心下转的居民给厦心推送居民签约信息
        if("12350200568420163H".equals(re.getHospitalCode())){
            xxSendPatientBaseInfo(re.getIdcard());
        }
    }
    /**
     * i健康推送患者信息给厦心集成平台
     * @param idCard
     */
    public void xxSendPatientBaseInfo(String idCard){
        try {
            String url = jwUrl +"/third/emr/xxSendPatientBaseInfo?idCard="+idCard;
            String re = httpClientUtil.get(url,"UTF-8");
            logger.info(idCard+":xxSendPatientBaseInfo:"+re);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

+ 0 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/GcTokenController.java

@ -1,7 +1,6 @@
package com.yihu.jw.hospital.endpoint.gateway;
import com.yihu.jw.entity.iot.gateway.GcClientDetails;
import com.yihu.jw.entity.iot.gateway.GcHttpLog;
import com.yihu.jw.entity.iot.gateway.GcToken;
@ -13,7 +12,6 @@ import com.yihu.jw.hospital.endpoint.gateway.model.GcClientDetailsModel;
import com.yihu.jw.hospital.endpoint.gateway.model.GcTokenModel;
import com.yihu.jw.hospital.endpoint.gateway.model.ResultOneModel;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.iot.IotRequestMapping;
import com.yihu.jw.util.common.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

+ 385 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java

@ -0,0 +1,385 @@
package com.yihu.jw.hospital.module.consult.service;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.order.dao.ConsultOrderDao;
import com.yihu.jw.util.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.UUID;
@Component
@Transactional
public class ConsultService {
	@Autowired
	public ConsultOrderDao consultDao;
//    @Autowired
//    public BasePatientDao patientDao;
    @Autowired
    public BaseDoctorDao doctorDao;
    @Autowired
    public ConsultTeamDao consultTeamDao;
    @Autowired
    private ImUtil imUtill;
//    @Value("${hlwyy.url}")
//    private String hlwyyUrl;
//    @Value("${im.data_base_name}")
////    private String ImDbName;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    public ConsultMoViDao consultMoViDao;
//    @Autowired
//    public ConsultPublicDao consultPublicDao;
//    @Autowired
//    public ConsultPublicReplyDao consultPublicReplyDao;
//    @Autowired
//    public ConsultCommunicationDao consultCommunicationDao;
//    @Autowired
//    public ConsultCommunicationReplyDao consultCommunicationReplyDao;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PatientService patientService;
    /**
     * 添加一条咨询记录
     *
     * @param patient 患者信息
     * @param title   咨询标题
     * @param type    咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,9在线复诊,11上门服务
     * @return
     */
    public ConsultDo addConsult(String patient, String title, String symptoms, String images, int type) {
        ConsultDo consult = new ConsultDo();
        consult.setCode(UUID.randomUUID().toString().replaceAll("-", ""));//UUID
        consult.setCzrq(new Date());
        consult.setDel("1");
        consult.setPatient(patient);
        consult.setTitle(title);
        consult.setSymptoms(symptoms);
        consult.setImages(images);
        consult.setType(type);
        //这边是没有签约
//		SignFamily signFamily = signFamilyDao.findByPatient(patient);
//		if(signFamily!=null){
//			consult.setSignCode(signFamily.getCode());
//		}
        return consultDao.save(consult);
    }
    /**
     * 查询患者所有的咨询记录
     *
     * @param patient  患者标识
     * @param id
     * @param pagesize 分页大小
     * @return
     */
//    public Page<Object> findConsultRecordByPatient(String patient, long id, int pagesize, String title) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (!StringUtils.isEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultDao.findByPatient(patient, title, id, pageRequest);
//            } else {
//                return consultDao.findByPatient(patient, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultDao.findByPatient(patient, id, pageRequest);
//            } else {
//                return consultDao.findByPatient(patient, pageRequest);
//            }
//        }
//    }
    /**
     * 按类型查找居民的咨询记录
     *
     * @return
     */
//    public Page<Object> findConsultRecordByType(String patient, long id, int pagesize, Integer type, String title) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest((int) id, pagesize, sort);
//        if (!StringUtils.isEmpty(title)) {
//            title = "%" + title + "%";
//            return consultDao.findByPatientAndType(patient, title, type, pageRequest);
//        } else {
//            return consultDao.findByPatientAndType(patient, type, pageRequest);
//        }
//
//    }
//    public Consult findOneConsult(String consult) {
//        return consultDao.findByCode(consult);
//    }
//    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
//        Doctor d = doctorDao.findByCode(doctor);
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);//当前签约团队
//        if (signFamily == null) {
//            List<SignFamily> signFamilys = signFamilyDao.findLastJySignByPatient(patient, 2);//获取旧的家庭签约关系
//            if (signFamilys != null && signFamilys.size() > 0) {
//                signFamily = signFamilys.get(0);
//            }
//        }
//        if (signFamily != null) {
//            new SendPatientUtil(doctor, doctorName, patient, contentType, content, title, signFamily.getType() + "", signFamily.getTeamCode(), imUtill).start();
//        } else {
//            throw new RuntimeException("无法找到签约关系!");
//        }
//    }
//    public JSONArray getDoctorConsultSessions(String user_id, String business_type, String status, String page, String size) {
//        BaseDoctorDODO doctor = doctorDao.findById(user_id).orElse(null);user_id);
//        String zbDoctorId = "";
//        if (doctor == null) {
//            return new JSONArray();
//        } else {
//            try {
//                String url = hlwyyUrl + "/open/noLogin/findDoctorByIdCard";
//                Map map = new HashMap<String, String>();
//                map.put("idCard", doctor.getIdcard());
//                String content = com.alibaba.fastjson.JSONObject.toJSONString(map);
//                String params = AesEncryptUtils.encrypt1(content);
//                String response = httpClientUtil.getBodyRawForm(url, params);
//                com.alibaba.fastjson.JSONObject resultObject = com.alibaba.fastjson.JSONObject.parseObject(response);
//                if (resultObject.get("status").equals("200")) {
//                    com.alibaba.fastjson.JSONObject jsonObjectData = com.alibaba.fastjson.JSONObject.parseObject(AesEncryptUtils.decrypt1(resultObject.get("data").toString()));
//                    if (jsonObjectData.getJSONObject("obj") != null) {
//                        zbDoctorId = jsonObjectData.getJSONObject("obj").getString("id");
//                    }
//                }
//            } catch (RuntimeException se) {
//                se.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        List<JSONObject> result = new ArrayList<>();
//        JSONArray patientConsult = imUtill.getSessions(user_id, business_type, status, "0", "9999");
//        for (int i = 0; i < patientConsult.length(); i++) {
//            JSONObject tmp = patientConsult.getJSONObject(i);
//            tmp.put("dataFrom", "wlyy");
//            result.add(tmp);
//        }
//        //获取专家咨询数据
//        if ("1".equals(status) && org.apache.commons.lang3.StringUtils.isNotBlank(zbDoctorId)) {//历史咨询 hlwyy
//            try {
//                String urlTmp;
//                if (hlwyyUrl.equals("http://192.168.120.210:9660/hospital")) {
//                    urlTmp = "http://192.168.120.32:16000/";
//                } else {
//                    urlTmp = "http://172.26.0.105:3000/";
//                }
//
//                String url = urlTmp + "api/v2/sessions/sessionListByType?user_id=" + zbDoctorId + "&page=1&size=9999&business_type=2&type=1";
//                String response = httpClientUtil.get(url, "UTF-8");
//                com.alibaba.fastjson.JSONArray resultObject = com.alibaba.fastjson.JSONArray.parseArray(response);
//                int arrLength = resultObject.size();
//                for (int i = 0; i < arrLength; i++) {
//                    com.alibaba.fastjson.JSONObject jsonObject = resultObject.getJSONObject(i);
//                    jsonObject.put("dataFrom", "hlwyy");
//                    String sessionIdTmp = jsonObject.getString("id");
//                    url = urlTmp + "api/v2/sessions/" + sessionIdTmp + "/participants/avatars";
//                    response = httpClientUtil.get(url, "UTF-8");
//                    jsonObject.put("hlwyy_user_avatars", response);
//                    String tmp = JSON.toJSONString(jsonObject);
//                    result.add(new JSONObject(tmp));
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        if ("0".equals(status) && org.apache.commons.lang3.StringUtils.isNotBlank(zbDoctorId)) {//进行中咨询
//            try {
//                String urlTmp;
//                if (hlwyyUrl.equals("http://192.168.120.210:9660/hospital")) {
//                    urlTmp = "http://192.168.120.32:16000/";
//                } else {
//                    urlTmp = "http://172.26.0.105:3000/";
//                }
//
//                String url = urlTmp + "api/v2/sessions/sessionListByType?user_id=" + zbDoctorId + "&page=1&size=9999&business_type=2&status=0&type=1";
//                String response = httpClientUtil.get(url, "UTF-8");
//                com.alibaba.fastjson.JSONArray resultObject = com.alibaba.fastjson.JSONArray.parseArray(response);
//                int arrLength = resultObject.size();
//                for (int i = 0; i < arrLength; i++) {
//                    com.alibaba.fastjson.JSONObject jsonObject = resultObject.getJSONObject(i);
//                    jsonObject.put("dataFrom", "hlwyy");
//                    String sessionIdTmp = jsonObject.getString("id");
//                    url = urlTmp + "api/v2/sessions/" + sessionIdTmp + "/participants/avatars";
//                    response = httpClientUtil.get(url, "UTF-8");
//                    jsonObject.put("hlwyy_user_avatars", response);
//                    String tmp = JSON.toJSONString(jsonObject);
//                    result.add(new JSONObject(tmp));
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        //咨询历史未读消息数量统计
//        Collections.sort(result, new Comparator<JSONObject>() {
//            public int compare(JSONObject o1, JSONObject o2) {
//                Long map1value = Long.parseLong(o1.get("create_date").toString());
//                Long map2value = Long.parseLong(o2.get("create_date").toString());
//                Long unRead1 = Long.parseLong(o1.get("unread_count").toString());
//                Long unRead2 = Long.parseLong(o2.get("unread_count").toString());
//                if (unRead1 != 0 || unRead2 != 0) {//未读排前面,再根据时间排序
//                    if (unRead1 != 0 && unRead2 != 0) {
//                        if (map1value - map2value > 0) {
//                            return -1;
//                        } else if (map1value - map2value < 0) {
//                            return 1;
//                        } else {
//                            return 0;
//                        }
//                    } else {
//                        if (unRead1 - unRead2 > 0) {
//                            return -1;
//                        } else if (unRead1 - unRead2 < 0) {
//                            return 1;
//                        } else {
//                            return 0;
//                        }
//                    }
//                } else {
//                    if (map1value - map2value > 0) {
//                        return -1;
//                    } else if (map1value - map2value < 0) {
//                        return 1;
//                    } else {
//                        return 0;
//                    }
//                }
//            }
//        });
//
//        Integer count = result.size();
//        Integer pageTmp = Integer.parseInt(page);
//        Integer sizeTmp = Integer.parseInt(size);
//        if (pageTmp == 0) {
//            pageTmp += 1;
//        }
//        if (count > 0) {
//            Integer pageCount = 0;
//            if (count % sizeTmp == 0) {
//                pageCount = count / sizeTmp;
//            } else {
//                pageCount = count / sizeTmp + 1;
//            }
//            int fromIndex = 0;
//            int toIndex = 0;
//            if (pageTmp != pageCount) {
//                fromIndex = (pageTmp - 1) * sizeTmp;
//                toIndex = fromIndex + sizeTmp;
//            } else {
//                fromIndex = (pageTmp - 1) * sizeTmp;
//                toIndex = count;
//            }
//            if (fromIndex < 0) {
//                fromIndex = 0;
//            }
//            if (toIndex > count) {
//                toIndex = count;
//            }
//            ;
//            return new JSONArray(result.subList(fromIndex, toIndex));
//        }
//        return new JSONArray();
//    }
//    public JSONArray getIMkangFuConsultSessions(String user_id, String type, String status, String page, String size, String name) {
//        List<JSONObject> result = new ArrayList<>();
//        JSONArray patientConsult = imUtill.getSessionListByType(user_id, page, size, type, status, name);
//
//        return patientConsult;
//    }
//    public JSONObject getSpecialAndKangFuConsultUnreadInfo(String user_id) {
//        JSONObject result = new JSONObject();
//        try {
//            BaseDoctorDO doctor = doctorDao.findById(user_id).orElse(null));
//
//            JSONObject specialistObj = new JSONObject();
//            JSONObject kangfuObj = new JSONObject();
//            kangfuObj.put("unReplyCount", 0);
//            kangfuObj.put("UnreadMessageCount", 0);
//            specialistObj.put("zjCount", 0);
//            specialistObj.put("zjUnreadMessageCount", 0);
//            if (doctor != null) {
//                String url = hlwyyUrl + "/open/noLogin/doctorReviewConsultCount";
//                Map map = new HashMap<String, String>();
//                map.put("doctorIdcard", doctor.getIdcard());
//                String content = com.alibaba.fastjson.JSONObject.toJSONString(map);
//                String params = AesEncryptUtils.encrypt1(content);
//                String response = httpClientUtil.getBodyRawForm(url, params);
//
//                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(response);
//                if (json != null && json.getInteger("status") == 200) {
//                    com.alibaba.fastjson.JSONObject jsonTmp = com.alibaba.fastjson.JSONObject.parseObject(AesEncryptUtils.decrypt1(json.getString("data")));
//                    if (jsonTmp.getInteger("status") == 200) {
//                        com.alibaba.fastjson.JSONObject tmp = jsonTmp.getJSONObject("obj");
//                        specialistObj.put("zjCount", tmp.getInteger("imgConsultCount") + specialistObj.getInt("zjCount"));
//                        specialistObj.put("zjUnreadMessageCount", tmp.getInteger("zjUnreadMessageCount") + specialistObj.getInt("zjUnreadMessageCount"));
//                    }
//                }
//                result.put("specialist", specialistObj);
//                //康复未回复
//                String sql = "SELECT count(t.id) count FROM " + ImDbName + ".topics t," + ImDbName + ".participants p," + ImDbName + ".doctors d," + ImDbName + ".wlyy_consults c," +
//                        ImDbName + ".patients s WHERE d.id = p.participant_id AND c.id = t.id AND c.patient = s.id AND p.session_id = t.session_id AND d.id in ('" + user_id + "') AND t. STATUS =0 and t.reply=0 AND c.type = 18 ";
//                Integer notReplayCount = jdbcTemplate.queryForObject(sql, Integer.class);
//                kangfuObj.put("unReplyCount", notReplayCount + kangfuObj.getInt("unReplyCount"));
//                //康复未读
//                org.json.JSONObject jsonObject = imUtill.getSessionUnreadMessageCountByType(user_id, "18", "");
//                kangfuObj.put("UnreadMessageCount", jsonObject.getInt("count") + kangfuObj.getInt("UnreadMessageCount"));
//                result.put("kangfuConsult", kangfuObj);
//                return result;
//            }
//            return null;
//        } catch (RuntimeException se) {
//            se.printStackTrace();
//            return null;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
}

+ 3509 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java

@ -0,0 +1,3509 @@
package com.yihu.jw.hospital.module.consult.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.hospital.module.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.dao.ConsultTeamLogDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.order.dao.ConsultTeamOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.text.DecimalFormat;
import java.util.*;
/**
 * 網絡諮詢类.
 * test
 *
 * @author George
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ConsultTeamService extends ConsultService {
    private final Logger logger = LoggerFactory.getLogger(ConsultTeamService.class);
    private final Clock clock = Clock.DEFAULT;
    @Autowired
    private ConsultTeamOrderDao consultTeamDao;
    // 咨询详细记录
    @Autowired
    private ConsultTeamLogDao consultTeamLogDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
   
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private BasePatientDao patientDao;
    
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    
    
    @Autowired
    private WeiXinAccessTokenUtils accessTokenUtils;
    
    @Autowired
    private BasePatientService patientService;
   
    @Autowired
    private MessageService messageService;
  
    @Autowired
    private PrescriptionExpressageDao expressageDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    
    Map<Integer, String> relations = new HashMap<>();
    @Value("${im.im_list_get}")
    private String im_list_get;
    @Value("${im.data_base_name}")
    private String imdb;
    @Autowired
    private PushMsgTask pushMsgTask;
    
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private BaseDoctorInfoService doctorService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private PatientDeviceDao patientDeviceDao;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PatientHealthGuidanceService guidanceService;
//    @Autowired
//    private PatientFamilyMemberDao familyMemberDao;
//    @Autowired
//    private HealthEduArticleService healthEduArticleService;
//    @Autowired
//    private CsrfConstant csrfConstant;
//    @Autowired
//    private ConsultHelpDao consultHelpDao;
//    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private DoctorAssistantUtil doctorAssistantUtil;
//    @Autowired
//    private PrescriptionExplainDao prescriptionExplainDao;
//    @Autowired
//    private ExaminationDao examinationDao;
//    @Autowired
//    private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;
//    @Autowired
//    private SpecialDiseaseMessagesDao specialDiseaseMessagesDao;
//    @Autowired
//    private PrescriptionFollowupContentService prescriptionFollowupContentService;
//    @Autowired
//    private SystemDictDao systemDictDao;
//    @Autowired
//    private FollowUpDao followupDao;
//    @Autowired
//    private PrescriptionReviewedDao prescriptionReviewedDao;
//    @Autowired
//    private JwPrescriptionService jwPrescriptionService;
//    @Autowired
//    private PrescriptionInfoService prescriptionInfoService;
//    @Autowired
//    private PresModeAdapter presModeAdapter;
//    @Autowired
//    private ZyDictService zyDictService;
    /**
     * 添加上门服务咨询
     */
    public JSONObject addDoorServiceConsult(String orderId) throws Exception {
        JSONObject result = new JSONObject();
        //上门服务关联的工单
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        String patient = doorServiceOrderDO.getPatient();
        String doctor = doorServiceOrderDO.getDispatcher();
        String doctorName = doorServiceOrderDO.getDispatcherName();
        int orderStatus = doorServiceOrderDO.getStatus();
//        // 判断居民是否已经签约
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        if (signFamily == null) {
//            result.put(ResponseContant.resultFlag, ResponseContant.fail);
//            String failMsg = "当前居民未签约,无法进行上门服务咨询!";
//            result.put(ResponseContant.resultMsg, failMsg);
//            return result;
//        }
        // 添加咨询记录
        BasePatientDO patientDO = patientService.findPatientById(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 = super.addConsult(patient, title, doorServiceOrderDO.getServeDesc(), patientDO.getPhone(), 11);
        //咨询详细信息
        ConsultTeamDo consultTeam = new ConsultTeamDo();
        consultTeam.setType(11);  //上门服务咨询
//        consultTeam.setAdminTeamId(signFamily.getAdminTeamId());//签约团队的信息-这边没有
        consultTeam.setRelationCode(doorServiceOrderDO.getId()); //关联业务code
        consultTeam.setSymptoms(doorServiceOrderDO.getServeDesc());
        consultTeam.setPatient(patient);
        consultTeam.setName(patientDO.getName());
        consultTeam.setBirthday(patientDO.getBirthday());
        consultTeam.setSex(patientDO.getSex());
        consultTeam.setPhoto(patientDO.getPhoto());
        consultTeam.setCzrq(new Date());
        consultTeam.setDel("1");
        consultTeam.setStatus(0);
        consultTeam.setEvaluate(0);
        consultTeam.setDoctorRead(1); // 医生未读数量为1
        consult.setRelationCode(doorServiceOrderDO.getId());//关联业务code
        consultTeam.setConsult(consult.getCode()); // 设置咨询标识
        //(im创建咨询) 上门服务咨询的sessionid为居民code+咨询code+工单编号+咨询类型
        String sessionId = patient + "_" + consult.getCode() + "_" + doorServiceOrderDO.getNumber() + "_" + consultTeam.getType();
        //4、 上门服务咨询-参与者
        JSONObject participants = new JSONObject();
        participants.put(patient, 0);
//        String content = patientDO.getName() + "-上门服务咨询";
//        String content = signFamily.getHospitalName() + "为您服务";
        String content = doorServiceOrderDO.getDoctorName() + "为您服务";
        JSONObject messages = imUtill.getCreateTopicMessage(patient, patientDO.getName(), consult.getTitle(), content, consult.getImages(), "");
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getCode(), content, participants, messages, imUtill.SESSION_TYPE_ONDOOR_NURSING);
        if (imResponseJson == null || imResponseJson.getString("status").equals("-1")) {
            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
    
//    @PostConstruct
//    public void init() {
//        relations.put(0, "其他");
//        relations.put(1, "父亲");
//        relations.put(2, "母亲");
//        relations.put(3, "老公");
//        relations.put(4, "老婆");
//        relations.put(5, "儿子");
//        relations.put(6, "女儿");
//        relations.put(7, "未知");
//        csrfConstant.init();
//    }
    /**
     * 查找邀请医生列表
     *
     * @param consultCode 咨询code
     * @param type        1家签医生 2社区邀约 3专病防治中心
     * @param hospital    医院code
     * @param deptName    科室名称
     * @param disease     专病类型
     * @param name        医生、机构、科室
     * @param sortBy      排序 不传默认综合
     *                    综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    1被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    2回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
     *                    3平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
     *                    4用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
     * @param size
     */
//    public PageEnvelop findHelpDoctorPage(String uid, String consultCode, String type, String hospital, String sortBy,
//                                          String deptName, String disease, String name, Integer page, Integer size) {
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor d = doctorDao.findByCode(uid);
//        boolean flag = true;
//        if (d != null) {
//            if (Constant.testHospital.equals(d.getHospital())) {
//                flag = false;
//            }
//        }
//        String patient = consult.getPatient();
//        String field = "";
//        if ("3".equals(type)) {
//            field = ",a.special_code specialCode,a.special_name specialName";
//        }
//        String sql = "SELECT DISTINCT d.code,d.name,d.photo,d.job_name jobName,d.dept_name deptName,d.hospital_name hospitalName " +
//                field + ",ifnull(h.reply_rate,'0%') replyRate " +
//                ",ifnull(h.average_response,0) averageResponse,ifnull(h.evaluate_score,80) evaluateScore " +
//                ",ifnull(h.invite_num,0) inviteNum,ifnull(h.invited_num,0) invitedNum " +
//                ",if(sf.id is null,0,1) 'signFlag',if(p.id is null,0,1) 'zbFlag' ";
//        String countSql = "select count(DISTINCT d.code) ";
//        String filter = "";
//        if ("3".equals(type)) {
//            filter = " from wlyy_admin_team a,wlyy_admin_team_member m,wlyy_doctor d " +
//                    " LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_specialist.wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE a.accept_type = 0 and a.available =1 and a.special_code is not null " +
//                    " and a.id = m.team_id and m.available=1 and m.doctor_code=d.code and d.`status`=1 ";
//            if (StringUtils.isNotBlank(disease)) {
//                filter += " and a.special_code='" + disease + "' ";
//            }
//        } else {
//            filter = "from wlyy_hospital_invite_specialist s,wlyy_doctor d " +
//                    "LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_specialist.wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE s.specialist=d.code and d.`status`=1 and s.type = '" + type + "' ";
//            if ("2".equals(type) && d != null) {
//                filter += " and s.hospital='" + d.getHospital() + "' ";
//            }
//        }
//        //排除医生自己
//        filter += " and d.code!='" + uid + "' ";
//        if (StringUtils.isNotBlank(hospital)) {
//            filter += " and d.hospital='" + hospital + "' ";
//        }
//        if (StringUtils.isNotBlank(deptName)) {
//            filter += " and d.dept_name='" + deptName + "' ";
//        }
//        if (StringUtils.isNotBlank(name)) {
//            filter += " and (d.name like '%" + name + "%' or d.dept_name like '%" + name + "%' or d.hospital_name like '%" + name + "%')";
//        }
//
//        if (flag) {
//            filter += " and d.hospital !='" + Constant.testHospital + "' ";
//        }
//        String orderBy = "";
//        if ("1".equals(sortBy)) {
//            //被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        } else if ("2".equals(sortBy)) {
//            //回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
//            orderBy = " order by replyRate desc,invitedNum desc,averageResponse desc,evaluateScore desc ";
//        } else if ("3".equals(sortBy)) {
//            //平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
//            orderBy = " order by averageResponse desc,invitedNum desc,replyRate desc,evaluateScore desc ";
//        } else if ("4".equals(sortBy)) {
//            //用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
//            orderBy = " order by evaluateScore desc,invitedNum desc,replyRate desc,averageResponse desc ";
//        } else {
//            //综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by signFlag desc,zbFlag desc,invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        }
//
//        orderBy += " limit " + (page - 1) * size + "," + size;
//
//        long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql + filter + orderBy);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//        Map<String, String> speMap = consultHelpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        for (Map<String, Object> map : list) {
//            String code = map.get("code") + "";
//            int askFlag = 0;
//            if (speMap.containsKey(code)) {
//                askFlag = 1;
//            }
//            map.put("askFlag", askFlag);
//        }
//        return PageEnvelop.getSuccessListWithPage("获取成功", list, page, size, count);
//    }
    //专科医生获取家庭医生咨询邀请
//    public Envelop findConsultHelpPage(String specialist, String status, String patientName, Integer page, Integer size) {
//        String sql = "select c.*,p.photo,d.dept_name deptName,d.photo doctorPhoto ";
//        String countSql = " select count(c.id) ";
//        String filter = " from wlyy_consult_help c " +
//                " left join wlyy_patient p on c.patient=p.code " +
//                " left join wlyy_doctor d on c.doctor=d.code " +
//                " where c.specialist='" + specialist + "' ";
//        String orderBy = " order by c.id desc limit " + (page - 1) * size + "," + size;
//        if (StringUtils.isNotBlank(status)) {
//            filter += " and c.status = '" + status + "' ";
//        }
//        if (StringUtils.isNotBlank(patientName)) {
//            filter += " and (c.patient_name like '%" + patientName + "%' or d.name like '%" + patientName + "%')";
//        }
//        Long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<ConsultHelp> helpList = jdbcTemplate.query(sql + filter + orderBy, new BeanPropertyRowMapper<>(ConsultHelp.class));
//
//        return PageEnvelop.getSuccessListWithPage("获取成功", helpList, page, size, count);
//    }
    //结束咨询修改 邀请的状态
//    public void endConsultHelp(String consultCode) {
//        try {
//            List<ConsultHelp> helps = consultHelpDao.findConsultAndStatus(consultCode);
//            if (helps.size() > 0) {
//                List<ConsultHelp> helpList = new ArrayList<>();
//                for (ConsultHelp help : helps) {
//                    String status = help.getStatus();
//                    String specialist = help.getSpecialist();
//                    if ("0".equals(status)) {
//                        help.setStatus("3");
//                        helpList.add(help);
//                    } else if ("1".equals(status)) {
//                        help.setStatus("2");
//                        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialist);
//                        doctorHelp.setInvitedNum(doctorHelp.getInvitedNum() + 1L);
//                        if (doctorHelp.getInviteNum() == null || doctorHelp.getInviteNum() == 0) {
//                            doctorHelp.setInviteNum(1L);
//                        }
//                        doctorHelp.setReplyRate(getRange(doctorHelp.getInvitedNum(), doctorHelp.getInviteNum()));
//                        doctorHelpDao.save(doctorHelp);
//                        helpList.add(help);
//                    }
//                }
//                if (helpList.size() > 0) {
//                    consultHelpDao.save(helpList);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    /**
     * 获取2个数的百分比
     *
     * @param first
     * @param second
     * @return
     */
    public String getRange(Long first, Long second) {
        if (second == 0 && first > 0) {
            return "100%";
        } else if (second == 0 && first == 0) {
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }
    //邀请专科-回复居民咨询
    @Transactional
//    public synchronized void askSpecialist(String consultCode, String sessionId, String doctorCode, String specialistCode) {
//        List<ConsultHelp> helps = consultHelpDao.findByConsultAndSpecialist(consultCode, specialistCode);
//        if (helps.size() > 0) {
//            throw new ServiceException("请勿重复邀请");
//        }
//        //医生统计表
//        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialistCode);
//        if (doctorHelp == null) {
//            doctorHelp = new DoctorHelp();
//            doctorHelp.setDoctor(specialistCode);
//            doctorHelp.setAverageResponse(0L);
//            doctorHelp.setInviteNum(1L);
//            doctorHelp.setResponseTime(0L);
//            doctorHelp.setReplyRate("0%");
//            doctorHelp.setInvitedNum(0L);
//            doctorHelp.setCreateTime(new Date());
//            doctorHelp.setEvaluateScore(80D);
//            doctorHelp.setReplyNum(1L);
//        } else {
//            doctorHelp.setInviteNum(doctorHelp.getInviteNum() + 1L);
//        }
//        doctorHelpDao.save(doctorHelp);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor doctor = doctorDao.findByCode(doctorCode);
//        Doctor specialist = doctorDao.findByCode(specialistCode);
//        Patient patient = patientDao.findByCode(consult.getPatient());
//        Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
//        SignFamily signFamily = signFamilyDao.findByPatient(consult.getPatient());
//        ConsultHelp help = new ConsultHelp();
//        help.setStatus("0");
//        help.setType(consult.getType() + "");
//        help.setPatientName(patient.getName());
//        help.setCreateTime(new Date());
//        help.setConsult(consultCode);
//        help.setPatient(consult.getPatient());
//        help.setDoctor(doctorCode);
//        help.setDoctorName(doctor.getName());
//        help.setHospital(doctor.getHospital());
//        help.setHospitalName(doctor.getHospitalName());
//        help.setSpecialist(specialistCode);
//        help.setSpecialistDept(specialist.getDept());
//        help.setSpecialistName(specialist.getName());
//        help.setSpecialistHospital(specialist.getHospital());
//        help.setSpecialistHospitalName(specialist.getHospitalName());
//        help.setSpecialistDeptName(specialist.getDeptName());
//        help.setTown(hospital.getTown());
//        help.setSessionId(sessionId);
//        help.setAdminTeamId(signFamily.getAdminTeamId());
//        consultHelpDao.save(help);
//
//
//        imUtill.updateParticipant(sessionId, specialistCode, null);
//        //设置邀请消息
//        //居民端和家庭医生端 家庭医生【姓名】已邀请 专科医生【姓名】进入咨询
//        //专科医生端 家庭医生【姓名】邀请您加入了群聊,群聊参与人还有: {患者姓名}{其他群聊成员}
//        String content1 = "家庭医生[" + doctor.getName() + "]已邀请 专科医生[" + specialist.getName() + "]进入咨询";
//        String doctors = signFamily.getDoctorName();
//        if (StringUtils.isNotBlank(signFamily.getDoctorHealthName()) && !doctors.equals(signFamily.getDoctorHealthName())) {
//            doctors += "," + signFamily.getDoctorHealthName();
//        }
//        for (ConsultHelp consultHelp : consultHelpList) {
//            doctors += "," + consultHelp.getSpecialistName();
//        }
//        String content2 = "家庭医生[" + doctor.getName() + "]邀请您加入了群聊,群聊参与人还有:{" + patient.getName() + "}{" + doctors + "}";
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "46", content1, null);
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "47", content2, null);
//
//        //发送医生助手消息
//        String first = specialist.getName() + "医生您好,您收到来自" + doctor.getHospitalName() + "的" + doctor.getName() + "咨询求助,请访问厦门i健康APP查看。";
//        doctorAssistantUtil.sendWXTemplate(9, specialist.getOpenid(), specialist.getCid(), first, "请及时处理", "咨询求助", specialist.getHospitalName(), specialist.getName());
//
//        messageService.addSpecialistDynamicMessages(patient, specialist, doctor, "咨询求助", null, "3", null);
//    }
    /**
     * 医生主动发送im消息
     */
    public void doctorSendImMsg(String patient, String doctor, String doctorName, String sessionId, String content, String contentType) {
        BasePatientDO  p = patientDao.findById(patient).orElse(null);
        if (StringUtils.isNotBlank(p.getOpenid())) {
            WechatTemplateConfig temp = templateConfigDao.findByScene("template_consult_notice", "yszdxx");
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("isPublic", 3);
            String first = temp.getFirst().replaceFirst("key1", doctorName);
            json.put("first", first);
            json.put("toUser", p.getId());
            json.put("represented", p.getId());//被代理人
            if ("1".equals(contentType)) {
                //文本消息
            } else if ("2".equals(contentType)) {
                content = "一条图片消息";
            } else if ("3".equals(contentType)) {
                content = "一条语音消息";
            } else {
                content = "一条消息";
            }
            String url = temp.getUrl() + "&openid=" + p.getOpenid() + "&peerId=" + doctor + "&peerName=" + doctorName;
            json.put("consultcontent", temp.getKeyword1());
            json.put("replycontent", content);
            json.put("doctorName", doctorName);
            json.put("remark", "");
            json.put("url", url);
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
        }
    }
    /**
     * 处方判断
     */
//    public JSONObject isPrescriptConsult(String patient) {
//        JSONObject json = new JSONObject();
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        if (signFamily == null) {
//            json.put("msg", "您还未签约,不能发起续方咨询");
//            return json;
//        }
//
//        //续方说明
//        List<PrescriptionExplain> list = prescriptionExplainDao.findList();
//        JSONArray ja = new JSONArray();
//        for (PrescriptionExplain explain : list) {
//            ja.put(explain.getContent());
//        }
//
//        Doctor doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//
//        Hospital hospital = hospitalDao.findByCode(signFamily.getHospital());
//
//        json.put("doctor", doctor.getCode());
//        json.put("doctorName", doctor.getName());
//        json.put("adminTeamId", signFamily.getAdminTeamId());
//        json.put("hospital", doctor.getHospital());
//        json.put("hospitalName", doctor.getHospitalName());
//        json.put("hospitalAddress", hospital.getAddress());
//        json.put("prescriptionExplain", ja);
//        return json;
//    }
    /**
     * 查询患者是否还有未结束的三师咨询
     */
//    public boolean exist(String patient, Integer type) throws Exception {
//        String memberCode = null;
//        if (type == 2 || type == 18) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//            if (sf == null) {
//                throw new ServiceException("不存在家庭签约");
//            }
//            if (StringUtils.isEmpty(sf.getDoctorHealth())) {
//                memberCode = sf.getDoctor();
//            } else {
//                memberCode = sf.getDoctorHealth();
//            }
//
//        }
//
//        int count = consultTeamDao.countByPatient(patient, type, memberCode);
//        return count > 0;
//    }
    /**
     * 查詢醫生網絡諮詢列表
     *
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的 5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamDo> findByDoctor(String uid, int type, long id, int pagesize, String patient, String title) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        switch (type) {
//            case 0:
//                // 全部
//                return findByDoctorType0(uid, id, patient, pagesize);
//            case 1:
//                // 咨询我的
//                return findByDoctorType1(uid, type, id, pagesize);
//            case 2:
//                // 我感兴趣的
//                return findByDoctorType2(uid, type, id, pagesize);
//            case 3:
//                // 我回复的
//                return findByDoctorType3(uid, id, pagesize);
//            case 4:
//                // 已完成的
//                return findByDoctorType4(uid, id, pagesize);
//            case 5:
//                // 5 名医咨询 全部
//                return findByDoctorType5(uid, id, pagesize, title);
//            case 6:
//                //6 名医咨询 进行中
//                return findByDoctorType6(uid, 0, id, pagesize, title);
//            case 7:
//                //7 名医咨询 已结束
//                return findByDoctorType6(uid, 1, id, pagesize, title);
//            case 8:
//                return findByDoctorType8(uid, id, pagesize, title);
//            case 9:
//                return findByDoctorType9(uid, id, pagesize);
//            case 10:
//                //我咨询的
//                return findByDoctorType10(uid, id, pagesize, title);
//            case 11:
//                //我咨询的 进行中
//                return findByDoctorType11(uid, 0, id, pagesize, title);
//            case 12:
//                //我咨询的 已结束中
//                return findByDoctorType11(uid, 1, id, pagesize, title);
//        }
//        return null;
//    }
//    private Page<ConsultTeamDo> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType10(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType8(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType5(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType6(String uid, int type, long id, int pagesize, String title) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, title, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, title, type, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, type, pageRequest);
//            }
//        }
//    }
    /**
     * 根据状态获取三师家庭咨询
     *
     * @param status 0未处理或未回复 1已回复 2已结束
     */
//    public Page<ConsultTeamDo> findConsultByDoctor(String doctor, int status, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//
//        if (status == 0) {
//            return findConsultByDoctorWcl(doctor, id, pagesize);
//        } else if (status == 1) {
//            return findConsultByDoctorIng(doctor, id, pagesize);
//        } else {
//            return findByDoctorType4(doctor, id, pagesize);
//        }
//    }
    /**
     * 获取三师家庭未处理咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorWcl(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 获取三师家庭已回复咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorIng(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 查询全部咨询记录
     */
//    public Page<ConsultTeamDo> findByDoctorType0(String uid, long id, String patient, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isEmpty(patient)) {
//            if (id > 0) {
//                return consultTeamDao.findDoctorList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorList(uid, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findDoctorPatientList(uid, patient, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorPatientList(uid, patient, pageRequest);
//            }
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType1(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorPointList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorPointList(uid, pageRequest);
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid 医生标识
     */
    public Page<ConsultTeamDo> findByDoctorType9(String uid, long id, int pagesize) {
        return null;
    }
    /**
     * 公共三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType2(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        // 未指定医生
//        filters.put("type", new SearchFilter("type", Operator.EQ, 0));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未回复
//        filters.put("status", new SearchFilter("status", Operator.EQ, 0));
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamDo> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeam.class);
//
//        return consultTeamDao.findAll(spec, pageRequest);
//    }
    /**
     * 医生参与过的未结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType3(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorJoinList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorJoinList(uid, pageRequest);
//        }
//    }
    /**
     * 医生参与过的已结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType4(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorFinishList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorFinishList(uid, pageRequest);
//        }
//    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamLog> findLogByConsult(String consult, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("consult", new SearchFilter("consult", Operator.EQ, consult));
//
//        if (id > 0) {
//            if (pagesize > 0)
//                filters.put("id", new SearchFilter("id", Operator.LT, id));
//            else
//                filters.put("id", new SearchFilter("id", Operator.GT, id));
//        }
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamLog> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeamLog.class);
//
//        if (pagesize <= 0) {
//            Page<ConsultTeamLog> p = new PageImpl<>(consultTeamLogDao.findAll(spec));
//            return p;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        return consultTeamLogDao.findAll(spec, pageRequest);
//    }
    /**
     * 批量回复
     */
//    public void reply(List<ConsultTeamLogDo> logs, String patient) throws Exception {
//        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(logs.get(0).getConsult());
//        WlyyTalkGroup wlyyTalkGroup = talkGroupService.findConsultTalkGroupByType(logs.get(0).getConsult(), 2);
//        for (ConsultTeamLog log : logs) {
//            reply(log, patient, null, log.getType());
//            //判断当前咨询是否创建讨论租
//            if (wlyyTalkGroup != null) {
//                sendGroupIM(patient, wlyyTalkGroup.getCode(), log.getChatType() + "", log.getContent());
//            } else {
//                //推送给IM
//                sendIM(patient, consultTeam.getDoctor(), log.getChatType() + "", log.getContent());
//            }
//        }
//    }
    /**
     * 查询居民咨询记录
     */
//    public JSONArray findByPatientAndTeam(String patient, Long teamCode, int page, int pageSize) {
//        PageRequest pageRequest = new PageRequest(page, pageSize);
//        BasePatientDO  p = patientDao.findByCode(patient);
//        Page<Object> result = consultDao.findByPatientAll(patient, pageRequest);
//        JSONArray array = new JSONArray();
//
//        for (Object obj : result) {
//            JSONObject consult = new JSONObject();
//            Object[] objArr = (Object[]) obj;
//            consult.put("id", objArr[0]);
//            consult.put("code", objArr[2]);
//            consult.put("type", objArr[1]);
//            consult.put("title", objArr[3]);
//            consult.put("symptoms", objArr[4]);
//            consult.put("czrq", objArr[5]);
//            consult.put("status", objArr[6]);
//            consult.put("adminTeamCode", objArr[7]);
//            consult.put("team", objArr[8]);
//            consult.put("patient", patient);
//            consult.put("patientName", p.getName());
//            consult.put("patientPhoto", p.getPhoto());
//            consult.put("total", result.getTotalElements());
//            array.put(consult);
//        }
//
//        return array;
//    }
    /**
     * 添加咨询记录
     *
     * @param log  日志对象
     * @param type 类型,0问,1回复,2追问,3评价
     */
//    public ConsultTeamLogDo reply(ConsultTeamLogDo log, String patient, String teamOrDoctor, int type) {
//        log.setCzrq(clock.getCurrentDate());
//        // 保存咨询记录
//        ConsultTeamLogDo temp = consultTeamLogDao.save(log);
//        if (temp != null) {
//            // 发送消息
//            if (type == 1) {
//                // 医生回复,给患者发消息
//                // 患者未读数量+1
//                consultTeamDao.increasePatientRead(log.getConsult());
//                // 医生有回复
//                consultTeamDoctorDao.updateReply(log.getConsult(), teamOrDoctor);
//
//                //shenzaixin v1.2.0 推送消息给患者
//                //HttpUtil.sendWeixinWebsocketMsg(patient, "{busiType:'qianyuezixun',msgid:'" + log.getId() + "'}");
//            } else if (type == 0 || type == 2) {
//                // 查询相关联的医生
//                Iterable<ConsultTeamDoctorDo> iterable = consultTeamDoctorDao.findByConsult(log.getConsult());
//                if (iterable != null && iterable.iterator().hasNext()) {
//                    Iterator<ConsultTeamDoctorDo> iterator = iterable.iterator();
//                    while (iterator.hasNext()) {
//                        // 患者提问或追问,给医生发消息
//                        ConsultTeamDoctorDo ctd = iterator.next();
//                        if (ctd == null) {
//                            continue;
//                        }
//                        // 推送消息给医生
//                        pushMsgTask.put(ctd.getTo(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.D_CT_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.您有新的消息.name(), temp.getConsult());
//                    }
//                }
//                // 医生未读数量+1
//                consultTeamDao.increaseDoctorRead(log.getConsult());
//            }
//        }
//        return temp;
//    }
    /**
     * 患者直接发起康复咨询
     */
//    public JSONObject addRecoverConsult(ConsultTeamDo ct, Long teamId, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        //议题添加团队内所有成员
//        JSONObject users = new JSONObject();
//        String specialDoctorCode = "";
//        List<BaseDoctorDO> docList = doctorAdminTeamMemberDao.findAllMembers(teamId);
//        for (BaseDoctorDO doc : docList) {
//            if (StringUtils.isBlank(specialDoctorCode) && doc.getLevel() == 1) {
//                specialDoctorCode = doc.getId();
//            }
//            users.put(doc.getId(), 0);
//        }
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        // 获取家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//        if (sf == null) {
//            // 不存在家庭签约
//            re.put("status", -1);
//            return re;
//        }
//        ct.setTeam(sf.getTeamCode());
//        // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//        //查找病人所在的团队
//        //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//        if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//            users.put(sf.getDoctorHealth(), 0);
//            ct.setDoctor(sf.getDoctorHealth());
//            if (StringUtils.isNotBlank(sf.getDoctor())) {
//                if (users.isNull(sf.getDoctor())) {
//                    //全科需要判断是否开启健管师邀请后在接收消息
//                    int isGetMessage = 1;
//                    if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                        isGetMessage = 0;
//                    }
//                    users.put(sf.getDoctor(), isGetMessage);
//                }
//            }
//        } else {
//            ct.setDoctor(sf.getDoctor());
//            users.put(sf.getDoctor(), 0);
//        }
//        ct.setAdminTeamId(teamId);
//
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        String sessionId = patient + "_" + ct.getDoctor() + "_" + specialDoctorCode + "_" + ct.getType();
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        //specialDoctorCode
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//            SpecialDiseaseMessages diseaseMessages = new SpecialDiseaseMessages();
//            diseaseMessages.setCode(patient);
//            diseaseMessages.setName(tempPatient.getName());
//            diseaseMessages.setAddress(tempPatient.getAddress());
//            diseaseMessages.setCodeType("2");
//            diseaseMessages.setCreateTime(sdf.format(new Date()));
//            diseaseMessages.setResult("发起康复咨询");
//            specialDiseaseMessagesDao.save(diseaseMessages);
//        } catch (Exception e) {
//            logger.info("ConsultTeamService中 addRecoverConsult 方法保存出错");
//            e.printStackTrace();
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 患者端
     * 添加三师咨询
     *
     * @param ct      三师咨询对象
     * @param patient 患者标识
     */
//    public JSONObject addTeamConsult(ConsultTeamDo ct, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        JSONObject users = new JSONObject();
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        if (ct.getType() == 2) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//
//            if (sf == null) {
//                // 不存在家庭签约
//                re.put("status", -1);
//                return re;
//            }
//            ct.setTeam(sf.getTeamCode());
//            // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//            //查找病人所在的团队
//            //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//            if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//                users.put(sf.getDoctorHealth(), 0);
//                ct.setDoctor(sf.getDoctorHealth());
//                if (StringUtils.isNotBlank(sf.getDoctor())) {
//                    if (users.isNull(sf.getDoctor())) {
//                        //全科需要判断是否开启健管师邀请后在接收消息
//                        int isGetMessage = 1;
//                        if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                            isGetMessage = 0;
//                        }
//                        users.put(sf.getDoctor(), isGetMessage);
//                    }
//                }
//            } else {
//                ct.setDoctor(sf.getDoctor());
//                users.put(sf.getDoctor(), 0);
//            }
//
//            // 设置家庭医生
//            ct.setAdminTeamId(sf.getAdminTeamId());
//        }
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        String sessionId = patient + "_" + ct.getTeam() + "_" + ct.getType();
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_MUC);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 添加续方咨询
     *
     * @param signTag      0为家签 1为非家签
     * @param hospital     机构CODE
     * @param hospitalName 机构名称
     * @param adminTeamId  机构名称
     */
//    public Integer addPrescriptionConsult(String jwCode, String patient, String agent, String doctorCode, ConsultTeam ct,
//                                          String reason, Integer type, String addressJson, int dispensaryType, Integer signTag,
//                                          String hospital, String hospitalName, Long adminTeamId, String systolic,
//                                          String diastolic, String bloodSugar, String bloodSugarType, String rateType) throws Exception {
//
//        synchronized (jwCode.intern()) {
//            String check = prescriptionInfoService.presCheckState(jwCode);
//            if ("0".equals(check)) {//存在未审核的续方
//                return -1;
//            }
//
//            Doctor doctor = doctorDao.findByCode(doctorCode);
//            if (signTag == null) {
//                signTag = 0;
//            }
//            //非家签 下线非家签可续方
////            if(1 == signTag){
////                ct.setAdminTeamId(adminTeamId);
////            }else{
//            //家签
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily == null) {
//                return -2;
//            }
//
//            ct.setAdminTeamId(signFamily.getAdminTeamId());
//            doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//            doctorCode = doctor.getCode();
//            adminTeamId = signFamily.getAdminTeamId();
////            }
//
//            // 查询患者信息
//            BasePatientDO  p = patientDao.findByCode(patient);
//
//            //1、获取基位处方详情(保存续方表、药品续方信息表、续方疾病类型表)
//            Prescription prescription = new Prescription();
//            //家签,非家签的标签
//            prescription.setSignTag(signTag);
//
//            prescription.setDiastolic(diastolic);
//            prescription.setSystolic(systolic);
//            prescription.setBloodSugar(bloodSugar);
//            prescription.setBloodSugarType(bloodSugarType);
//
//            prescription = savePrescription(prescription, jwCode, doctor, p, ct, reason, hospital, rateType);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("title", p.getName() + "申请续方");
//
//            //2、获取体征记录
//            List<PatientDevice> devices = patientDeviceDao.findByPatient(patient);
//            if (devices != null && devices.size() > 0) {
//                int count = messageDao.findTzMessage(patient);
//                jsonObject.put("tzMsg", "最近七天有" + count + "条异常记录");
//            } else {
//                jsonObject.put("tzMsg", "居民未绑定体征设备");
//            }
//            //3、获取上次续方时间:与平安的“智慧医保的审方系统”对接,判断居民上次续方时间,点击跳转上次续方记录。(此功能需与第三方系统对接,如果本次版本无法实现,则消息中不显示此条信息)
//            jsonObject.put("lastTime", "");
//
//            String content = jsonObject.toString();
//
//            //4、创建咨询
//            JSONObject users = new JSONObject();//咨询参与者
//            users.put(patient, 0);
//            users.put(doctorCode, 0);
//            if (patient.equals(agent)) {
//                agent = null;
//            }
//            //关联业务code
//            ct.setRelationCode(prescription.getCode());
//            //医生信息
//            ct.setDoctor(doctorCode);
//            ct.setDoctorName(doctor.getName());
//            // 设置患者信息
//            ct.setPatient(patient);
//            if (1 == type) {
//                ct.setSymptoms("高血压");
//            } else if (2 == type) {
//                ct.setSymptoms("糖尿病");
//            } else if (3 == type) {
//                ct.setSymptoms("高血压,糖尿病");
//            } else if (4 == type) {
//                ct.setSymptoms("其他疾病");
//            }
//
//            // 设置患者姓名
//            ct.setName(p.getName());
//            // 设置患者生日
//            ct.setBirthday(p.getBirthday());
//            //新增性别
//            ct.setSex(p.getSex());
//            // 设置患者头像
//            ct.setPhoto(p.getPhoto());
//            // 设置操作日期
//            ct.setCzrq(new Date());
//            ct.setDel("1");
//            ct.setStatus(0);
//            ct.setEvaluate(0);
//            // 医生未读数量为1
//            ct.setDoctorRead(1);
//            // 添加咨询记录
//            Consult consult = addConsult(ct.getPatient(), "申请续方", ct.getSymptoms(), ct.getImages(), ct.getType());
//            // 设置关联指导
//            consult.setGuidance(ct.getGuidance());
//            //关联业务code
//            consult.setRelationCode(prescription.getCode());
//            // 设置咨询标识
//            ct.setConsult(consult.getCode());
//
//            //推送给IM去创建议题,取得成员消息
//            JSONObject messages = ImUtill.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), agent);
//
//            //5、(im创建咨询) 续方咨询的sessionid为居民code+续方code+咨询类型
//            String sessionId = patient + "_" + consult.getCode() + "_" + ct.getType();
//            JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), p.getName(), users, messages, ImUtill.SESSION_TYPE_PRESCRIPTION);
//            if (obj == null) {
//                throw new ServiceException("IM消息发送异常!");
//            }
//            if (obj.getInt("status") == -1) {//im议题创建失败
//                throw new ServiceException(obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//            consultTeamDao.save(ct);
//            consultDao.save(consult);
//
//            //设置咨询code
//            prescription.setConsult(consult.getCode());
//            prescription.setViewSuifang(0);
//            prescription.setViewWenjuan(0);
//            prescription.setViewXufang(0);
//            prescription.setViewChufang(0);
//            prescription.setViewTizhen(0);
//            prescription.setViewJiancha(0);
//            prescriptionDao.save(prescription);
//
//            //6、记录咨询的医生详情
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(doctorCode);
//            consultTeamDoctorDao.save(cd);
//
//            //7、发送系统消息提示团队长有未审核的消息
//            addCheckMessage(prescription, sessionId, p);
//
//            //8、 保存医生咨询信息
//            // 添加咨询转发记录
//            // 添加医生咨询日志
//            addLogs(ct);
//
//            Patient patientObj = patientDao.findByCode(patient);
//
//            //9、添加续方的随访记录
//            Followup followup = new Followup();
//            followup.setFollowupDate(new Date());
//            followup.setFollowupPlanDate(new Date());
//            followup.setDoctorCode(doctorCode);
//            followup.setDoctorName(doctor.getName());
//            followup.setOrgCode(doctor.getHospital());
//            followup.setOrgName(doctor.getHospitalName());
//            followup.setPatientCode(patient);
//            followup.setPatientName(patientObj.getName());
//            followup.setIdcard(patientObj.getIdcard());
//
//            if (3 == type) {
//                followup.setFollowupClass("1,2");
//            } else {
//                followup.setFollowupClass(String.valueOf(type));
//            }
//
//            followup.setFollowupType("1");//门诊随访
//
//            followup.setDataFrom("2");//数据来源 1基卫 2APP
//            followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
//            followup.setCreateTime(new Date());
//            followup.setCreater(doctorCode);
//            followup.setAdminTeamCode(adminTeamId);
//            followup.setSignType(2);
//            //保存质询code
//            followup.setSignCode(patientService.getSignCodeByPatient(patient));
//            followup.setPrescriptionCode(prescription.getCode());
//            followupDao.save(followup);
//
//
//            PrescriptionExpressage expressage = expressageDao.findByPrescriptionPay(prescription.getCode());
//            if (expressage == null) {
//                expressage = new PrescriptionExpressage();
//                expressage.setCode(getCode());
//            }
//            expressage.setPrescriptionCode(prescription.getCode());
//            com.alibaba.fastjson.JSONObject addressInfo = JSON.parseObject(addressJson);
//
//            String phone = addressInfo.getString("phone");
//            expressage.setMobile(phone);//收货人手机号码
////        配药机构信息(签约机构)
//            expressage.setHospitalCode(prescription.getHospital());
//            expressage.setHospitalName(prescription.getHospitalName());
////            expressage.setHospitalAddress(signAddress);
//
//            //微信登录患者信息
//            String userName = p.getName();
//            String userProvince = p.getProvince();
//            String userProvinceName = p.getProvinceName();
//            String userCity = p.getCity();
//            String userCityName = p.getCityName();
//            String userTown = p.getTown();
//            String userTownName = p.getTownName();
//            String userStreet = p.getStreet();
//            String userStreetName = p.getStreetName();
//            String userAddress = p.getAddress();
//            switch (dispensaryType) {
//                case 1:
//                    prescription.setDispensaryType(1);//取药类型:1 自取 2快递配送 3健管师配送
//                    //自取保存居民信息
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 2:
//                    prescription.setDispensaryType(2);//取药类型:1 自取 2快递配送 3健管师配送
//                    //快递保存信息
//                    String name = addressInfo.getString("receiver");
//                    String proviceCode = addressInfo.getString("provinceCode");
//                    String proviceName = addressInfo.getString("provinceName");
//                    String cityCode = addressInfo.getString("cityCode");
//                    String cityName = addressInfo.getString("cityName");
//                    String townCode = addressInfo.getString("townCode");
//                    String townName = addressInfo.getString("townName");
//                    String streeCode = addressInfo.getString("streeCode");
//                    String streeName = addressInfo.getString("streeName");
//                    String address = addressInfo.getString("address");
//
//                    expressage.setName(name);//居民姓名
//                    expressage.setProvinceCode(proviceCode);//省代码
//                    expressage.setProvinceName(proviceName);//省名称
//                    expressage.setCityCode(cityCode);//市代码
//                    expressage.setCityName(cityName);//市名称
//                    expressage.setTownCode(townCode);//区code
//                    expressage.setTownName(townName);//区名称
//                    expressage.setStreetCode(streeCode);//街道code
//                    expressage.setStreetName(streeName);//街道名称
//                    expressage.setAddress(address);//居民详细地址
//
//                    expressage.setExpressageHospitalName("顺丰快递");
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 3:
//                    prescription.setDispensaryType(3);//取药类型:1 自取 2快递配送 3健管师配送
//                    //健管师配送
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    //居民选择的要送达的服务站
//                    String userOrgCode = addressInfo.getString("code");
//                    String userOrgName = addressInfo.getString("name");
//                    String userOrgAddress = addressInfo.getString("address");
//                    expressage.setPatientHospitalCode(userOrgCode);
//                    expressage.setPatientHospitalName(userOrgName);
//                    expressage.setPatientHospitalAddress(userOrgAddress);
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 4:
//                    prescription.setDispensaryType(4);//取药类型:1 自取 2快递配送 3健管师配送 4网格员派送
//
//                    expressage.setName(addressInfo.getString("receiver"));//居民姓名
//                    expressage.setProvinceCode(addressInfo.getString("provinceCode"));//省代码
//                    expressage.setProvinceName(addressInfo.getString("provinceName"));//省名称
//                    expressage.setCityCode(addressInfo.getString("cityCode"));//市代码
//                    expressage.setCityName(addressInfo.getString("cityName"));//市名称
//                    expressage.setTownCode(addressInfo.getString("townCode"));//区code
//                    expressage.setTownName(addressInfo.getString("townName"));//区名称
//                    expressage.setStreetCode(addressInfo.getString("streeCode"));//街道codestreetCode
//                    expressage.setStreetName(addressInfo.getString("streeName"));//街道名称
//                    expressage.setAddress(addressInfo.getString("address"));//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//            }
//
//            //保存物流信息
//            expressageDao.save(expressage);
//
//            return 1;
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addCheckMessage(Prescription prescription, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(prescription.getDoctor());
//        message.setSender(prescription.getPatient());
//        message.setCode(getCode());
//        message.setSenderName(prescription.getPatientName());
//        message.setTitle(prescription.getPatientName() + "申请续方");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(6);//续方咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(prescription.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(prescription.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 保存续方信息
     */
//    public Prescription savePrescription(Prescription prescription, String jwCode, Doctor doctor, Patient p, ConsultTeam ct, String reason, String hospital, String ratType) throws Exception {
//        //获取智业处方详细
//        String response = jwPrescriptionService.getRecipe(jwCode, p.getSsc(), null, hospital);
//        com.alibaba.fastjson.JSONObject jsonObject = presModeAdapter.modelToSinglePrescription(response);
//
//        //续方主表
//        prescription.setCode(getCode());
//        prescription.setParentCode(jwCode);
//        prescription.setHospitalName(doctor.getHospitalName());
//        prescription.setHospital(doctor.getHospital());
//        prescription.setAdminTeamId(ct.getAdminTeamId());
//        prescription.setCreateTime(new Date());
//        prescription.setDept(doctor.getDept());
//        prescription.setDeptName(doctor.getDeptName());
//        prescription.setDoctor(doctor.getCode());
//        prescription.setDoctorName(doctor.getName());
//        prescription.setJwCode(jwCode);
//        prescription.setPatient(p.getCode());
//        prescription.setPatientName(p.getName());
//        prescription.setSsc(p.getSsc());
//        prescription.setReason(reason);
//        prescription.setType(2);
//        prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.revieweding.getValue());
//        prescription.setConsult(ct.getConsult());
//        prescription.setJwPayStatus(0);//处方结算状态,0为未结算,1为结算成功,默认为0
//        prescription.setZyCancelState(0);//智业取消状态
//        //保存智业的医生信息
//        Map<String, Object> map = zyDictService.findJwDoctorByDoctor(doctor.getCode());
//        if (map != null) {
//            prescription.setJwDoctorCode(map.get("jw_doctor").toString());
//            prescription.setJwHospital(map.get("jw_doctor_hospital").toString());
//        }
//        //设置费别类型
//        prescription.setJwRateTypeCode(zyDictService.getRateType(ratType));
//        prescription.setPresCreateTime(DateUtil.stringToDate(jsonObject.getString("createTime"), "yyyy-MM-dd"));
//
//
//        //保存续方药品(处方)信息
//        com.alibaba.fastjson.JSONArray infos = jsonObject.getJSONArray("prescriptionInfo");
//        int day = 0;
//        if (infos != null && infos.size() > 0) {
//            day = infos.getJSONObject(0).getInteger("dayCount");
//        }
//        for (int i = 0; i < infos.size(); i++) {
//            com.alibaba.fastjson.JSONObject info = infos.getJSONObject(i);
//            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
//            prescriptionInfo.setPrescriptionCode(prescription.getCode());
//            prescriptionInfo.setCode(getCode());
//            prescriptionInfo.setDel(1);
//            prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
//            prescriptionInfo.setDrugCode(info.getString("drugCode"));//药品code
//            prescriptionInfo.setDrugName(info.getString("drugName"));//药品名称
//            prescriptionInfo.setDrugRate(info.getString("drugRate"));//吃药频率
//            prescriptionInfo.setDrugRateName(getZyCommonDictName(info.getString("drugRate")));
//            prescriptionInfo.setDrugFormat(info.getString("drugFormat"));//药品规格
//            prescriptionInfo.setNum(info.getInteger("num"));//药品数目
//            prescriptionInfo.setPrice(CommonUtil.doubleToInt(info.getDouble("price")));//药品单价
////            prescriptionInfo.setIsRefrigerate(0);//是否冷藏 1是 0否
//            prescriptionInfo.setJwSubCode(info.getString("jwSubCode"));//智业子处方号
//
//            prescriptionInfo.setDrugNumUnit(info.getString("drugNumUnit"));//数量单位编码
//            prescriptionInfo.setDrugNumUnitName(info.getString("drugNumUnitName"));//数量单位名称
//            prescriptionInfo.setCost(CommonUtil.doubleToInt(info.getDouble("cost")));//金额
//            prescriptionInfo.setCharge(CommonUtil.doubleToInt(info.getDouble("charge")));//自付
//            prescriptionInfo.setBindFlag(info.getString("bindFlag"));//成组标志, 0.非成组,1.成组
//            prescriptionInfo.setDayCount(info.getInteger("dayCount"));//用药天数
//            //设置最小用药天数
//            if (prescriptionInfo.getDayCount() != null && prescriptionInfo.getDayCount() < day) {
//                day = prescriptionInfo.getDayCount();
//            }
//            prescriptionInfo.setDrugUsage(info.getString("drugUsage"));//用药方法编码
//            prescriptionInfo.setUsageName(info.getString("usageName"));//用药方法名称
//            prescriptionInfo.setPhysicDose(info.getString("physicDose"));//用药剂量
//            prescriptionInfo.setPhysicDoseUnit(info.getString("physicDoseUnit"));//剂量单位编码
//            prescriptionInfo.setPhysicDoseUnitName(info.getString("physicDoseUnitName"));//剂量单位名称
//            prescriptionInfo.setPhysicInjectPlace(info.getString("physicInjectPlace"));//注射地点编码
//            prescriptionInfo.setPhysicInjectPlaceName(info.getString("physicInjectPlaceName"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTest(info.getString("physicSkinTest"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTestName(info.getString("physicSkinTestName"));//皮试类型名称
//            prescriptionInfo.setRemark(info.getString("Remark"));//备注
//            //需要特殊处理的字段
//            ZyIvPhysicDict physicDict = zyDictService.findByPhysicCode(prescriptionInfo.getDrugCode());
//            String subjectClass = info.getString("subjectClass");//科目类型
//            String physicAmount = info.getString("physicAmount");//用药总量
//            String physicAmountUnit = info.getString("physicAmountUnit");//总量单位编码
//            String physicAmountUnitName = info.getString("physicAmountUnitName");//总量单位名称
//            int isRefrigerate = 0;
//            if (physicDict != null) {
//                subjectClass = physicDict.getSubjectClass();
//                isRefrigerate = "2".equals(physicDict.getStorageConditions()) ? 1 : isRefrigerate;
//                physicAmount = null;
//                physicAmountUnit = physicDict.getPackUnit();
//                physicAmountUnitName = zyDictService.findByDictNameAndCode("IV_MEASURE_UNIT_DICT", physicAmountUnit);
//            }
//            prescriptionInfo.setPhysicAmount(physicAmount);
//            prescriptionInfo.setPhysicAmountUnit(physicAmountUnit);
//            prescriptionInfo.setPhysicAmountUnitName(physicAmountUnitName);
//            prescriptionInfo.setIsRefrigerate(isRefrigerate);
//            prescriptionInfo.setSubjectClass(subjectClass);//科目编码
//
//            prescriptionInfoDao.save(prescriptionInfo);
//        }
//        //设置最小用药天数
//        prescription.setMinDrugDay(day);
//        //保存续方记录
//        prescriptionDao.save(prescription);
//
//
//        //保存续方疾病类型
//        com.alibaba.fastjson.JSONArray jaDiagnosis = jsonObject.getJSONArray("prescriptionDt");
//        for (Iterator iterator = jaDiagnosis.iterator(); iterator.hasNext(); ) {
//            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) iterator.next();
//            PrescriptionDiagnosis diagnosis = new PrescriptionDiagnosis();
//            diagnosis.setCode(json.getString("code"));
//            diagnosis.setPrescriptionCode(prescription.getCode());
//            diagnosis.setCreateTime(new Date());
//            diagnosis.setName(json.getString("name"));
//            diagnosis.setHealthProblemName(json.getString("healthProblemName"));
//            diagnosis.setHealthProblem(json.getString("healthProblem"));
//            diagnosis.setUpdateTime(new Date());
//            prescriptionDiagnosisDao.save(diagnosis);
//        }
//
//        //保存审核信息
//        PrescriptionReviewed reviewed = new PrescriptionReviewed();
//        reviewed.setPrescriptionCode(prescription.getCode());
//        reviewed.setCode(getCode());
//        reviewed.setStatus(PrescriptionReviewed.PrescriptionReviewedStatus.reviewed_wait.getValue());
//        reviewed.setCreateTime(new Date());
//        reviewed.setDoctor(prescription.getDoctor());
//        reviewed.setDoctorName(prescription.getDoctorName());
//        reviewed.setHospital(prescription.getHospital());
//        reviewed.setHospitalName(prescription.getHospitalName());
//        prescriptionReviewedDao.save(reviewed);
//
//        //添加保存日志
//        prescriptionLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.create.getValue(), 1, 1);
//
//        return prescription;
//    }
    public String getZyCommonDictName(String code) {
        try {
            String sql = "SELECT t.name FROM zy_common_dict t WHERE t.code=? AND t.dict_name='IV_RECIPE_FREQUENCY_DICT'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{code});
            if (list != null && list.size() > 0) {
                return (String) (list.get(0).get("name"));
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendIM(String from, String to, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/pm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendGroupIM(String from, String groupCode, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/gm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("group", groupCode));
        params.add(new BasicNameValuePair("groupType", "1"));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 添加三师咨询日志
     */
//    private String addLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //先判断从健康指导转咨询是否存在指导。
//            JSONObject json = guidanceService.findById(ct.getGuidance());
//
//            if (json == null) {
//                //再判断从健康教育文章转咨询是否存在文章 20170602
//                HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//                if (article != null) {
//                    return verdictAddLogs(ct);
//                }
//                throw new ServiceException("健康指导不存在");
//            } else {
//                //  健康指导转咨询的指导内容
//                content += "医生" + (json.get("doctorName") != null ? json.get("doctorName").toString() : "")
//                        + "发出的指导:" + (json.getString("content") != null ? json.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLog infoLog = new ConsultTeamLog();
//        infoLog.setConsult(ct.getConsult());
//        if (content.length() > 2500) {
//            content = content.substring(0, 2500);
//        }
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLog imgLog = new ConsultTeamLog();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLog voiceLog = new ConsultTeamLog();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLog> iterable = consultTeamLogDao.save(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 添加三师咨询日志(增加咨询来源是否存在判断)
     */
//    private String verdictAddLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //再判断从健康教育文章转咨询是否存在文章 20170602
//            HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//            if (article == null) {
//                throw new RuntimeException("健康教育文章不存在!");
//            } else {
//                //  健康指导转咨询的指导内容
//                JSONObject jsonArticle = new JSONObject();
//
//                jsonArticle.put("doctorName", ct.getDoctorName() != null ? ct.getDoctorName() : "");
//                jsonArticle.put("content", article.getSummary() != null ? article.getSummary() : "");
//                jsonArticle.put("czrq", article.getCzrq() != null ? DateUtil.dateToStr(article.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM) : "");
//
//                content += "医生" + (jsonArticle.get("doctorName") != null ? jsonArticle.get("doctorName").toString() : "")
//                        + "发出的文章:" + (jsonArticle.getString("content") != null ? jsonArticle.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLogDo infoLog = new ConsultTeamLogDo();
//        infoLog.setConsult(ct.getConsult());
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLogDo imgLog = new ConsultTeamLogDo();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLogDo voiceLog = new ConsultTeamLogDo();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLogDo> iterable = consultTeamLogDao.saveAll(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 查询咨询列表
     *
     * @param patientCode 患者标志
     * @param status      咨询状态(0未结束,1已结束,-1 已取消)
     * @param pageSize    页数
     */
//    public Page<ConsultTeamDo> findByPatient(String patientCode, int status, long id, int pageSize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pageSize <= 0) {
//            pageSize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
//
//        Page<ConsultTeamDo> list = null;
//        switch (status) {
//            case 0:
//                // 未结束
//                if (id > 0) {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case 1:
//                // 已结束
//                if (id > 0) {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case -1:
//                // 已取消
//                if (id > 0) {
//                    list = consultTeamDao.findCancelBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findCancelBypatient(patientCode, pageRequest);
//                }
//                break;
//        }
//        return list;
//    }
    /**
     * 医生关闭三师咨询(续方咨询)
     *
     * @param consult 三师咨询标识
     */
//    public int finish(String consult, String endOperator, int endType) throws Exception {
//
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String name = "";
//        String returnJson = "";
//        //推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            name = p.getName();
//            returnJson = sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
//        } else {
//            Doctor d = doctorDao.findByCode(endOperator);
//            name = d.getName();
//            returnJson = sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
//        }
//
//        if (StringUtils.isEmpty(returnJson)) {
//            throw new ServiceException("send consult finished IM message failed");
//        } else {
//            JSONObject jo = new JSONObject(returnJson);            //设置消息ID
//            consultTeam.setEndMsgId(jo.getInt("startId") + "");
//            consultTeam.setEndOperator(endOperator);
//            consultTeam.setEndType(endType);
//        }
//
//        JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());
//
//        if (group != null) {
//            String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");
//
//            if (StringUtils.isEmpty(json)) {
//                throw new ServiceException("send consult finished IM message failed");
//            }
//        }
//
//        return consultTeamDao.updateStatusByConsult(consult);
//    }
    /**
     * 设置咨询已读
     */
    @Transactional
    public int readMessage(String consult) {
        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);
        consultTeam.setDoctorRead(0);
        return 1;
    }
    /**
     * 取消三师咨询
     */
//    public int cancel(String consult) {
//        return consultTeamDao.cancel(consult);
//    }
    public ConsultTeamDo findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }
    /**
     * 三师咨询转接医生
     *
     * @param from    转出医生标识
     * @param to      转入医生标识
     * @param consult 三师咨询标识
     */
//    public void transfer(String from, String to, String consult) {
//        // 检查是否存在
//        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
//            ConsultTeam ct = consultTeamDao.findByConsult(consult);
//            int count = consultTeamLogDao.countByConsult(consult);
//            // 设置未读消息数
//            ct.setDoctorRead(count);
//            consultTeamDao.save(ct);
//            // 查询医生信息
//            Doctor d = doctorDao.findByCode(from);
//            // 再保存
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult);
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setFrom(d.getCode());
//            cd.setFromName(d.getName());
//            cd.setTo(to);
//            consultTeamDoctorDao.save(cd);
//        }
//    }
    /**
     * 查询患者视频和三师咨询记录
     */
//    public Page<ConsultDo> findConsultRecordByPatientType(String patient, long id, int pagesize) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//        filters.put("type", new SearchFilter("type", Operator.LT, 3));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<Consult> spec = DynamicSpecifications.bySearchFilter(filters.values(), Consult.class);
//        return consultDao.findAll(spec, pageRequest);
//    }
    /**
     * 清空医生未读数量
     */
//    public void clearDoctorRead(String consult) {
//        consultTeamDao.clearDoctorRead(consult);
//    }
    /**
     * 查询医生的咨询统计
     */
//    public Map<String, Long> getAllCount(String doctorCode) {
//        Map<String, Long> result = new HashMap<>();
//
//        //根据医生code查询总咨询数
//        long allCount = consultTeamDoctorDao.getAllCountByDoctorCode(doctorCode);
//
//        //根据医生code查询今日咨询数
//        long todayCount = consultTeamDoctorDao.getTodayCountByDoctorCode(doctorCode);
//
//        result.put("all", allCount);
//        result.put("today", todayCount);
//
//        return result;
//    }
    /**
     * 查找未完成咨询
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient) {
//        return consultTeamDao.findUnfinishedConsult(patient);
//    }
//    public List<ConsultHelp> findUnfinishedByPatientAndSpecialist(String patient, String doctor) {
//        return consultHelpDao.findUnfinishedByPatientAndSpecialist(patient, doctor);
//    }
    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient, String doctor) {
//        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
//    }
    /**
     * 查询患者全部的咨询数目
     */
//    public Integer findByDoctorSize(String patientCode, String doctorCode) {
//
//        return consultDao.findByPatient(patientCode, doctorCode);
//    }
    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();
        for (int i = 0; i < consults.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(consults));
        paramList.addAll(Arrays.asList(consults));
        String sqlgp = "select DISTINCT consult,to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlgpm = "select DISTINCT to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.consult,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.to_doctor = b.qkdoctor_code group by a.consult ";
        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }
    public ConsultTeamLogDo oneLog(Long logId) {
        return consultTeamLogDao.findById(String.valueOf(logId)).orElse(null);
    }
//    public boolean isExistConsult(String uid, String doctor) {
//        int consultTeam = consultTeamDao.countByPatient(uid, 2, doctor);
//        return consultTeam > 0;
//    }
    /**
     * 进入咨询
     */
//    public int intoTopic(String consult, String patient, String agent) throws Exception {
//        ConsultTeamDo ct = consultTeamDao.findByConsult(consult);
//        if (ct.getStatus() != 0) {
//            return -1;
//        }
//
//        String content = "进入了咨询";
//        BasePatientDO  p = patientDao.findById(patient).orElse(null);
//        String intoUserName = p.getName();
//        if (patient.equals(agent)) {
//            content = intoUserName + content;
//        } else {
//            PatientFamilyMember familyMember = familyMemberDao.findByPatientAndFamilyMember(patient, agent);
//            Patient member = patientDao.findByCode(agent);
//            content = member.getName() + "(" + relations.get(familyMember.getFamilyRelation()) + ")" + content;
//        }
//
//        imUtil.sendIntoTopicIM(ct.getPatient(), ct.getPatient(), ct.getConsult(), content, agent, intoUserName);
//
//        return 0;
//    }
    /**
     * 根据健康管理师和患者 找到正在进行中的咨询
     */
//    public ConsultTeam getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patientCode, doctor, 2);
//        return consultTeam;
//    }
//    public List<String> getConsultListByPatientAndDoctor(String doctor) throws Exception {
//        List<String> list = consultTeamDao.findParientListByDoctor(doctor);
//        return list;
//    }
//    public void transfers(String uid, String doctor, String consult) {
//        String[] doctors = doctor.split(",");
//        for (int i = 0; i < doctors.length; i++) {
//            transfer(uid, doctors[i], consult);
//        }
//    }
//    public String produceConsultAdminTeamCode() {
//        StringBuffer sf = new StringBuffer();
//        StringBuffer sf1 = new StringBuffer();
//        long size = 0L;
//        //找出家庭签约中团队code是空的
//        List<ConsultTeamDo> consultTeams = consultTeamDao.findByTypeAndAdminTeamIdIsNull(2);
//        sf.append("家庭签约咨询中团队code是空的数据数:" + consultTeams.size());
//        for (ConsultTeam consultTeam : consultTeams) {
//            //得到签约中的全科医生的团队
//            SignFamily signfamily = signFamilyDao.findByjiatingPatient(consultTeam.getPatient());
//            if (signfamily != null) {
//                if (signfamily.getAdminTeamId() != null && signfamily.getAdminTeamId() > 0) {
//                    consultTeam.setAdminTeamId(signfamily.getAdminTeamId());
//                    size++;
//                }
//            } else {
//                sf1.append(",找不到医生所属的团队,家庭签约咨询的Id:" + consultTeam.getId());
//            }
//        }
//        sf.append(",填充团队的签约数据数:" + size);
//        sf.append(sf1);
//        return sf.toString();
//    }
    public void save(ConsultTeamDo consult) {
        consultTeamDao.save(consult);
    }
    public ConsultTeamDo findByConsultCode(String consultCode) {
        return consultTeamDao.findByConsult(consultCode);
    }
//    public List<ConsultTeamLogDo> getConsultLog(String consultCode) {
//        return consultTeamLogDao.getConsultLogByConsultLog(consultCode);
//    }
//    public void addForHelpTeamConsult(ConsultTeamDo ct, String uid, String oldConsultCode) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        BaseDoctorDO doctorTemp = doctorDao.findById(uid).orElse(null);
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        String returnJson = null;
//        JSONObject jo;
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        if (StringUtils.isEmpty(returnJson))
//            returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        else
//            sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        jo = new JSONObject(returnJson);
//        //设置消息ID
//        ct.setStartMsgId(jo.getInt("startId") + "");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public void sendForHelpMsg(ConsultTeam ct, String uid, String oldConsultCode) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        sendIM(ct.getPatient(), ct.getDoctor(), "6", "咨询问题:" + ct.getSymptoms());
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//    }
//    public List<ConsultTeamDo> hasUnfinished(String doctorCode, String uid) {
//        return consultTeamDao.findUnfinishedConsult(uid, doctorCode);
//    }
    /**
     * 判断两医生是否在同一团队内
     */
    public boolean isCommonTeam(String docCode1, String docCode2) {
        String sqlQuSum =
                "SELECT c.team_id FROM " +
                        "(SELECT a.* FROM wlyy_admin_team_member a where a.doctor_code='" + docCode1 + "' ) c " +
                        "LEFT JOIN " +
                        "(SELECT b.* FROM wlyy_admin_team_member b where b.doctor_code='" + docCode2 + "' ) d " +
                        "on c.team_id=d.team_id " +
                        "WHERE d.team_id IS NOT NULL";
        List ls = jdbcTemplate.queryForList(sqlQuSum);
        return ls != null && ls.size() > 0;
    }
    /**
     * 通过team获取医生code
     *
     * @param consult 关联的上一个咨询
     */
//    public List findByTeam(String consult) {
//        return consultTeamDao.findByTeamAndType(consult, 10);
//    }
    /**
     * 全科医生求助专科医生(同团队)
     *
     * @param isSend 是否转发患者咨询内容
     */
//    public void addSeekHelpTeam(ConsultTeamDo ct, String uid, String oldConsultCode, int isSend) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        JSONObject participants = new JSONObject();
//        participants.put(ct.getPatient(), 0);
//        participants.put(ct.getDoctor(), 0);
//        BaseDoctorDO doctor = doctorService.findDoctorByCode(uid);
//        JSONObject sessionJson = imUtill.createSession(participants, imUtill.SESSION_TYPE_P2P, doctor.getName() + "发起求助!", "");
//        if (sessionJson.getString("status").equals("-1")) {
//            throw new RuntimeException(sessionJson.getString("message"));
//        }
//        JSONObject session = sessionJson.getJSONObject("data");
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ct.setTeam(oldConsultCode);
//            ConsultTeamDo oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "居民问题:" + oldConsult.getSymptoms(), "1");
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                        }
//                    }
//                }
//            }
//            BaseDoctorDO doctorTemp = doctorDao.findById(ct.getDoctor()).orElse(null);
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctorTemp.getName());
//            imUtill.sendTopicIM(doctor.getId(), doctor.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//
//
//        ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "咨询问题:" + ct.getSymptoms(), "1");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                }
//            }
//        }
//    }
    /**
     * 全科医生求助专科医生(不同团队)
     */
//    public void addSeekHelpOtherTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        Doctor doctorTemp = doctorDao.findByCode(uid);
//        Doctor doctor = doctorDao.findByCode(ct.getDoctor());
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        if (StringUtils.isBlank(oldConsultCode)) {
//            JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, consult.getImages(), null);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put(ct.getPatient(), 0);
//            jsonObject.put(ct.getDoctor(), 0);
//            //设置消息ID
//            JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//            if (obj == null || obj.getInt("status") == -1) {
//                throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//        } else {
//            //转发咨询问题
//            Consult oldConsult = consultDao.findByCode(oldConsultCode);
//            ConsultTeam consultTeam = consultTeamDao.findByConsult(oldConsultCode);
//            ct.setTeam(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), "居民问题:" + oldConsult.getSymptoms(), oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//                ct.setStartMsgId(obj.get("start_msg_id").toString());
//                Thread.sleep(100);//消息发送顺序问题处理
//                ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "6", content, null);
//                if (StringUtils.isNotBlank(consult.getImages())) {
//                    String imgs[] = consult.getImages().split(",");
//                    for (String url : imgs)
//                        ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "2", url, null);
//                }
//            } else if (oldConsult != null && isSend == 0) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//            }
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + consultTeam.getTeam() + consult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctor.getName());
//            ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public int finishConsult(String consult, String endOperator, int endType) throws Exception {
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//        Consult cons = consultDao.findByCode(consult);
//
//        if (consultTeam.getStatus() == 1) {
//            return -1;
//        }
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String endName = "";
//        String endId = "";
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            endId = p.getCode();
//        } else {
//            if (endOperator.equals("admin")) {
//                endId = "system";
//                endName = "咨询超时未回复,系统自动";
//            } else {
//                Doctor d = doctorDao.findByCode(endOperator);
//                endId = d.getCode();
//                endName = d.getName();
//            }
//        }
//
//        JSONObject obj = ImUtill.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
//        if (obj == null) {
//            throw new ServiceException("IM消息结束异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(String.valueOf(obj.get("message")));
//        }
//
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (endName == null ? "" : endName));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = endName + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
////                first += "咨询已结束,请及时对咨询医生进行评价。";
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//            }
//        } else {
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                BasePatientDO  p = patientDao.findByCode(consultTeam.getPatient());
//                String name = p.getName();
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//
//                if (endOperator.equals("admin")) {
//                    templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxcspj");
//                }
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (name == null ? "" : name));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = name + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
//                /*if (endOperator.equals("admin")) {
//                    first += "咨询超时未回复,系统自动关闭,请及时对咨询医生进行评价。";
//                }else {
//                    first += "咨询已结束,请及时对咨询医生进行评价。";
//                }*/
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//
//            }
//        }
//
//        consultTeam.setEndMsgId(obj.getString("id"));
//        cons.setEndTime(new Date());
//        consultTeam.setEndTime(new Date());
//        consultTeam.setStatus(1);
//        consultDao.save(cons);
//        consultTeamDao.save(consultTeam);
//
//        //结束医生求组的记录
//        endConsultHelp(consult);
//        return 1;
//    }
    /**
     * 新增名医咨询
     * type  1患者 2医生
     * agent 代理人
     */
//    public JSONObject famousConsult(ConsultTeam ct, String uid, String type, String agent) throws Exception {
//        // 设置患者信息
//        agent = uid.equals(agent) ? null : agent;
//        ct.setPatient(uid);
//        String senderId = "";
//        String senderName = "";
//        if ("1".equals(type)) {
//            // 查询患者信息
//            Patient tempPatient = patientDao.findByCode(uid);
//            // 设置患者姓名
//            ct.setName(tempPatient.getName());
//            // 设置患者生日
//            ct.setBirthday(tempPatient.getBirthday());
//            //新增性别
//            ct.setSex(tempPatient.getSex());
//            // 设置患者头像
//            ct.setPhoto(tempPatient.getPhoto());
//
//            senderId = tempPatient.getCode();
//
//            senderName = tempPatient.getName();
//
//        } else if ("2".equals(type)) {
//            Doctor doctorTemp = doctorDao.findByCode(uid);
//            // 设置医生姓名
//            ct.setName(doctorTemp.getName());
//            // 设置医生生日
//            ct.setBirthday(doctorTemp.getBirthday());
//            //新增性别
//            ct.setSex(doctorTemp.getSex());
//            // 设置医生头像
//            ct.setPhoto(doctorTemp.getPhoto());
//
//            senderId = doctorTemp.getCode();
//
//            senderName = doctorTemp.getName();
//        }
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put(ct.getPatient(), 0);
//        jsonObject.put(ct.getDoctor(), 0);
//
//        JSONObject messages = ImUtill.getCreateTopicMessage(senderId, senderName, senderName + "发起咨询", content, ct.getImages(), agent);
//
//        JSONObject obj = ImUtill.createTopics(null, consult.getCode(), consult.getSymptoms(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//        if (obj == null) {
//            throw new ServiceException("im消息创建异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(obj.getString("message"));
//        }
//        //设置消息ID
//        ct.setStartMsgId(obj.getString("start_msg_id"));
//        JSONObject object = ImUtill.getTopic(ct.getConsult());
//        JSONArray array = new JSONArray(object.get("data").toString());
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//        if (array.length() == 0) {
//            //由于IM是异步操作,会话生成后,可能还未生成到数据库导致无法
//            //获取会话ID。休眠1秒后继续获取相应信息
//            // PS:可以通过前端请求两次去解决,由于离职,就不挖坑了,后来者可以改善、
//            Thread.sleep(1000);
//            object = ImUtill.getTopic(ct.getConsult());
//            array = new JSONArray(object.get("data").toString());
//        }
//        return array.getJSONObject(0);
//    }
//    @Override
//    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
//        super.sendMucMessageBySingnType(doctor, doctorName, patient, content, contentType, title);
//    }
    //过滤非本次咨询专科医生
//    public void removeSpecialist(JSONObject jsonObject, String uid, String consult) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        List<ConsultHelp> helpList = consultHelpDao.findConsult(consult);
//        Map<String, String> speMap = helpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        SignFamily signFamily = signFamilyDao.findByPatient(uid);
//        if (signFamily != null) {
//            speMap.put(signFamily.getDoctor(), "1");
//            if (StringUtils.isNotBlank(signFamily.getDoctorHealth())) {
//                speMap.put(signFamily.getDoctorHealth(), "1");
//            }
//        }
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                if (!speMap.containsKey(code)) {
//                    j.remove(i);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONObject jsonObject, String uid) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONArray j, String uid) {
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
    /**
     * 医生发送血糖血压快捷回复咨询
     */
//    public void addPrescriptionBloodStatusConsult(String prescriptionCode, String type, String followupid) throws Exception {
//
//        if ("1".equals(type)) {//血压
//            prescriptionFollowupContentService.importPatientBloodPressureToFollowup(prescriptionCode, followupid, true, "");
//        } else if ("2".equals(type)) {//血糖
//            prescriptionFollowupContentService.importPatientBloodSugarToFollowup(prescriptionCode, followupid, true, "");
//        }
//
//    }
    /**
     * 医生发送症状、体征及生活方式回复咨询
     */
//    public void addPrescriptionFollowupContentConsult(String prescriptionCode, String type, String followupid) throws Exception {
//        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//        org.json.JSONObject contentobj = new org.json.JSONObject();
//        //医生发送的消息
//        if ("1".equals(type)) {
//            contentobj.put("text", "请填写您近期身体异常症状问卷");
//        } else {
//            contentobj.put("text", "请填写您近期体征及生活方式调查问卷");
//        }
//        contentobj.put("doctorremind", "已向居民发送问卷填写请求,填写完成后您将收到消息提醒");
//        contentobj.put("patientremind", "填写完成并提交后,医生将可以查看您的问卷内容");
//        contentobj.put("msgType", type);
//        contentobj.put("isSendWxTemplate", true);//是否发送咨询回复的微信模板
//        //医生发送Im消息
//        ImUtil.sendTopicIM(prescription.getDoctor(), prescription.getDoctorName(), prescription.getConsult(), "17", contentobj.toString(), null);
//    }
    /**
     * 根据续方code获取咨询
     */
//    public ConsultTeamDo getConsultStatus(String prescriptionCode) {
//        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//        if (prescription != null) {
//            return consultTeamDao.findByConsult(prescription.getConsult());
//        }
//        return null;
//    }
    /**
     * pcim 使用
     */
    public com.alibaba.fastjson.JSONObject getSessionId(String patient) {
        com.alibaba.fastjson.JSONObject re = new com.alibaba.fastjson.JSONObject();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT a. STATUS, t.session_id FROM wlyy_consult_team a,  ");
        sql.append(imdb).append(".topics t WHERE a.patient = '").append(patient).append("' ");
        sql.append("AND a.consult = t.id AND a.type = 2 AND a.del = '1' ORDER BY a.id DESC LIMIT 1");
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql.toString());
        if (list != null && list.size() > 0) {
            re.put("status", list.get(0).get("STATUS"));
            re.put("sessionId", list.get(0).get("session_id"));
        } else {
            re.put("status", -1);
        }
        return re;
    }
    /**
     * 根据居民code获取剩余家庭咨询次数
     */
//    public JSONObject countRemainConsult(String patient) {
//        JSONObject json = new JSONObject();
//        try {
//            String consultTimes = systemDictDao.findByDictNameAndCode("CONSULT_TIMES", "1.4.2");
//            int count = Integer.parseInt(consultTimes);
//            json.put("count", count);
//            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
//            if (signFamily == null) {
//                return json;
//            }
//            int amount = consultTeamDao.countRemainConsult(patient, 2, signFamily.getBegin(), signFamily.getEnd());
//            amount = count - amount;
//            if (amount < 0) {
//                amount = 0;
//            }
//            json.put("amount", amount);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return json;
//    }
    /**
     * 返回json
     */
    public String getMessageById(String sessionType, String content, String title) {
        com.alibaba.fastjson.JSONObject re = new com.alibaba.fastjson.JSONObject();
        re.put("title", title);
        content = "'" + content.replace(",", "','") + "'";
        String tableName = "";
        switch (sessionType) {
            case "1":
            case "8":
                tableName = "muc_messages";
                break;
            case "2":
                tableName = "p2p_messages";
                break;
            default:
                tableName = "group_messages";
                break;
        }
        String sql = "select id, session_id, sender_id, sender_name, content_type, content, timestamp from " + imdb + "." +
                tableName + " where id in(" + content + ") order by timestamp desc ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray ja = new com.alibaba.fastjson.JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", map.get("id"));
            json.put("session_id", map.get("session_id"));
            json.put("sender_id", map.get("sender_id"));
            json.put("sender_name", map.get("sender_name"));
            json.put("content_type", map.get("content_type"));
            json.put("content", map.get("content"));
            json.put("timestamp", map.get("timestamp"));
            ja.add(json);
        }
        re.put("list", ja);
        return re.toString();
    }
    //判断居民家庭医生专科是否有共管关系
    public int getSpecialDoctorFamilyDoctorPatientCount(String patient, String special_doctor, String family_doctor) {
        String sql = "SELECT " +
                "count(a.id) FROM wlyy_specialist.wlyy_specialist_patient_relation a " +
                "JOIN wlyy.wlyy_sign_family b " +
                "ON a.patient=b.patient " +
                "AND b.`status`=1 " +
                "WHERE a.sign_status> 0 " +
                "AND a.`status`>=0 " +
                "AND a.doctor='" + special_doctor + "' " +
                "AND (b.doctor='" + family_doctor + "' or b.doctor_health='" + family_doctor + "')" +
                "AND a.patient='" + patient + "'";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
    /**
     * 添加在线复诊咨询
     */
//    public Integer addExaminationConsult(String visitNo, String patient, String agent, String doctorCode, ConsultTeam ct, String reason, String diagnosis) throws Exception {
//
//        synchronized (visitNo.intern()) {
//            Doctor doctor = doctorDao.findByCode(doctorCode);
//            doctorCode = doctor.getCode();
//            // 查询患者信息
//            BasePatientDO  p = patientDao.findByCode(patient);
//
//            Examination examination = new Examination();
//            //续方主表
//            examination.setCode(getCode());
//            examination.setVisitNo(visitNo);
////            prescription.setParentCode(jwCode);
//            examination.setHospitalName(doctor.getHospitalName());
//            examination.setHospital(doctor.getHospital());
////            prescription.setAdminTeamId(ct.getAdminTeamId());
//            examination.setCreateTime(new Date());
//            examination.setDept(doctor.getDept());
//            examination.setDeptName(doctor.getDeptName());
//            examination.setDoctor(doctor.getCode());
//            examination.setDoctorName(doctor.getName());
////            prescription.setJwCode(jwCode);
//            examination.setPatient(p.getCode());
//            examination.setPatientName(p.getName());
//            examination.setSsc(p.getSsc());
//            examination.setReason(reason);
////            prescription.setType(2);
//            examination.setStatus(PrescriptionLog.PrescriptionLogStatus.revieweding.getValue());
//            examination.setConsult(ct.getConsult());
//            examination.setJwPayStatus(0);//处方结算状态,0为未结算,1为结算成功,默认为0
//            //保存健康档案处方里的诊断名称
//            examination.setAdjustReason(diagnosis);
//            examination = examinationDao.save(examination);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("title", p.getName() + "申请在线复诊");
//
//            //2、获取体征记录
//            List<PatientDevice> devices = patientDeviceDao.findByPatient(patient);
//            if (devices != null && devices.size() > 0) {
//                int count = messageDao.findTzMessage(patient);
//                jsonObject.put("tzMsg", "最近七天有" + count + "条异常记录");
//            } else {
//                jsonObject.put("tzMsg", "居民未绑定体征设备");
//            }
//            //3、获取上次续方时间:与平安的“智慧医保的审方系统”对接,判断居民上次续方时间,点击跳转上次续方记录。(此功能需与第三方系统对接,如果本次版本无法实现,则消息中不显示此条信息)
//            jsonObject.put("lastTime", "");
//
//
//            String content = jsonObject.toString();
//
//            //4、创建咨询
//            JSONObject users = new JSONObject();//咨询参与者
//            users.put(patient, 0);
//            users.put(doctorCode, 0);
//            if (patient.equals(agent)) {
//                agent = null;
//            }
//            //关联业务code
//            ct.setRelationCode(examination.getCode());
//            //医生信息
//            ct.setDoctor(doctorCode);
//            ct.setDoctorName(doctor.getName());
//            // 设置患者信息
//            ct.setPatient(patient);
//            //主要症状
//            ct.setSymptoms(diagnosis);
//
//            // 设置患者姓名
//            ct.setName(p.getName());
//            // 设置患者生日
//            ct.setBirthday(p.getBirthday());
//            //新增性别
//            ct.setSex(p.getSex());
//            // 设置患者头像
//            ct.setPhoto(p.getPhoto());
//            // 设置操作日期
//            ct.setCzrq(new Date());
//            ct.setDel("1");
//            ct.setStatus(0);
//            ct.setEvaluate(0);
//            // 医生未读数量为1
//            ct.setDoctorRead(1);
//            // 添加咨询记录
//            Consult consult = addConsult(ct.getPatient(), "申请 在线复诊", ct.getSymptoms(), ct.getImages(), ct.getType());
//            // 设置关联指导
//            consult.setGuidance(ct.getGuidance());
//            //关联业务code
//            consult.setRelationCode(examination.getCode());
//            // 设置咨询标识
//            ct.setConsult(consult.getCode());
//
//            //推送给IM去创建议题,取得成员消息
//            JSONObject messages = ImUtill.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), agent);
//
//            //5、(im创建咨询) 续方咨询的sessionid为居民code+续方code+咨询类型
//            String sessionId = patient + "_" + consult.getCode() + "_" + ct.getType();
//            JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), p.getName(), users, messages, ImUtill.SESSION_TYPE_EXAMINATION);
//            if (obj == null) {
//                throw new ServiceException("IM消息发送异常!");
//            }
//            if (obj.getInt("status") == -1) {//im议题创建失败
//                throw new ServiceException(obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//            consultTeamDao.save(ct);
//            consultDao.save(consult);
//
//            //设置咨询code
//            examination.setConsult(consult.getCode());
//            examinationDao.save(examination);
//
//            //6、记录咨询的医生详情
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(doctorCode);
//            consultTeamDoctorDao.save(cd);
//
//            //7、发送系统消息提示团队长有未审核的消息
//            addExaminationCheckMessage(examination, sessionId, p);
//
//            //8、 保存医生咨询信息
//            // 添加咨询转发记录
//            // 添加医生咨询日志
//            addLogs(ct);
//
//            Patient patientObj = patientDao.findByCode(patient);
//
//            return 1;
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addExaminationCheckMessage(Examination examination, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(examination.getDoctor());
//        message.setSender(examination.getPatient());
//        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
//        message.setSenderName(examination.getPatientName());
//        message.setTitle(examination.getPatientName() + "申请在线复诊");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(31);//在线复诊咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(examination.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(examination.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 根据关联业务code查询咨询记录 wlyyDoorServiceOrderService.queryOneDetail(consult.getRelationCode());
     */
//    public ConsultTeamDo queryByRelationCode(String relationCode) {
//        if (StringUtils.isEmpty(relationCode)) {
//            return null;
//        }
//        ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(relationCode);
//        return consultTeam;
//    }
    /**
     * 根据咨询查关联业务记录
     */
//    public com.alibaba.fastjson.JSONObject queryByConsultCode(String code, Integer type) {
//        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
//        if (StringUtils.isEmpty(code) || null == type) {
//            return null;
//        }
//        Consult consult = consultDao.queryByCodeAndType(code, type);
//
//        if (null == consult) {
//            result.put("data", "");
//            return result;
//        }
//
//        if (type == 11) {
//            WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(consult.getRelationCode());
//            com.alibaba.fastjson.JSONObject patientInfo = wlyyDoorServiceOrderService.queryOrderCardInfo(orderDO);
//            result.put("data", patientInfo);
//        }
//
//        result.putIfAbsent("data", consult);
//        return result;
//    }
//    public JSONObject updateIMMsg(String sessionId, String sessionType, String msgId, String content) {
//        JSONObject result = new JSONObject();
//        if (StringUtils.isEmpty(sessionId) || StringUtils.isEmpty(sessionType) || StringUtils.isEmpty(msgId) || StringUtils.isEmpty(content)) {
//            result.put("data", "参数【sessionId,sessionType,msgId,content】不可为空!");
//            result.put("status", -1);
//            return result;
//        }
//        JSONObject contentJsonObj = null;
//        try {
//            contentJsonObj = new JSONObject(content);
//        } catch (Exception e) {
//            result.put("status", -1);
//            result.put("data", "【content】必须是json格式:" + e.getMessage());
//            return result;
//        }
//        String response = ImUtill.updateMessage(sessionId, sessionType, msgId, content);
//        return new JSONObject(response);
//    }
//    public JSONObject addTeamSpecialConsult(ConsultTeam ct, String patientCode, String agent, String specialDoctorCode, String doctorCode) throws Exception {
//        JSONObject re = new JSONObject();
////        if (exist(patientCode, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
////            re.put("status", -3);
////            return re;
////        }
//
//        JSONObject users = new JSONObject();
//
//        if (patientCode.equals(agent)) {
//            agent = null;
//        }
//
//        users.put(doctorCode, 0);
//        users.put(specialDoctorCode, 0);
//
//        // 设置患者信息
//        ct.setPatient(patientCode);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patientCode);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        ct.setDoctor(doctorCode);
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patientCode, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), agent);
//        users.put(patientCode, 0);
//        JSONObject obj = ImUtill.createTopics(patientCode + "_" + doctorCode + "_" + specialDoctorCode + "_" + ct.getType(), consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patientCode.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//    }
//    public JSONObject getConsultDoctorForConsulting(String patientCode) {
//        JSONObject result = new JSONObject();
//        String sql = "SELECT DISTINCT p.patient, p.name AS patient_name, p.`team_code`,te.`name` AS team_name, d.`code` as special_code, d.`name` as special_name, d.dept_name,d.hospital_name \n" +
//                "FROM wlyy_specialist.wlyy_patient_rehabilitation_plan p, wlyy_doctor d ,wlyy_admin_team te\n" +
//                "WHERE p.patient = '" + patientCode + "' AND d.`code`= p.create_user and te.id = p.team_code AND te.available=1 GROUP BY p.patient, p.create_user,p.team_code";
//        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        result.put("ConsultTeamList", list);
//        //家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patientCode);
//        if (StringUtils.isNoneBlank(sf.getDoctor())) {
//            result.put("doctor", sf.getDoctor());
//            result.put("doctorName", sf.getDoctorName());
//        }
//        if (StringUtils.isNoneBlank(sf.getDoctorHealth())) {
//            result.put("doctorHealth", sf.getDoctorHealth());
//            result.put("doctorHealthName", sf.getDoctorHealthName());
//        }
//        return result;
//    }
}

+ 162 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoctorDoorServiceAuditController.java

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

+ 1347 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java

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

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 324 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java


+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationDao.java

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

+ 28 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationTempDao.java

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

+ 30 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceApplicationDao.java

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

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceConfigureDao.java

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

+ 38 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceOrderDao.java

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

+ 29 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceVoucherDao.java

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

+ 26 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCancelLogDao.java

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

+ 28 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDao.java

@ -0,0 +1,28 @@
package com.yihu.jw.hospital.module.door.dao;
import com.yihu.jw.entity.door.WlyyDoorCommentDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 
 * 服务工单评价 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * Administrator 	1.0  		2019年03月20日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface WlyyDoorCommentDao
        extends PagingAndSortingRepository<WlyyDoorCommentDO, Integer>,
        JpaSpecificationExecutor<WlyyDoorCommentDO> {
    @Query("select t from WlyyDoorCommentDO t where t.patient = ?1 and t.orderId = ?2 ")
    WlyyDoorCommentDO selectCommentDoctor(String patient, String orderId);
}

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDoctorDao.java

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

+ 33 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorConclusionDao.java

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

+ 40 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorDao.java

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

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorFeeDictDao.java

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

+ 34 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorStatusDao.java

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

+ 41 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorFeeDetailDao.java

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

+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorOrderItemDao.java

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

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPatientConfirmLogDao.java

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

+ 30 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDao.java

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

+ 19 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDetailDao.java

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

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDrugDao.java

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

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorProcessLogDao.java

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

+ 51 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorServiceOrderDao.java

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

+ 21 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorTransRecordDao.java

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

+ 165 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoctorRegistrationTempService.java

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

+ 0 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java


Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott