소스 검색

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

LAPTOP-KB9HII50\70708 1 년 전
부모
커밋
76bb2c3cec
100개의 변경된 파일13601개의 추가작업 그리고 66개의 파일을 삭제
  1. 9 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  2. 116 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/service/SystemMessageService.java
  3. 36 1
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java
  4. 1 1
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/YkyyPrescriptionService.java
  5. 43 23
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/EntranceService.java
  6. 118 0
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/vo/GuahaoDoctor.java
  7. 13 0
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java
  8. 20 0
      business/base-service/src/main/java/com/yihu/jw/message/dao/MessageNoticeSettingDao.java
  9. 18 0
      business/base-service/src/main/java/com/yihu/jw/message/dao/SpecialistDynamicMessagesDao.java
  10. 22 0
      business/base-service/src/main/java/com/yihu/jw/message/dao/WlyyDynamicMessagesDao.java
  11. 113 0
      business/base-service/src/main/java/com/yihu/jw/message/service/MessageService.java
  12. 4 1
      business/base-service/src/main/java/com/yihu/jw/order/dao/ConsultTeamOrderDao.java
  13. 4 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/BasePatientDao.java
  14. 18 0
      business/base-service/src/main/java/com/yihu/jw/patient/dao/PatientEventDao.java
  15. 2 0
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultDao.java
  16. 7 0
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  17. 67 32
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  18. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultDo.java
  19. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java
  20. 20 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java
  21. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorOrderItemDO.java
  22. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceApplicationDo.java
  23. 15 7
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java
  24. 19 0
      common/common-entity/src/main/java/com/yihu/jw/entity/followup/Followup.java
  25. 52 0
      common/common-entity/src/main/java/com/yihu/jw/entity/followup/FollowupClassDrugs.java
  26. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/article/KnowledgeArticleDictDO.java
  27. 57 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/BaseSignDO.java
  28. 452 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/PatientReservation.java
  29. 49 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/ReservationHospitalDept.java
  30. 178 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/MessageNoticeSetting.java
  31. 191 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SpecialistDynamicMessages.java
  32. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/message/WlyyDynamicMessages.java
  33. 135 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/PatientDischargeDO.java
  34. 102 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientDiseaseServer.java
  35. 2 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientMedicalRecordsDO.java
  36. 342 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPatientInfoDO.java
  37. 48 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPlanTemplateDO.java
  38. 67 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/TemplateJson.java
  39. 107 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatPushLog.java
  40. 70 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTag.java
  41. 107 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTagLog.java
  42. 91 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplate.java
  43. 147 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateConfig.java
  44. 25 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTemplateData.java
  45. 71 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WeixinTemplate.java
  46. 53 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxAccessTokenLog.java
  47. 23 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WxOpenidTemp.java
  48. 8 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/specialist/SpecialistMapping.java
  49. 13 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyHisSettleVO.java
  50. 48 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/endpoint/EnvelopRestEndpoint.java
  51. 340 0
      common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java
  52. 71 0
      common/common-util/src/main/java/com/yihu/jw/util/common/DataUtils.java
  53. 148 0
      common/common-util/src/main/java/com/yihu/jw/util/common/ISqlUtils.java
  54. 15 0
      common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java
  55. 14 0
      common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java
  56. 1 1
      svr/svr-internet-hospital/src/main/resources/bootstrap.yml
  57. 385 0
      svr/svr-visit-behind/pom.xml
  58. 23 0
      svr/svr-visit-behind/src/main/java/com/yihu/SvrVisitBehind.java
  59. 169 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/async/AsynService.java
  60. 27 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/BeanConfig.java
  61. 49 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/MvcConfig.java
  62. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SpringSecurityAuditorAware.java
  63. 44 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SwaggerDocs.java
  64. 146 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/GcTokenController.java
  65. 98 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/BaseResultModel.java
  66. 33 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/GcClientDetailsModel.java
  67. 51 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/GcTokenModel.java
  68. 39 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/ResultOneModel.java
  69. 38 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/CrosXssFilter.java
  70. 164 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/GateWayInterceptor.java
  71. 120 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/XssHttpServletRequestWrapper.java
  72. 1856 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java
  73. 381 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java
  74. 3484 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  75. 186 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoctorDoorServiceAuditController.java
  76. 1420 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  77. 126 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/PatientDoorServiceApplicationController.java
  78. 340 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java
  79. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationDao.java
  80. 28 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationTempDao.java
  81. 30 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceApplicationDao.java
  82. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceConfigureDao.java
  83. 38 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceOrderDao.java
  84. 29 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoorServiceVoucherDao.java
  85. 26 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCancelLogDao.java
  86. 28 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDao.java
  87. 25 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDoctorDao.java
  88. 33 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorConclusionDao.java
  89. 40 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorDao.java
  90. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorFeeDictDao.java
  91. 34 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorDoctorStatusDao.java
  92. 41 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorFeeDetailDao.java
  93. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorOrderItemDao.java
  94. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPatientConfirmLogDao.java
  95. 30 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDao.java
  96. 19 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDetailDao.java
  97. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorPrescriptionDrugDao.java
  98. 21 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorProcessLogDao.java
  99. 51 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorServiceOrderDao.java
  100. 0 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorTransRecordDao.java

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

@ -80,4 +80,13 @@ public interface SystemMessageDao extends PagingAndSortingRepository<SystemMessa
    @Modifying
    @Query("update SystemMessageDO s set s.del=0 where s.type=?1 and s.relationCode=?2 ")
    void delMessageByTypeAndRelationCode(String type,String relationCode);
    @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();
    @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);
}

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

@ -5,10 +5,13 @@ 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.hospital.message.MessageNoticeSetting;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.message.dao.MessageNoticeSettingDao;
import com.yihu.jw.message.dao.SpecialistDynamicMessagesDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.StringUtil;
@ -19,6 +22,7 @@ import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
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;
@ -50,6 +54,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
    SpecialistDynamicMessagesDao specialistDynamicMessagesDao;
    /**
     * 新增线上就诊消息
@ -187,5 +200,108 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
        List<Map<String,Object>> listfront = hi
    }*/
    /**
     * 获取消息提示开关
     *
     * @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;
    }
}

+ 36 - 1
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -9207,6 +9207,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        if (StringUtils.isNotBlank(one.getDoctor())&&(one.getStatus().equalsIgnoreCase("1")||one.getStatus().equalsIgnoreCase("2"))) {
            throw new RuntimeException("已有医生接诊");
        }
        String doctor = one.getDoctor();
        one.setDoctor(outpatientDO.getDoctor());
        one.setDoctorName(outpatientDO.getDoctorName());
        one.setRegisterDate(outpatientDO.getRegisterDate());
@ -9215,7 +9216,40 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        one.setType(outpatientDO.getType());
        one.setOutpatientType(outpatientDO.getOutpatientType());
        WlyyOutpatientDO outpatient = outpatientDao.save(one);
        if (!outpatientDO.getDoctor().equalsIgnoreCase(doctor)){
            String title="";
            String msg="";
            String date= "";
            String sex = "";
            String age = "";
            if (one!=null){
                sex= IdCardUtil.getSexForIdcard(one.getIdcard());
                age = IdCardUtil.getAgeForIdcard(one.getIdcard())+"";
            }
            String name = one.getPatientName();
            String baseUrl = findDomainUrlInDict();
            if (one.getType().equalsIgnoreCase("1")){
                title = "图文复诊";
                msg = name+"("+sex+" "+age+"岁)向您发起了图文复诊已更换其他医生接诊,请您知悉。";
            }else if (one.getType().equalsIgnoreCase("2")){
                title = "视频复诊";
                date = DateUtil.dateToStrLong(one.getRegisterDate());
                msg = name+"("+sex+" "+age+"岁)预约了"+date+"的视频复诊已更换其他医生接诊,请您知悉。";
            }
            if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
                String url=baseUrl+"/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+one.getDescription()+"&type=3&id="+one.getId();
                enterpriseService.sendTWMesByDoctor("zsyy",one.getDoctor(),title,msg,url);
            }else if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
                String url=baseUrl+"/ims-app-web/#/onlineChat/detail?_rs_title="+one.getDescription()+"&type=3&id="+one.getId();
                enterpriseService.sendTWMesByDoctor("xm_ykyy_wx",one.getDoctor(),title,msg,url);
            }else if (wechatId.equalsIgnoreCase("xm_xzzx_wx")){
                String url="https://ih.xmheart.com/hlwyy/ims-app-web/#/onlineChat/detail?_rs_title="+one.getDescription()+"&type=3&id="+one.getId();
                enterpriseService.sendTWMesByDoctor("xm_xzzx_wx",one.getDoctor(),title,msg,url);
            }else if (wechatId.equalsIgnoreCase("xm_hcyy_wx")){
                String url="https://hlwyy.xmhcyy.com/hcyy/ims-app-web/#/onlineChat/detail?_rs_title="+one.getDescription()+"&type=3&id="+one.getId();
                enterpriseService.sendTWMesByDoctor("xm_hcyy_wx",one.getDoctor(),title,msg,url);
            }
        }
        WlyyPatientRegisterTimeDO registerTimeDO = null;
        try {
@ -15330,6 +15364,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            wlyyHisSettleVO.setJjzfe0(ylzMedicalRelationDO.getMedicalPrice());
            wlyyHisSettleVO.setGwybz0(ylzMedicalRelationDO.getGwyPay());
            wlyyHisSettleVO.setFybfy0(ylzMedicalRelationDO.getPersonCash());
            wlyyHisSettleVO.setQtjjzf(ylzMedicalRelationDO.getOtherPay());
            wlyyHisSettleVO.setCfdxje("0");
            wlyyHisSettleVO.setBjjjzf("0");
            wlyyHisSettleVO.setSybxzf(ylzMedicalRelationDO.getSbjjPay());

+ 1 - 1
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/YkyyPrescriptionService.java

@ -1504,7 +1504,7 @@ public class YkyyPrescriptionService extends BaseJpaService<WlyyPrescriptionDO,
            salertaxnum = "110000999999003";
            dzfpAppKey="23760028";
            dzfpAppSecret="45591CA66F8D4589";
            dzfpToken="44d50530356519e60973b70cwqn46acs";
            dzfpToken="44d50530356519e60973b70ki9ihenos";
            salertaxnum="110000999999003";
            saleraddress="福建省厦门市厦禾路336号";
            saleraccount="建行厦门市厦禾支行 35101561001052502781";

+ 43 - 23
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/EntranceService.java

@ -1791,32 +1791,48 @@ public class EntranceService {
            if (object.getString("retCodeOut").equalsIgnoreCase("00")){
                logger.info("第一次调用his退费接口结束");
                //调用易联众预缴金退款接口
                String refund = ylzPayService.refund(operatorId, operatorName, cardType, accountType, cardNo, idNo, amount, outChargeNo, userName, "1", traceSerial, outRefundNo,cardNo);
                BusinessOrderRefundDO businessOrderRefundDO = new BusinessOrderRefundDO();
                businessOrderRefundDO.setOrderNo(businessOrderDO.getOrderNo());
                businessOrderRefundDO.setOutRefundNo(outRefundNo);
                businessOrderRefundDO.setStatus(1);
                businessOrderRefundDO.setCreateTime(new Date());
                businessOrderRefundDO.setUpdateTime(new Date());
                businessOrderRefundDO.setPatient(businessOrderDO.getPatient());
                businessOrderRefundDO.setPatientName(businessOrderDO.getPatientName());
                businessOrderRefundDO = orderRefundDao.save(businessOrderRefundDO);
                JSONObject jsonObject = JSONObject.parseObject(refund);
                //获取调用易联众退费接口交易状态
                String respCode = jsonObject.getString("respCode");
                if (respCode.equals("000000")){
                    businessOrderRefundDO.setRefundTime(new Date());
                    businessOrderRefundDO.setStatus(2);
                try{
                    String refund = ylzPayService.refund(operatorId, operatorName, cardType, accountType, cardNo, idNo, amount, outChargeNo, userName, "1", traceSerial, outRefundNo,cardNo);
                    BusinessOrderRefundDO businessOrderRefundDO = new BusinessOrderRefundDO();
                    businessOrderRefundDO.setOrderNo(businessOrderDO.getOrderNo());
                    businessOrderRefundDO.setOutRefundNo(outRefundNo);
                    businessOrderRefundDO.setStatus(1);
                    businessOrderRefundDO.setCreateTime(new Date());
                    businessOrderRefundDO.setUpdateTime(new Date());
                    businessOrderRefundDO.setPatient(businessOrderDO.getPatient());
                    businessOrderRefundDO.setPatientName(businessOrderDO.getPatientName());
                    businessOrderRefundDO = orderRefundDao.save(businessOrderRefundDO);
                    JSONObject jsonObject = JSONObject.parseObject(refund);
                    //获取调用易联众退费接口交易状态
                    String respCode = jsonObject.getString("respCode");
                    if (respCode.equals("000000")){
                        businessOrderRefundDO.setRefundTime(new Date());
                        businessOrderRefundDO.setStatus(2);
                        orderRefundDao.save(businessOrderRefundDO);
                        businessOrderDO.setStatus(9);
                        businessOrderDao.save(businessOrderDO);
                        tradeState = "succ";
                    }else {
                        tradeState = "fail";
                    }
                    logger.info("第二次调用his退费接口开始");
                    resp = BS15051(operatorId, operatorName, cardType, cardNo, accountType, idNo, withdrawMode, depositType, ServiceType, amount, outRefundNo, outChargeNo, origTraceNo, traceSerial, paydate, notes, tradeState, failReason, failTime, extra, demoFlag);
                    logger.info("第二次调用his退费接口结束");
                }catch (Exception e){
                    BusinessOrderRefundDO businessOrderRefundDO = new BusinessOrderRefundDO();
                    businessOrderRefundDO.setOrderNo(businessOrderDO.getOrderNo());
                    businessOrderRefundDO.setOutRefundNo(outRefundNo);
                    businessOrderRefundDO.setStatus(1);
                    businessOrderRefundDO.setCreateTime(new Date());
                    businessOrderRefundDO.setUpdateTime(new Date());
                    businessOrderRefundDO.setPatient(businessOrderDO.getPatient());
                    businessOrderRefundDO.setPatientName(businessOrderDO.getPatientName());
                    businessOrderRefundDO = orderRefundDao.save(businessOrderRefundDO);
                    orderRefundDao.save(businessOrderRefundDO);
                    businessOrderDO.setStatus(9);
                    businessOrderDO.setStatus(10);
                    businessOrderDao.save(businessOrderDO);
                    tradeState = "succ";
                }else {
                    tradeState = "fail";
                }
                logger.info("第二次调用his退费接口开始");
                resp = BS15051(operatorId, operatorName, cardType, cardNo, accountType, idNo, withdrawMode, depositType, ServiceType, amount, outRefundNo, outChargeNo, origTraceNo, traceSerial, paydate, notes, tradeState, failReason, failTime, extra, demoFlag);
                logger.info("第二次调用his退费接口结束");
            }
        }
        return resp;
@ -3417,6 +3433,10 @@ public class EntranceService {
                sbs.append("<psn_no>"+hisSettleVO.getPsnNo()+"</psn_no>");
            }
            if (StringUtils.isNotEmpty(hisSettleVO.getQtjjzf())) {
                sbs.append("<qtjjzf>"+hisSettleVO.getQtjjzf()+"</qtjjzf>");
            }
            if (StringUtils.isNotEmpty(hisSettleVO.getSetlTime())){
                sbs.append("<setl_time>"+hisSettleVO.getSetlTime()+"</setl_time>");
            }

+ 118 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/vo/GuahaoDoctor.java

@ -0,0 +1,118 @@
package com.yihu.jw.hospital.prescription.vo;
/**
 * Created by hzp on 2016/8/13.
 * 挂号服务医生信息
 */
public class GuahaoDoctor {
    private String id;//医生编码
    private String name;//医生姓名
    private String sex;//医生性别
    private String title;//医生职称
    private String edu;//医生学历
    private String introduce;//医生简介
    private String photo;//医生头像
    private String fee;//医生挂号费
    private String hosDeptId;//医生科室编码
    private String hosDeptName;//医生科室名称
    private String hospitalId;//医生医院编码
    private String hospitalName;//医生医院名称
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getEdu() {
        return edu;
    }
    public void setEdu(String edu) {
        this.edu = edu;
    }
    public String getIntroduce() {
        return introduce;
    }
    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    public String getFee() {
        return fee;
    }
    public void setFee(String fee) {
        this.fee = fee;
    }
    public String getHosDeptId() {
        return hosDeptId;
    }
    public void setHosDeptId(String hosDeptId) {
        this.hosDeptId = hosDeptId;
    }
    public String getHosDeptName() {
        return hosDeptName;
    }
    public void setHosDeptName(String hosDeptName) {
        this.hosDeptName = hosDeptName;
    }
    public String getHospitalId() {
        return hospitalId;
    }
    public void setHospitalId(String hospitalId) {
        this.hospitalId = hospitalId;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
}

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

@ -9,4 +9,17 @@ import org.springframework.data.repository.PagingAndSortingRepository;
public interface WlyySignFamilyDao extends PagingAndSortingRepository<SignFamily, Integer>, JpaSpecificationExecutor<SignFamily> {
    @Query("select count(*) from SignFamily  t where t.doctor=?1 and t.status=1")
    Integer getCountByDoctorCode(String doctor);
    @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.patient = ?1 and a.type =2 and a.status >= 1")
    SignFamily findByjiatingPatient(String code);
    @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.patient = ?1 and a.type =2 and a.status >= 0")
    SignFamily findByPatient(String patient);
}

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

@ -0,0 +1,20 @@
package com.yihu.jw.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/message/dao/SpecialistDynamicMessagesDao.java

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

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

@ -0,0 +1,22 @@
package com.yihu.jw.message.dao;
import com.yihu.jw.entity.message.WlyyDynamicMessages;
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;
/***
 * @ClassName: WlyyDynamicMessagesDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2020/9/10 9:35
 */
public interface WlyyDynamicMessagesDao extends PagingAndSortingRepository<WlyyDynamicMessages, Long>, JpaSpecificationExecutor<WlyyDynamicMessages> {
    @Query("select m from WlyyDynamicMessages m where m.createTime>?1 and m.createTime<?2 group by m.name,m.code,m.createTime order by m.createTime desc ")
    Page<WlyyDynamicMessages> findByTime(String createTime, String endTime, Pageable pageRequest);
    @Query("select count(1) from WlyyDynamicMessages m where m.createTime>?1 and m.createTime<?2")
    Integer findCountsByTime(String createTime, String endTime);
}

+ 113 - 0
business/base-service/src/main/java/com/yihu/jw/message/service/MessageService.java

@ -1,13 +1,17 @@
package com.yihu.jw.message.service;
import com.yihu.jw.entity.base.message.BaseMessageDO;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.dao.MessageNoticeSettingDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@ -26,6 +30,13 @@ public class MessageService extends BaseJpaService<BaseMessageDO, MessageDao> {
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    MessageNoticeSettingDao messageNoticeSettingDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String MESSAGE_NOTICESETTING = "wlyy:message:setting:";
    /**
@ -213,4 +224,106 @@ public class MessageService extends BaseJpaService<BaseMessageDO, MessageDao> {
        return messageDao.getAllByPatient(receiver,msgTypeCode,platform,pageRequest);
    }
    /**
     * 获取消息提示开关
     * @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;
    }
}

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

@ -14,7 +14,10 @@ import java.util.Date;
public interface ConsultTeamOrderDao extends PagingAndSortingRepository<ConsultTeamDo, String>, JpaSpecificationExecutor<ConsultTeamDo> {
	// 根據consult查詢咨询记录
	ConsultTeamDo findByConsult(String consult);
	
	ConsultTeamDo queryByRelationCode(String relationCode);
//	// 关闭咨询
//	@Modifying
//	@Query("update ConsultTeam a set a.status = 1 where a.consult = ?1")

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

@ -14,6 +14,10 @@ import java.util.Map;
 */
public interface BasePatientDao extends PagingAndSortingRepository<BasePatientDO, String>, JpaSpecificationExecutor<BasePatientDO> {
    @Query(value = "select p.* from base_patient p,patient_medicare_card c where c.code=?1 and c.patient_code=p.id and c.type='A_01' limit 1",nativeQuery = true)
    BasePatientDO findBySsc(String ssc);
    BasePatientDO findById(String id);
    BasePatientDO findByIdcardAndDel(String Idcard,String del);

+ 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;
}

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

@ -13,6 +13,8 @@ import org.springframework.data.repository.PagingAndSortingRepository;
 * @author huangwenjie
 */
public interface ConsultDao extends PagingAndSortingRepository<ConsultDo, String>, JpaSpecificationExecutor<ConsultDo> {
	ConsultDo findByCode(String code);
	
	@Query("from ConsultDo a where a.relationCode = ?1")
	ConsultDo findByRelationCode(String outpatientid);

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

@ -189,6 +189,13 @@ public class ImService {
    @Value("${wechat.flag}")
    private boolean flag;
    public static String im_host;
    @Value("${im.im_list_get}")
    public void setIm_host(String im_host) {
        ImService.im_host = im_host;
    }
    /**
     * 查询患者所有的咨询记录

+ 67 - 32
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;
@ -22,7 +23,7 @@ import java.util.List;
public class ImUtil {
	
	@Autowired
	private HttpClientUtil HttpClientUtil;
	private HttpClientUtil httpClientUtil;
	
	@Value("${im.im_list_get}")
	private String im_host;
@ -140,7 +141,7 @@ public class ImUtil {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
@ -149,7 +150,7 @@ public class ImUtil {
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("data", jsonValue);
		HttpClientUtil.putBody(imAddr, params);
		httpClientUtil.putBody(imAddr, params);
	}
	
	/**
@ -177,7 +178,7 @@ public class ImUtil {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
@ -202,7 +203,7 @@ public class ImUtil {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
@ -237,7 +238,7 @@ public class ImUtil {
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
@ -270,7 +271,7 @@ public class ImUtil {
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
@ -281,8 +282,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 extend) {
		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 extend) {
//		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);
@ -318,7 +323,36 @@ public class ImUtil {
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	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);
		params.put("sender_name", fromName);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("session_id", sessionId);
		params.put("business_type", businessType);
		params.put("extend", null);
//		String response = httpClientUtil.postBody(imAddr, params);
		String response = HttpClientUtil.postBodyStatic(imAddr, params);
		return response;
	}
	/**
	 * 更新会话状态
	 *
@ -497,7 +531,7 @@ public class ImUtil {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
		JSONObject params = new JSONObject();
		params.put("user", user + ":" + 0);
		HttpClientUtil.putBody(imAddr, params);
		httpClientUtil.putBody(imAddr, params);
	}
	
	/**
@ -533,7 +567,7 @@ public class ImUtil {
		Boolean re = false;
		String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
		JSONObject params = new JSONObject();
		String ret = HttpClientUtil.get(url, "UTF-8");
		String ret = httpClientUtil.get(url, "UTF-8");
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
@ -555,8 +589,9 @@ public class ImUtil {
	/**
	 * 创建会话(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);
@ -599,7 +634,7 @@ public class ImUtil {
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
				+ "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			String ret = httpClientUtil.get(url, "UTF-8");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException(obj.getString("message"));
@ -615,7 +650,7 @@ public class ImUtil {
	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 {
			String ret = HttpClientUtil.get(url, "UTF-8");
			String ret = httpClientUtil.get(url, "UTF-8");
			JSONArray obj = JSON.parseArray(ret);
			return obj;
		} catch (Exception e) {
@ -678,7 +713,7 @@ public class ImUtil {
	public JSONObject getTopic(String topicId) throws Exception {
		String url = im_host + "api/v2/sessions/topics/" + topicId + "?topic_id=" + topicId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("获取议题失败!");
@ -700,7 +735,7 @@ public class ImUtil {
	public JSONArray getParticipants(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
@ -717,7 +752,7 @@ public class ImUtil {
	public JSONArray getSessions(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
@ -727,7 +762,7 @@ public class ImUtil {
	public JSONObject cleanMessageToRedis(String sessionId){
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
@ -737,7 +772,7 @@ public class ImUtil {
	public JSONObject cleanMessageLastFetchTime(String sessionId,String userId){
		String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
@ -754,7 +789,7 @@ public class ImUtil {
	public JSONObject getSingleSessionInfo(String sessionId,String userId){
		String url = im_host + "api/v2/sessions/" + sessionId + "/session?user_id=" + userId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
@ -776,7 +811,7 @@ public class ImUtil {
		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");
		String response = httpClientUtil.post(imAddr, params, "UTF-8");
		return response;
	}
	
@ -816,7 +851,7 @@ public class ImUtil {
	 */
	public Integer sessionCountByType(String userid,Integer type,Integer status){
		String url = im_host + "api/v2/sessions/sessionCountByType?user_id="+userid+"&type="+type+"&status="+status;
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
		if(obj.getInteger("status") ==200){
			return obj.getInteger("count");
@ -828,7 +863,7 @@ public class ImUtil {
	public Integer SessionsUnreadMessageCountByUserId(String userid){
		String url = im_host + "api/v2/sessions/unread_message_count?user_id="+userid;
//		String url = "http://ehr.yihu.com/api/v2/sessions/unread_message_count?user_id="+userid;
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
@ -848,7 +883,7 @@ public class ImUtil {
		if (StringUtils.isNotBlank(senderId)){
			url+="&senderId="+senderId;
		}
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
@ -864,7 +899,7 @@ public class ImUtil {
	 */
	public Integer UserSessionsUnreadMessageCount(String session,String userid){
		String url = im_host + "api/v2/sessions/"+session+"/unread_message_count?user_id="+userid;
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
@ -882,7 +917,7 @@ public class ImUtil {
	public JSONObject getSessionUnreadMessageCount(String sessionId, String userId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/unread_message_count?user_id=" + userId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			return  JSONObject.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
@ -895,7 +930,7 @@ public class ImUtil {
	 */
	public String getOnlineCountByType(String type) {
		String url = im_host + "api/v2/sessions/getOnlineCountByType?type="+type;
		String ret = HttpClientUtil.get(url, "UTF-8");
		String ret = httpClientUtil.get(url, "UTF-8");
		return ret;
	}
@ -905,7 +940,7 @@ public class ImUtil {
	 */
	public String getOnlineListByType(String type) {
		String url = im_host + "api/v2/sessions/getOnlineListByType?type="+type;
		String ret = HttpClientUtil.get(url, "UTF-8");
		String ret = httpClientUtil.get(url, "UTF-8");
		return ret;
	}
@ -916,7 +951,7 @@ public class ImUtil {
	 */
	public String findByUserIdAndType(String userId,String type) {
		String url = im_host + "api/v2/sessions/findByUserIdAndType?userId="+userId+"&type="+type;
		String ret = HttpClientUtil.get(url, "UTF-8");
		String ret = httpClientUtil.get(url, "UTF-8");
		return ret;
	}
@ -933,7 +968,7 @@ public class ImUtil {
	 */
	public String getSessionListByType(String user_id, String page, String size, String type, String status, String name,String search_type){
		String url = im_host + "api/v2/sessions/sessionListByType?user_id="+user_id+"&page="+page+"&size="+size+"&type="+type+"&status="+(status==null?"":status)+"&name="+(name==null?"":name)+"&search_type="+(search_type==null?"":search_type);
		String ret = HttpClientUtil.get(url, "utf-8");
		String ret = httpClientUtil.get(url, "utf-8");
		return ret;
	}
}

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

@ -14,6 +14,9 @@ import java.util.Date;
@Entity
@Table(name = "wlyy_consult")
public class ConsultDo extends UuidIdentityEntity {
	private String code;//新补充字段
	// 患者标识
	private String patient;
	// 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,
@ -41,6 +44,14 @@ public class ConsultDo extends UuidIdentityEntity {
	//来源
	private String source;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getSource() {
		return source;
	}

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

@ -305,6 +305,17 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
    private Integer well;//好评度
    //外部数据-年龄数据
    private Integer age;
    @Transient
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getWell() {
        return well;

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

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

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

@ -25,6 +25,16 @@ public class WlyyDoorOrderItemDO extends IdEntity {
    private String code;
    private Date createTime;
    private String orderId;
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public String getDoctor() {
        return doctor;
    }

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

@ -19,6 +19,9 @@ 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 +72,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;
    }

+ 15 - 7
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,23 +581,28 @@ 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;
    }
    @Column(name = "number")
    public String getNumber() {
        return number;

+ 19 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/followup/Followup.java

@ -29,9 +29,11 @@ public class Followup extends IntegerIdentityEntity {
	private Date followupNextDate;
	//随访方式【字典FOLLOWUP_WAY_DICT】
	private String followupType;
	private String followupClassName;
	//随访类别,多类别“,”分割【1.高血压 2.糖尿病 3.肿瘤 4.精神分裂症 5.产后 6.新生儿 7.严重精神病 8.80岁以上老人 9.肺结核 10异常体温随访
	// 11.冠心病日常随访 12.慢性妇科炎症13.慢性前列腺疾病日常随访 14.慢性乳腺疾病日常随访 15慢性肾病日常随访 16慢性阻塞性肺病 17脑卒中日常随访 18脂肪肝日常随访 21厦心冠心病社区随访
	private String followupClass;
	private String followupTypeName;
	//随访管理状态【字典FOLLOWUP_MANAGER_STATUS】
	private String followupManagerStatus;
	//医生代码
@ -436,4 +438,21 @@ public class Followup extends IntegerIdentityEntity {
		this.ruralDoctorsFlag = ruralDoctorsFlag;
	}
	@Transient
	public String getFollowupTypeName() {
		return followupTypeName;
	}
	public void setFollowupTypeName(String followupTypeName) {
		this.followupTypeName = followupTypeName;
	}
	@Transient
	public String getFollowupClassName() {
		return followupClassName;
	}
	public void setFollowupClassName(String followupClassName) {
		this.followupClassName = followupClassName;
	}
}

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

@ -0,0 +1,52 @@
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;
	}
}

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/article/KnowledgeArticleDictDO.java

@ -128,6 +128,7 @@ public class KnowledgeArticleDictDO extends UuidIdentityEntity {
		this.doctorList = doctorList;
	}
	@Column(name = "is_comment")
	public Integer getComment() {
		return comment;
	}

+ 57 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/BaseSignDO.java

@ -0,0 +1,57 @@
package com.yihu.jw.entity.hospital.booking;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 签到表
 * Created by yeshijie on 2022/12/7.
 */
@Entity
@Table(name = "base_sign")
public class BaseSignDO extends UuidIdentityEntityWithCreateTime {
    private String relationId;//关联id
    private Integer type;//类型1门诊/预约挂号
    private String patient;
    private String patientName;
    @Column(name = "relation_id")
    public String getRelationId() {
        return relationId;
    }
    public void setRelationId(String relationId) {
        this.relationId = relationId;
    }
    @Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
}

+ 452 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/PatientReservation.java

@ -0,0 +1,452 @@
package com.yihu.jw.entity.hospital.booking;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
/**
 * 预约挂号记录表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_reservation")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_reservation")
public class PatientReservation extends IdEntity {
	/**
	 *
	 */
	private static final long serialVersionUID = 8452660447546825044L;
	// 预约号/预约流水号
	private String code;
	// 医生标识(医生帮患者预约时才会有值)
	private String doctor;
	// 医生姓名(医生帮患者预约时才会有值)
	private String dname;
	// 患者标识
	private String patient;
	// 患者身份证
	private String idcard;
	// 患者姓名
	private String name;
	// 患者手机号
	private String phone;
	// 患者社保卡号
	private String ssc;
	// 预约时间段:AM (上午)或者PM (下午)
	private String sectionType;
	// 一次预约段的开始时间
	private Date startTime;
	// 一次预约段的结束时间
	private Date endTime;
	// 医生所在医疗机构编码
	private String orgCode;
	// 医疗机构名称
	private String orgName;
	// 科室编码
	private String deptCode;
	// 科室名称
	private String deptName;
	// 专家ID/编码
	private String doctorCode;
	// 专家姓名
	private String doctorName;
	// 专家头像
	private String doctorPhoto;
	// 专家职称
	private String doctorJob;
	// 状态:1预约成功,0预约取消
	private Integer status;
	//取消预约者(状态为预约取消时才有值)
	private String canceler;
	//取消预约者姓名(状态为预约取消时才有值)
	private String cancelerName;
	//取消预约者角色(状态为预约取消时才有值)1专科医生,2全科医生,3健康管理师,4临时专科 5.患者 (与医生服务团队角色一直)6.客服
	private Integer cancelerType;
	//取消时间(状态为预约取消时才有值)
	private String cancelerTime;
	// 预约时间
	private Date czrq;
	// 0 健康之路 1智业
	private String type;
	// 签约类型 1三师 2家庭
	private Integer signType;
	// 行政团队
	private Long adminTeamCode;
	//关联电话记录Code(通过客服系统预约才有值)
	private String callCode;
	//客服系统客服code(通过客服系统预约才有值)
	private String userCode;
	//客服系统客服name(通过客服系统预约才有值)
	private String userName;
	//转诊类型 1普诊 2复诊
	private Integer reservationType;
	//附带消息类型(0:健康咨询  1:康复计划 2:门诊记录 3:住院记录 4:检查检验 5:用药记录 6:体检记录 7:血压情况  8
	//:血糖情况 9:产检记录 10:免疫记录  11:筛查报告)
	private String incidentalMsgType;
	//附带消息内容大概
	private String incidentalMsg;
	//转诊原因
	private String reservationReason;
	//参数json字符串
	private String paramJson;
	//业务关联code
	private String relationCode;
	private Integer source;//代预约来源(1体征预警 2疾病筛查 3康复复诊 4健康咨询)
	private Integer patientReadStatus;
	private Integer doctorReadStatus;
	private String signId;//base_sign表的id
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getDoctor() {
		return doctor;
	}
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getSsc() {
		return ssc;
	}
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	@Column(name = "section_type")
	public String getSectionType() {
		return sectionType;
	}
	public void setSectionType(String sectionType) {
		this.sectionType = sectionType;
	}
	@Column(name = "start_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getStartTime() {
		return startTime;
	}
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}
	@Column(name = "end_time")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEndTime() {
		return endTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	@Column(name = "org_code")
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	@Column(name = "org_name")
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}
	@Column(name = "dept_code")
	public String getDeptCode() {
		return deptCode;
	}
	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}
	@Column(name = "dept_name")
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	@Column(name = "doctor_code")
	public String getDoctorCode() {
		return doctorCode;
	}
	public void setDoctorCode(String doctorCode) {
		this.doctorCode = doctorCode;
	}
	@Column(name = "doctor_name")
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	@Column(name = "doctor_photo")
	public String getDoctorPhoto() {
		return doctorPhoto;
	}
	public void setDoctorPhoto(String doctorPhoto) {
		this.doctorPhoto = doctorPhoto;
	}
	@Column(name = "doctor_job")
	public String getDoctorJob() {
		return doctorJob;
	}
	public void setDoctorJob(String doctorJob) {
		this.doctorJob = doctorJob;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getCanceler() {
		return canceler;
	}
	public void setCanceler(String canceler) {
		this.canceler = canceler;
	}
	@Column(name = "canceler_name")
	public String getCancelerName() {
		return cancelerName;
	}
	public void setCancelerName(String cancelerName) {
		this.cancelerName = cancelerName;
	}
	@Column(name = "canceler_type")
	public Integer getCancelerType() {
		return cancelerType;
	}
	public void setCancelerType(Integer cancelerType) {
		this.cancelerType = cancelerType;
	}
	@Column(name = "canceler_time")
	public String getCancelerTime() {
		return cancelerTime;
	}
	public void setCancelerTime(String cancelerTime) {
		this.cancelerTime = cancelerTime;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public Integer getSignType() {
		return signType;
	}
	public void setSignType(Integer signType) {
		this.signType = signType;
	}
	public Long getAdminTeamCode() {
		return adminTeamCode;
	}
	public void setAdminTeamCode(Long adminTeamCode) {
		this.adminTeamCode = adminTeamCode;
	}
	public String getCallCode() {
		return callCode;
	}
	public void setCallCode(String callCode) {
		this.callCode = callCode;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public Integer getReservationType() {
		return reservationType;
	}
	public void setReservationType(Integer reservationType) {
		this.reservationType = reservationType;
	}
	public String getIncidentalMsgType() {
		return incidentalMsgType;
	}
	public void setIncidentalMsgType(String incidentalMsgType) {
		this.incidentalMsgType = incidentalMsgType;
	}
	public String getIncidentalMsg() {
		return incidentalMsg;
	}
	public void setIncidentalMsg(String incidentalMsg) {
		this.incidentalMsg = incidentalMsg;
	}
	public String getReservationReason() {
		return reservationReason;
	}
	public void setReservationReason(String reservationReason) {
		this.reservationReason = reservationReason;
	}
	public String getParamJson() {
		return paramJson;
	}
	public void setParamJson(String paramJson) {
		this.paramJson = paramJson;
	}
	public String getRelationCode() {
		return relationCode;
	}
	public void setRelationCode(String relationCode) {
		this.relationCode = relationCode;
	}
	public Integer getSource() {
		return source;
	}
	public void setSource(Integer source) {
		this.source = source;
	}
	public Integer getPatientReadStatus() {
		return patientReadStatus;
	}
	public void setPatientReadStatus(Integer patientReadStatus) {
		this.patientReadStatus = patientReadStatus;
	}
	public Integer getDoctorReadStatus() {
		return doctorReadStatus;
	}
	public void setDoctorReadStatus(Integer doctorReadStatus) {
		this.doctorReadStatus = doctorReadStatus;
	}
	@Column(name = "sign_id")
	public String getSignId() {
		return signId;
	}
	public void setSignId(String signId) {
		this.signId = signId;
	}
}

+ 49 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/booking/ReservationHospitalDept.java

@ -0,0 +1,49 @@
package com.yihu.jw.entity.hospital.booking;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
 * Created by wangzhinan on 2019/9/11.
 * 预约科室
 */
@Entity
@Table(name = "wlyy_reservation_hospital_dept")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_reservation_hospital_dept")
public class ReservationHospitalDept extends IdEntity {
    private String code;//科室编码
    private String hospitalCode;//医院或者社区编码
    private String name;//科室名称
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name ="hospital_code")
    public String getHospitalCode() {
        return hospitalCode;
    }
    public void setHospitalCode(String hospitalCode) {
        this.hospitalCode = hospitalCode;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

+ 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;
    }
}

+ 86 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/message/WlyyDynamicMessages.java

@ -0,0 +1,86 @@
package com.yihu.jw.entity.message;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/***
 * @ClassName: WlyyDynamicMessages
 * @Description: 门户页实时动态展示
 * @Auther: shi kejing
 * @Date: 2020/9/10 9:17
 */
@Entity
@Table(name = "wlyy_dynamic_messages")
public class WlyyDynamicMessages 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类型 1医生 2居民
public WlyyDynamicMessages(){
}
public WlyyDynamicMessages(Long id){
    this.id = id;
}
    @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;
    }
}

+ 135 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/PatientDischargeDO.java

@ -0,0 +1,135 @@
package com.yihu.jw.entity.rehabilitation;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "wlyy_patient_discharge")
public class PatientDischargeDO extends IdEntity {
    // 业务主键
    private String code;
    private String patient;    //居民code
    // 身份证号
    private String idcard;
    // 姓名
    private String name;
    // 社保卡號
    private String ssc;
    private String hospital;//居民签约所在机构code
    private String hospitalName;//机构名称
    private String address;//地址
    private Integer type;//1患者家签列表 2康复下转列表
    private Integer signStatus;//签约状态(1已家签 0 待家签)
    private String createUser;//创建code
    private String createUserName;//创建者
    private Date createTime;//创建时间
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public Integer getSignStatus() {
        return signStatus;
    }
    public void setSignStatus(Integer signStatus) {
        this.signStatus = signStatus;
    }
}

+ 102 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientDiseaseServer.java

@ -0,0 +1,102 @@
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.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Trick on 2018/7/4.
 */
@Entity
@Table(name = "wlyy_patient_disease_server")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_disease_server")
public class PatientDiseaseServer extends IdEntity {
    private String code;
    private String specialistRelationCode;//专科医生团队签约关系code',
    private String patient;//居民',
    private String patientName;//居民名字',
    private String disease;//疾病',
    private String diseaseName;//疾病名称',
    private String del;//1正常;0删除',
    private Date updateTime;
    private Date createTime;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getSpecialistRelationCode() {
        return specialistRelationCode;
    }
    public void setSpecialistRelationCode(String specialistRelationCode) {
        this.specialistRelationCode = specialistRelationCode;
    }
    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 getDisease() {
        return disease;
    }
    public void setDisease(String disease) {
        this.disease = disease;
    }
    public String getDiseaseName() {
        return diseaseName;
    }
    public void setDiseaseName(String diseaseName) {
        this.diseaseName = diseaseName;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    @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;
    }
}

+ 2 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientMedicalRecordsDO.java

@ -3,6 +3,7 @@ package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import com.yihu.jw.entity.UuidIdentityEntity;
import org.springframework.stereotype.Component;
import javax.persistence.Column;
import javax.persistence.Entity;
@ -12,6 +13,7 @@ import java.util.Date;
/**
 * create by hmf on 2020/02/27 居民住院病历
 */
@Component
@Entity
@Table(name = "wlyy_patient_medical_records_rehabilitation")
public class PatientMedicalRecordsDO extends UuidIdentityEntity {

+ 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;
    }
}

+ 48 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPlanTemplateDO.java

@ -32,6 +32,54 @@ public class RehabilitationPlanTemplateDO extends UuidIdentityEntityWithOperator
        return saasId;
    }
    /**
     * 新增字段
     */
    @Column(name = "disease_id")
    private String diseaseId;//病种code
    @Column(name = "disease_name")
    private String diseaseName;
    @Column(name = "status")
    private String status;
    @Column(name = "type")
    private String type;
    public String getDiseaseId() {
        return diseaseId;
    }
    public void setDiseaseId(String diseaseId) {
        this.diseaseId = diseaseId;
    }
    public String getDiseaseName() {
        return diseaseName;
    }
    public void setDiseaseName(String diseaseName) {
        this.diseaseName = diseaseName;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }

+ 67 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/TemplateJson.java

@ -0,0 +1,67 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author suqinyi
 * @Date 2023/9/19
 */
@Entity
@Table(name = "template_json")
@SequenceGenerator(name="id_generated", sequenceName="DICT_DOCTOR_DUTY_SEQ")
public class TemplateJson extends UuidIdentityEntity {
    private String templateId;
    private String templateName;
    private String templateJson;
    private Date createTime;
    private String createUser;
    public String getTemplateId() {
        return templateId;
    }
    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }
    public String getTemplateName() {
        return templateName;
    }
    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
    public String getTemplateJson() {
        return templateJson;
    }
    public void setTemplateJson(String templateJson) {
        this.templateJson = templateJson;
    }
    @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 String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
}

+ 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;
    }
}

+ 70 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wechat/WechatTag.java

@ -0,0 +1,70 @@
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")
public class WechatTag extends IdEntity {
    private Integer tagId;
    private String tagName;
    private Date createTime;
    private Integer del;
    private String townCode;//区code
    private String townName;//区名称
    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 Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    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;
    }
}

+ 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;
    }
}

+ 8 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/specialist/SpecialistMapping.java

@ -59,6 +59,14 @@ public class SpecialistMapping {
    }
    public static class rehabilitation{
        public static final String findRehabilitationServiceItem = "/findRehabilitationServiceItem";
        public static final String findRehabilitationPlanTemplatenew = "/findRehabilitationPlanTemplatenew";
        public static final String saveRehabilitationPlanTemplate = "/saveRehabilitationPlanTemplate";
        public static final String saveTemplate = "/saveTemplate";
        public static final String findDiseaseList = "/findDiseaseList";
        public static final String findSaveTemplate = "/findSaveTemplate";
        public static final String findRehabilitationPlan = "/findRehabilitationPlan";
        public static final String createRehabilitationPlanTemplate = "/createRehabilitationPlanTemplate";
        public static final String deleteRehabilitationPlanTemplate = "/deleteRehabilitationPlanTemplate";

+ 13 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/hospital/prescription/WlyyHisSettleVO.java

@ -256,6 +256,19 @@ public class WlyyHisSettleVO extends UuidIdentityVOWithOperator {
    @ApiModelProperty(value = "统筹基金支付",example = "统筹基金支付")
    private String tcjjzf;
    /**
     * 其他基金支付
     */
    @ApiModelProperty(value = "其他基金支付",example = "其他基金支付")
    private String qtjjzf;
    public String getQtjjzf() {
        return qtjjzf;
    }
    public void setQtjjzf(String qtjjzf) {
        this.qtjjzf = qtjjzf;
    }
    public String getYljzjj() {
        return yljzjj;

+ 48 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/web/endpoint/EnvelopRestEndpoint.java

@ -632,4 +632,52 @@ public abstract class EnvelopRestEndpoint extends Exception {
        }
        return ip;
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("message", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("message", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public void error(Exception e) {
        e.printStackTrace();
    }
}

+ 340 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java

@ -0,0 +1,340 @@
package com.yihu.jw.util.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.entity.util.SystemConfEntity;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by yeshijie on 2023/2/13.
 */
@Component
public class CommonUtil {
    private Logger logger = LoggerFactory.getLogger(CommonUtil.class);
//    @Value("${neiwang.enable}")
    private Boolean isneiwang = false;  //如果不是内网项目要转到到内网wlyy在上传
//    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
//    @Value("${neiwang.wlyy}")
    private String neiwangWlyy;  //内网的项目地址
    @Autowired
    private HttpClientUtil httpClientUtil;
    public static String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    /**
     * 传入身高体重,计算BMI值
     *
     * @param weightStr 体重
     * @param heightStr 身高
     * @return
     */
    public static double getBMIByWeightAndHeight(String weightStr, String heightStr) {
        DecimalFormat df2 = new DecimalFormat("###.00");
        double weight = Double.parseDouble(weightStr);
        Integer heightCM = Integer.parseInt(heightStr);
        heightStr = df2.format(heightCM / 100d);
        double height = Double.parseDouble(heightStr);
        double bmi = weight / (height * height);
        return bmi;
    }
    /**
     * 删除文件夹
     * @param folder
     */
    public static void deleteFolder(File folder){
        File[] files  = folder.listFiles();
        if (files != null){
            for(File f: files){
                if (f.isDirectory()){
                    deleteFolder(f);
                }else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
    /**
     * double转字符串,在转int
     * double*100转int 有bug 34.3会会变成3429
     * @param d
     * @return
     */
    public static Integer doubleToInt(Double d){
        if(d==null){
            return 0;
        }
        String currency = String.valueOf(d);
        int index = currency.indexOf(".");
        int length = currency.length();
        Integer amLong = 0;
        if(index == -1){
            amLong = Integer.valueOf(currency+"00");
        }else if(length - index >= 3){
            amLong = Integer.valueOf((currency.substring(0, index+3)).replace(".", ""));
            if(length-index>3){
                if(Integer.valueOf(currency.substring(index+3,index+4))>=5){
                    amLong++;
                }
            }
        }else if(length - index == 2){
            amLong = Integer.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
        }else{
            amLong = Integer.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
        }
        return amLong;
    }
    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;
    }
    public String copyTempVoice(String voices) throws Exception {
        if (isneiwang) {
            // 文件保存的临时路径
            String serverUrl = fastdfs_file_url;
            FastDFSUtil fastDFSUtil = new FastDFSUtil();
            String fileUrls = "";
            File f = new File(voices);
            if (f.exists()) {
                String fileName = f.getName();
                InputStream in = new FileInputStream(f);
                ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
                in.close();
                if (result != null) {
                    fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",") + serverUrl
                            + result.get("groupName").toString().replaceAll("\"", "") + "/"
                            + result.get("remoteFileName").toString().replaceAll("\"", "");
                    f.delete();
                }
            }
            return fileUrls;
        } else {
            String fileUrls = toNeiWang(voices, "");
            return fileUrls;
        }
    }
    /**
     * 如果是外网那是发送到内网的服务器
     *
     * @param files
     * @return
     */
    public String toNeiWang(String files, String tempPath) throws FileNotFoundException {
        logger.info(" toNeiWang start files :" + tempPath + files);
        //转发到内网服务器
        String[] fileArray = files.split(",");
        String fileUrls = "";
        for (String file : fileArray) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            File f = new File(tempPath + file);
            logger.info(" toNeiWang File exists :" + f.exists());
            if (f.exists()) {
                String fileName = f.getName();
                InputStream in = new FileInputStream(f);
                String returnStr = request(request, in, fileName);
                logger.info("returnStr :" + returnStr);
                logger.info("fileName :" + fileName);
                logger.info("result :" + returnStr.toString());
                if (returnStr != null) {
                    //1.3.7去掉前缀
                    fileUrls += returnStr+",";
                    f.delete();
                }
            } else {
                String path = tempPath + file;
                String returnStr = request(request, path);
                logger.info("result :" + returnStr.toString());
                if (returnStr != null) {
                    //1.3.7去掉前缀
                    fileUrls += returnStr+",";
                }
            }
        }
        logger.info(" toNeiWang end files :" + fileUrls);
        return fileUrls.substring(0,fileUrls.length()-1);
    }
    private String request(HttpServletRequest request, String path) {
        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径
        String result = "";
        try {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("filePaths", path));
            // 将响应内容转换为字符串
            result = httpClientUtil.post(url, params, "UTF-8");
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public String request(String remote_url, MultipartFile file, String type) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        logger.info(file.getOriginalFilename());
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(type)) {
                builder.addTextBody("type", type); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public String request(HttpServletRequest request, InputStream in, String fileName) {
        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(request.getParameter("type")) ||
                    !org.springframework.util.StringUtils.isEmpty(request.getAttribute("type"))) {
                builder.addTextBody("type",  null != request.getParameter("type") ? request.getParameter("type") : String.valueOf(request.getAttribute("type"))); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public String copyTempImage(String files) throws Exception {
        String tempPath = SystemConfEntity.getInstance().getTempPath() + File.separator;
        if (isneiwang) {
            // 文件保存的临时路径
            String[] fileArray = files.split(",");
            FastDFSUtil fastDFSUtil = new FastDFSUtil();
            String fileUrls = "";
            for (String file : fileArray) {
                File f = new File(tempPath + file);
                File fs = new File(tempPath + file + "_small");
                if (f.exists()) {
                    String fileName = f.getName();
                    InputStream in = new FileInputStream(f);
                    ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
                    in.close();
                    if (result != null) {
                        //1.3.7去掉前缀
                        fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",")
                                + result.get("groupName").toString().replaceAll("\"", "") + "/"
                                + result.get("remoteFileName").toString().replaceAll("\"", "");
                        f.delete();
                        if (fs.exists()) {
                            fs.delete();
                        }
                    }
                }
            }
            return fileUrls;
        } else {
            String fileUrls = toNeiWang(files, tempPath);
            return fileUrls;
        }
    }
}

+ 71 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/DataUtils.java

@ -0,0 +1,71 @@
package com.yihu.jw.util.common;/**
 * Created by nature of king on 2018/9/17.
 */
/**
 * @author wangzhinan
 * @create 2018-09-17 15:32
 * @desc 数据转换工具
 **/
public class DataUtils {
    public static Integer doubleToInt(Double d) {
        if (d == null) {
            return 0;
        }
        String currency = String.valueOf(d);
        int index = currency.indexOf(".");
        int length = currency.length();
        Integer amLong = 0;
        if (index == -1) {
            amLong = Integer.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Integer.valueOf((currency.substring(0, index + 3)).replace(".", ""));
            if (length - index > 3) {
                if (Integer.valueOf(currency.substring(index + 3, index + 4)) >= 5) {
                    amLong++;
                }
            }
        } else if (length - index == 2) {
            amLong = Integer.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Integer.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong;
    }
    public static String integerTransferDouble(Integer amount){
        try {
            if(!amount.toString().matches("\\-?[0-9]+"));
        }catch (Exception e) {
            e.printStackTrace();
        }
        int flag = 0;
        String amString = amount.toString();
        if(amString.charAt(0)=='-'){
            flag = 1;
            amString = amString.substring(1);
        }
        StringBuffer result = new StringBuffer();
        if(amString.length()==1){
            result.append("0.0").append(amString);
        }else if(amString.length() == 2){
            result.append("0.").append(amString);
        }else{
            String intString = amString.substring(0,amString.length()-2);
            for(int i=1; i<=intString.length();i++){
                if( (i-1)%3 == 0 && i !=1){
//                    result.append(",");
                }
                result.append(intString.substring(intString.length()-i,intString.length()-i+1));
            }
            result.reverse().append(".").append(amString.substring(amString.length()-2));
        }
        if(flag == 1){
            return "-"+result.toString();
        }else{
            return result.toString();
        }
    }
}

+ 148 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/ISqlUtils.java

@ -0,0 +1,148 @@
package com.yihu.jw.util.common;/**
 * Created by nature of king on 2018/4/27.
 */
import com.alibaba.fastjson.JSONObject;
import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author wangzhinan
 * @create 2018-04-27 12:47
 * @desc sql自定义编辑
 **/
public class ISqlUtils {
    public static String getSql(Object object,Integer page,Integer size,String isFlag){
        StringBuffer sb = new StringBuffer();
        Class c =object.getClass();
        Table table = (Table)c.getAnnotation(Table.class);
        String tableName = table.name();
        if (isFlag.equalsIgnoreCase("count")){
            sb.append("select count(1) AS total from ").append(tableName).append(" where 1=1");
        }else if(isFlag.equalsIgnoreCase("*")){
            sb.append("select * from ").append(tableName).append(" where 1=1 ");
        }
        JSONObject object1  = (JSONObject) JSONObject.toJSON(object);
        if (object1.getString("id") !=null){
            sb.append(" and id = '" + object1.getString("id")+"' ");
        }
        Field[] fArray= c.getDeclaredFields();
        for(Field f:fArray){
            //拿到字段后与实体类中的属性匹配,并得到其get方法,用来获取他的属性值
            String getMethodName ="";
            boolean isCExist =f.isAnnotationPresent(Column.class);
            if(isCExist){
                Column mc =f.getAnnotation(Column.class);
                String columeName =mc.name();  //字段对应数据库名字
                String name =f.getName();       //字段名字
                Class a= f.getType();          //字段类型
                Object value=null;              //字段值
                getMethodName="get"+name.substring(0,1).toUpperCase()+name.substring(1);//拼接属性的get方法
                try {
                    Method m =c.getMethod(getMethodName);
                    value =(Object)m.invoke(object);     //拿到属性的值
                    if(value == null || "".equals(value)){  //如果属性没值,不拼接sql
                        continue;
                    }
                    else if(value instanceof String){
                        value ="'%"+value+"%'";
                        sb.append(" and ").append(columeName +" like " ).append(value+"");
                    }else if (value instanceof Integer){
                        value = value;
                        sb.append(" and ").append(columeName +" = " ).append(value+"");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if(isFlag.equalsIgnoreCase("*")){
            sb.append(" ORDER BY create_time DESC ").append("LIMIT ").append((page-1)*size+",").append(size);
        }
        return sb.toString();
    }
    public static String getAllSql(Object object){
        StringBuffer sb = new StringBuffer();
        Class c =object.getClass();
        Table table = (Table)c.getAnnotation(Table.class);
        String tableName = table.name();
        sb.append("select * from ").append(tableName).append(" where 1=1 ");
        Field[] fArray= c.getDeclaredFields();
        for(Field f:fArray){
            //拿到字段后与实体类中的属性匹配,并得到其get方法,用来获取他的属性值
            String getMethodName ="";
            boolean isCExist =f.isAnnotationPresent(Column.class);
            if(isCExist){
                Column mc =f.getAnnotation(Column.class);
                String columeName =mc.name();  //字段对应数据库名字
                String name =f.getName();       //字段名字
                Object value=null;              //字段值
                getMethodName="get"+name.substring(0,1).toUpperCase()+name.substring(1);//拼接属性的get方法
                try {
                    Method m =c.getMethod(getMethodName);
                    value =(Object)m.invoke(object);     //拿到属性的值
                    if(value == null || "".equals(value) || value.equals(Integer.parseInt("0"))){  //如果属性没值,不拼接sql
                        continue;
                    }
                    else if(value instanceof String){
                        value ="'"+value+"'";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sb.append(" and ").append(columeName +"=" ).append(value+"");
            }
        }
        return sb.toString();
    }
    public static  String getUpdateSql(Object object){
        StringBuffer sb = new StringBuffer();
        Class c = object.getClass();
        Table table = (Table)c.getAnnotation(Table.class);
        String tableName = table.name();
        sb.append("update ").append(tableName).append(" set ");
        Field[] fArray = c.getDeclaredFields();
        for (Field f:fArray){
            String getMethoName = "";
            boolean isCExist = f.isAnnotationPresent(Column.class);
            if (isCExist){
                Column mc = f.getAnnotation(Column.class);
                String columeName = mc.name();
                String name = f.getName();
                Class a= f.getType();
                Object value= null;
                getMethoName = "get" + name.substring(0,1).toUpperCase()+name.substring(1);
                try {
                    Method m = c.getMethod(getMethoName);
                    if (Date.class.isAssignableFrom(a)){
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = sdf.format((Object)m.invoke(object));
                    }else {
                        value = (Object)m.invoke(object);
                    }
                    if (value == null || "".equals(value)){
                        continue;
                    }
                    else if (value instanceof  String){
                        value = "'"+value+"'";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                sb.append(columeName + "=").append(value+"").append(",");
            }
        }
        sb.deleteCharAt(sb.length()-1);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
        sb.append(" where ").append("id = ").append("'"+jsonObject.get("id")+"'");
        return sb.toString();
    }
}

+ 15 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/IdCardUtil.java

@ -352,4 +352,19 @@ public class IdCardUtil {
        }
        return idcard;
    }
    public static String getSexNameBySexOrIdcard(String sex,String idcard){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(sex)){
            if(level_sex_1.equals(sex)){
                return level_sex_1_name;
            }else if(level_sex_2.equals(sex)){
                return level_sex_2_name;
            }else{
                return level_sex_3_name;
            }
        }else {
            return getSexNameForIdcard_new(idcard);
        }
    }
}

+ 14 - 0
common/common-util/src/main/java/com/yihu/jw/util/http/HttpClientUtil.java

@ -370,6 +370,17 @@ public class HttpClientUtil {
        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");
        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 postBodyHead(String url, com.alibaba.fastjson.JSONObject params, Map<String, Object> headerMap) {
        RestTemplate restTemplate = new RestTemplate();
@ -797,4 +808,7 @@ public class HttpClientUtil {
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
}

+ 1 - 1
svr/svr-internet-hospital/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name:  svr-internet-hospital-wangzhinan
    name:  svr-internet-hospital
  cloud:
    config:
      failFast: true

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

@ -0,0 +1,385 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-visit-behind</artifactId>
    <packaging>jar</packaging>
    <version>${parent.version}</version>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--            <scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!--注释掉就不会读取git的配置,只会读取yml中的配置-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>com.ylz.loginsdk</groupId>-->
        <!--<artifactId>ehcsdk</artifactId>-->
        <!--<version>1.0</version>-->
        <!--</dependency>-->
        <!--        <dependency>
                    <groupId>com.ylz.dmrh</groupId>
                    <artifactId>ehcsdk-java-sdk-base</artifactId>
                    <version>1.0.3</version>
                </dependency>-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-request-mapping</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-exception</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
            <version>4.2.3-GA</version>
        </dependency>
        <!-- 文件服务器 -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>fastdfs-starter</artifactId>
        </dependency>
        <!-- Swagger-ui library -->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- Jzkl Starter -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <!-- <scope>runtime</scope> -->
        </dependency>
        <!--<dependency>-->
        <!--<groupId>com.yihu</groupId>-->
        <!--<artifactId>elasticsearch-starter</artifactId>-->
        <!--<version>2.0.0</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>mailapi</artifactId>
                    <groupId>javax.mail</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 发送邮件 -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--   poi xml导入导出工具 start-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.yihu.ehr</groupId>
                    <artifactId>commons-util</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.commons</groupId>
                    <artifactId>commons-collections4</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>shield</artifactId>
            <version>2.4.6</version>
        </dependency>
        <!-- xlsx  依赖这个包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <!--   poi xml导入导出工具 end -->
        <!--基础业务组件-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>base-service</artifactId>
            <version>2.0.0</version>
            <exclusions>
                <exclusion>
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.his.hesb</groupId>
                    <artifactId>mqSdk</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--缩略图-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>push-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>sms-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>es-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.hikvision.ga</groupId>
            <artifactId>artemis-http-client</artifactId>
            <version>1.1.3</version>
        </dependency>
        <!--钉钉sdk-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>zwdd-sdk-java</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-speech-sdk-java</artifactId>
            <version>1.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.5</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-visit-behind</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <!-- 生成的jar中,不要包含pom.xml和pom.properties这两个文件 -->
                        <addMavenDescriptor>false</addMavenDescriptor>
                        <manifest>
                            <!-- 是否要把第三方jar加入到类构建路径 -->
                            <addClasspath>true</addClasspath>
                            <!-- 外部依赖jar包的最终位置 -->
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.yihu.SvrVisitBehind</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--拷贝依赖到jar外面的lib目录-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <id>copy-lib</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- 依赖包输出目录,将来不打进jar包里 -->
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                            <includeScope>runtime</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!--指定配置文件,将resources打成外部resource-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <!-- 指定配置文件目录,这样jar运行时会去找到同目录下的resources文件夹下查找 -->
                        <manifestEntries>
                            <Class-Path>resources/</Class-Path>
                        </manifestEntries>
                    </archive>
                    <!-- 打包时忽略的文件(也就是不打进jar包里的文件) -->
                    <excludes>
                        <exclude>**/*.yml</exclude>
                        <exclude>**/*.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- 拷贝资源文件 外面的resource目录-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <!-- 资源文件输出目录 -->
                            <outputDirectory>${project.build.directory}/resources</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
                <version>3.2.0</version>
            </plugin>
        </plugins>
    </build>
</project>

+ 23 - 0
svr/svr-visit-behind/src/main/java/com/yihu/SvrVisitBehind.java

@ -0,0 +1,23 @@
package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class SvrVisitBehind extends SpringBootServletInitializer {
    public static void main(String[] args)  {
        SpringApplication.run(SvrVisitBehind.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SvrVisitBehind.class);
    }
}

+ 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());
            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();
        }
    }
}

+ 27 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/BeanConfig.java

@ -0,0 +1,27 @@
package com.yihu.jw.hospital.config;
import com.yihu.jw.hospital.prescription.service.PrescriptionExpressageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
    //顺丰快递接口请求地址
    @Value("${express.sf_url}")
    private String sf_url;
    //顺丰快递接口接入编码
    @Value("${express.sf_code}")
    private String sf_code;
    //顺丰快递接口checkword
    @Value("${express.sf_check_word}")
    private String sf_check_word;
    @Bean(name = "prescriptionExpressageService")
    PrescriptionExpressageService prescriptionExpressageService(){
        return new PrescriptionExpressageService(sf_url,sf_code,sf_check_word);
    }
}

+ 49 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/MvcConfig.java

@ -0,0 +1,49 @@
package com.yihu.jw.hospital.config;
import com.yihu.jw.hospital.interceptor.CrosXssFilter;
import com.yihu.jw.hospital.interceptor.GateWayInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@Profile({"mlwProd"})
public class MvcConfig extends WebMvcConfigurationSupport {
    private Logger logger = LoggerFactory.getLogger(MvcConfig.class);
    @Autowired
    private GateWayInterceptor gateWayInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
//         excludePathPatterns 用户排除拦截 ,/third/juye/kit/**
        registry.addInterceptor(gateWayInterceptor).addPathPatterns("/open/gc/**").excludePathPatterns(
                "/open/gc/accesstoken",
                "/open/gc/createGcClientDetails");
        super.addInterceptors(registry);
        logger.info("init gateWayInterceptor");
    }
    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CrosXssFilter());
        registration.addUrlPatterns("/open/gc/**");
        registration.setName("CrosXssFilter");
        registration.setOrder(1);
        return registration;
    }
}

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SpringSecurityAuditorAware.java

@ -0,0 +1,15 @@
package com.yihu.jw.hospital.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
@Configuration
public class SpringSecurityAuditorAware implements AuditorAware {
    @Override
    public Optional getCurrentAuditor() {
        return Optional.empty();
    }
}

+ 44 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/config/SwaggerDocs.java

@ -0,0 +1,44 @@
package com.yihu.jw.hospital.config;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * Created by lith on 2018/11/23
 */
public class SwaggerDocs {
    public static void main(String[] args) throws Exception {
        //1.请求 http://ip:port/swagger-resources获取group
        String group = "Default";
        //2.定义请求地址 new URL("http://ip:port/v2/api-docs?group=" + groupName)
        //项目的swagger-ui地址
        URL remoteSwaggerFile = new URL("http://127.0.0.1:10024/v2/api-docs?group=" + group);
        //3.定义文件输出路径
        String prefix = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        //文档输出地址
        Path outputFile = Paths.get(prefix.substring(prefix.lastIndexOf(":") + 1, prefix.indexOf("target") - 1) + "/build/" + group);
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                //.withBasePathPrefix()
                .build();
        Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(remoteSwaggerFile)
                .withConfig(config)
                .build();
        converter.toFile(outputFile);
    }
}

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

@ -0,0 +1,146 @@
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;
import com.yihu.jw.gateway.dao.GcHttpLogDao;
import com.yihu.jw.gateway.service.GcClientDetailsService;
import com.yihu.jw.gateway.service.GcTokenService;
import com.yihu.jw.hospital.endpoint.gateway.model.BaseResultModel;
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.util.common.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
 * Created by chenweida on 2017/8/17.
 * 对外的网关
 */
@Controller
@RequestMapping(value = BaseHospitalRequestMapping.UpWebTherapySupserviceInfo.PREFIX, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Api(description = "token相关服务")
public class GcTokenController {
    @Autowired
    private GcTokenService gcTokenService;
    @Autowired
    private GcClientDetailsService clientDetailsService;
    @Autowired
    private GcHttpLogDao httpLogDao;
    @Value("${interceptor.accesstoken.time}")
    private Integer tokenTime;
    @Value("${wechat.id}")
    private String wxId;
    @ApiOperation("获取accesstoken")
    @RequestMapping(value = "accesstoken", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public ResultOneModel<GcTokenModel> getToken(
            @ApiParam(name = "appid", value = "appid", required = true) @RequestParam(required = true, value = "appid") String appid,
            @ApiParam(name = "appSecret", value = "appSecret", required = true) @RequestParam(required = true, value = "appSecret") String appSecret,
            @ApiParam(name = "过期时间 yyyy-MM-dd", value = "overTime", required = false) @RequestParam(required = false, value = "overTime") String overTime,
            HttpServletRequest request) {
        String ip = "";
        try {
            ip = IpUtil.getIpAddress(request);
            //查询appId 的token是否过期
            GcToken gcToken = new GcToken();
            List<GcToken> gcTokenList = gcTokenService.findByAppId(appid,wxId);
            if(gcTokenList == null || gcTokenList.size() == 0){
                //得到用户
                GcClientDetails clientDetails = clientDetailsService.findByAppId(appid);
                if (clientDetails == null) {
                    ResultOneModel resultOneModel = new ResultOneModel(null);
                    resultOneModel.setStatus(BaseResultModel.statusEm.error_Appid.getCode());
                    resultOneModel.setMessage(BaseResultModel.statusEm.error_Appid.getMessage());
                    saveHttpLog(ip, new JSONObject(request.getParameterMap()).toString(), "", "", request.getRequestURI(), 0, BaseResultModel.statusEm.error_Appid.getMessage());
                    return resultOneModel;
                }
                //判断appSecret
                if (!appSecret.equals(clientDetails.getAppSecret())) {
                    ResultOneModel resultOneModel = new ResultOneModel(null);
                    resultOneModel.setStatus(BaseResultModel.statusEm.error_AppSecret.getCode());
                    resultOneModel.setMessage(BaseResultModel.statusEm.error_AppSecret.getMessage());
                    saveHttpLog(ip, new JSONObject(request.getParameterMap()).toString(), "", "", request.getRequestURI(), 0, BaseResultModel.statusEm.error_Appid.getMessage());
                    return resultOneModel;
                }
                //生成token
                try {
                    gcToken = gcTokenService.createToken(appid, appSecret, IpUtil.getIpAddress(request),overTime,tokenTime);
                    saveHttpLog(ip, new JSONObject(request.getParameterMap()).toString(), new JSONObject(gcToken).toString(), gcToken.getAccesstoken(), request.getRequestURI(), 1, "成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                gcToken = gcTokenList.get(0);
            }
            GcTokenModel gcTokenModel = new GcTokenModel();
            BeanUtils.copyProperties(gcToken, gcTokenModel);
            System.out.print("token"+gcToken.getOutTime());
            gcTokenModel.setOutTime(gcToken.getOutTime().getTime());
            return new ResultOneModel(gcTokenModel);
        } catch (Exception e) {
            e.printStackTrace();
            saveHttpLog(ip, new JSONObject(request.getParameterMap()).toString(), "", "", request.getRequestURI(), 0, BaseResultModel.statusEm.login_system_error.getMessage());
            return new ResultOneModel(BaseResultModel.statusEm.login_system_error.getCode(), BaseResultModel.statusEm.login_system_error.getMessage());
        }
    }
    @ApiOperation("生成appId,appSecret")
    @RequestMapping(value = "createGcClientDetails", method = RequestMethod.POST)
    public ResultOneModel<GcClientDetailsModel> createClientDetails(
            @ApiParam(name = "appUri", value = "appUri", required = false) @RequestParam(required = false, value = "appUri") String appUri,
            @ApiParam(name = "createUserName", value = "createUserName", required = false) @RequestParam(required = false, value = "createUserName") String createUserName,
            @ApiParam(name = "creatieUser", value = "creatieUser", required = false) @RequestParam(required = false, value = "creatieUser") String creatieUser,
            @ApiParam(name = "remark", value = "remark", required = false) @RequestParam(required = false, value = "remark") String remark
    ){
        try {
            GcClientDetails gcClientDetails = clientDetailsService.createClientDetails(appUri,createUserName,creatieUser,remark);
            if(gcClientDetails==null){
                return new ResultOneModel(BaseResultModel.statusEm.login_system_error.getCode(), BaseResultModel.statusEm.login_system_error.getMessage());
            }
            GcClientDetailsModel gcClientDetailsModel = new GcClientDetailsModel();
            BeanUtils.copyProperties(gcClientDetails, gcClientDetailsModel);
            return new ResultOneModel(gcClientDetailsModel);
        }catch (Exception e) {
            return new ResultOneModel(BaseResultModel.statusEm.login_system_error.getCode(), BaseResultModel.statusEm.login_system_error.getMessage());
        }
    }
    private void saveHttpLog(String ip, String input, String output, String token, String method, Integer flag, String message) {
        GcHttpLog gcHttpLog = new GcHttpLog();
        gcHttpLog.setCreateTime(new Date());
        gcHttpLog.setIp(ip);
        gcHttpLog.setInput(input);
        if(output.length() > 3000) {
            output = output.substring(0, 3000);
        }
        gcHttpLog.setOutput(output);
        gcHttpLog.setToken(token);
        gcHttpLog.setMethod(method);
        gcHttpLog.setFlag(flag);
        gcHttpLog.setMessage(message);
        httpLogDao.save(gcHttpLog);
    }
}

+ 98 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/BaseResultModel.java

@ -0,0 +1,98 @@
package com.yihu.jw.hospital.endpoint.gateway.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by chenweida on 2017/8/17.
 */
@ApiModel("返回实体")
public class BaseResultModel {
    @ApiModelProperty(value = "状态", required = false, access = "response")
    protected Integer status = statusEm.success.getCode();
    @ApiModelProperty(value = "信息", required = false, access = "response")
    protected String message = "成功";
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public enum statusEm {
        success(10000, "请求成功"),//请求成功
        error_Appid(40004, "appid不存在"),//appid不存在
        error_AppSecret(40001, "AppSecret不存在"),//AppSecret不存在
        token_out_effect(-9002, "无效的token"),//token无效
        token_no_power(-9003, "用户没权限"),// 没权限 包括未授权 或者uri错误
        token_out_time(-9004, "accesstoken已过期"),//token无效
        token_null(-9005, "accesstoken为空"),// 没权限 包括未授权 或者uri错误
        error_params(-10000, "请求失败 参数错误"),//请求失败 参数错误
        error_no_ip(-10010, "请求失败,获取IP失败"),//请求失败,获取IP失败
        login_system_error(-10020, "系统异常"),
        login_publickey_error(-10030, "获取公钥失败"),
        file_upload_error(-10040, "文件上传失败"),
        find_error(-10050, "查询失败"),
        opera_error(-10060, "操作失败"),
        no_openid(-30000,"用户openId为空无法发送"),
        login_account_error(-20010, "账号不存在"),
        login_password_error(-20020, "密码错误"),
        login_IMEI_error(-20030, "获取imei失败");
        ;
        statusEm(Integer code, String message) {
            this.code = code;
            this.message = message;
        }
        private Integer code;
        private String message;
        public Integer getCode() {
            return code;
        }
        public void setCode(Integer code) {
            this.code = code;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
    }
    public BaseResultModel() {
    }
    public BaseResultModel(String message) {
        this.message = message;
    }
    public BaseResultModel(Integer status, String message) {
        this.status = status;
        this.message = message;
    }
}

+ 33 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/GcClientDetailsModel.java

@ -0,0 +1,33 @@
package com.yihu.jw.hospital.endpoint.gateway.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * GtClientDetails entity. @author MyEclipse Persistence Tools
 */
@ApiModel(description = "")
public class GcClientDetailsModel{
    // Fields
    @ApiModelProperty(value = "appId", required = false, access = "response")
    private String appId;
    @ApiModelProperty(value = "appSecret", required = false, access = "response")
    private String appSecret;
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getAppSecret() {
        return appSecret;
    }
    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }
}

+ 51 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/GcTokenModel.java

@ -0,0 +1,51 @@
package com.yihu.jw.hospital.endpoint.gateway.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
/**
 * Created by chenweida on 2017/8/17.
 */
@ApiModel(description = "")
public class GcTokenModel {
    @ApiModelProperty(value = "请求凭证", required = false, access = "response")
    private String accesstoken;
    @ApiModelProperty(value = "创建时间", required = false, access = "response")
    private Date createTime;
    @ApiModelProperty(value = "过期时间", required = false, access = "response")
    private Long outTime;
    public String getAccesstoken() {
        return accesstoken;
    }
    public void setAccesstoken(String accesstoken) {
        this.accesstoken = accesstoken;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    /*public Date getOutTime() {
        return outTime;
    }
    public void setOutTime(Date outTime) {
        this.outTime = outTime;
    }*/
    public Long getOutTime() {
        return outTime;
    }
    public void setOutTime(Long outTime) {
        this.outTime = outTime;
    }
}

+ 39 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/endpoint/gateway/model/ResultOneModel.java

@ -0,0 +1,39 @@
package com.yihu.jw.hospital.endpoint.gateway.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by chenweida on 2017/8/17.
 * 对外放回的实体
 */
@ApiModel("返回的实体类")
public class ResultOneModel<T> extends BaseResultModel {
    @ApiModelProperty(value = "返回数据", required = false, access = "response")
    private T result;
    public T getResult() {
        return result;
    }
    public void setResult(T result) {
        this.result = result;
    }
    public ResultOneModel(T result) {
        this.result = result;
    }
    public ResultOneModel() {
    }
    public ResultOneModel(Integer code, String message) {
        super(code, message);
    }
    public ResultOneModel(Integer status, String message, T result) {
        super(status, message);
        this.result = result;
    }
}

+ 38 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/CrosXssFilter.java

@ -0,0 +1,38 @@
package com.yihu.jw.hospital.interceptor;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
 * Created by yeshijie on 2020/9/2.
 */
//@WebFilter(filterName = "CrosXssFilter", urlPatterns = { "/*" })
public class CrosXssFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CrosXssFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //sql,xss过滤
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        logger.info("CrosXssFilter.......orignal url:{},ParameterMap:{}",httpServletRequest.getRequestURI(), JSONObject.toJSONString(httpServletRequest.getParameterMap()));
        XssHttpServletRequestWrapper xssHttpServletRequestWrapper=new XssHttpServletRequestWrapper(
                httpServletRequest);
        chain.doFilter(xssHttpServletRequestWrapper, response);
        logger.info("CrosXssFilter..........doFilter url:{},ParameterMap:{}",xssHttpServletRequestWrapper.getRequestURI(), JSONObject.toJSONString(xssHttpServletRequestWrapper.getParameterMap()));
    }
    @Override
    public void destroy() {
    }
}

+ 164 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/GateWayInterceptor.java

@ -0,0 +1,164 @@
package com.yihu.jw.hospital.interceptor;
/**
 * Created by chenweida on 2017/8/17.
 */
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.iot.gateway.GcHttpLog;
import com.yihu.jw.entity.iot.gateway.GcToken;
import com.yihu.jw.gateway.dao.GcHttpLogDao;
import com.yihu.jw.gateway.dao.GcTokenDao;
import com.yihu.jw.hospital.endpoint.gateway.model.BaseResultModel;
import com.yihu.jw.util.common.IpUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
 * 对外的请求拦截
 */
@Component
public class GateWayInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(GateWayInterceptor.class);
    @Autowired
    private GcTokenDao gcTokenDaoDao;
    public static String status = "1";
    @Autowired
    private GcHttpLogDao httpLogDao;
    /**
     * preHandle:预处理回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        String accesstoken = request.getHeader("accesstoken");
        String ip = IpUtil.getIpAddress(request);
        //********************************判断accesstoken********************************
        try {
            if (org.springframework.util.StringUtils.isEmpty(accesstoken)) {
                saveHttpLog(ip, JSONObject.toJSONString(request.getParameterMap()), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_null.getMessage());
                //没权限
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_null.getCode(), BaseResultModel.statusEm.token_null.getMessage());
                response.getOutputStream().write(JSONObject.toJSONString(baseResultModel).getBytes());
                flag = false;
            }
            GcToken gcToken = gcTokenDaoDao.findByToken(accesstoken);
            if (gcToken == null) {
                saveHttpLog(ip, JSONObject.toJSONString(request.getParameterMap()), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_no_power.getMessage());
                //没权限
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_no_power.getCode(), BaseResultModel.statusEm.token_no_power.getMessage());
                response.getOutputStream().write(JSONObject.toJSONString(baseResultModel).getBytes());
                flag = false;
            }
            if (gcToken.getDel() == null || gcToken.getDel() == 0) {
                saveHttpLog(ip, JSONObject.toJSONString(request.getParameterMap()), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_out_effect.getMessage());
                //token无效
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_out_effect.getCode(), BaseResultModel.statusEm.token_out_effect.getMessage());
                response.getOutputStream().write(JSONObject.toJSONString(baseResultModel).getBytes());
                flag = false;
            }
            if (System.currentTimeMillis() > gcToken.getOutTime().getTime()) {
                saveHttpLog(ip, JSONObject.toJSONString(request.getParameterMap()), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), BaseResultModel.statusEm.token_out_time.getMessage());
                //token过期
                BaseResultModel baseResultModel = new BaseResultModel(BaseResultModel.statusEm.token_out_time.getCode(), BaseResultModel.statusEm.token_out_time.getMessage());
                response.getOutputStream().write(JSONObject.toJSONString(baseResultModel).getBytes());
                flag = false;
            }
        } catch (Exception e) {
            saveHttpLog(ip, JSONObject.toJSONString(request.getParameterMap()), null, accesstoken, request.getRequestURI(), GcHttpLog.flagEm.error.getCode(), e.getMessage());
            return false;
        }
        //********************************判断accesstoken********************************
        return flag;
    }
    /**
     * 后处理回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String output = "";
        if (modelAndView != null) {
            output = JSONObject.toJSONString(modelAndView.getModelMap());
        } else {
            Object returnObj = request.getAttribute("returnObj");
            if (returnObj != null) {
                output = JSONObject.toJSONString(returnObj);
            }
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        response.getOutputStream()
        String token = request.getHeader("accesstoken");
        String ip = IpUtil.getIpAddress(request);
        saveHttpLog(ip,
                JSONObject.toJSONString(request.getParameterMap()),
                output,
                token,
                request.getRequestURI(),
                GcHttpLog.flagEm.success.getCode(),
                null);
    }
    /**
     * 整个请求处理完毕回调方法
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
    public void saveHttpLog(String ip, String input, String output, String token, String method, Integer flag, String message) {
        GcHttpLog gcHttpLog = new GcHttpLog();
        gcHttpLog.setCreateTime(new Date());
        gcHttpLog.setIp(ip);
        gcHttpLog.setInput(input);
        if(StringUtils.isNotEmpty(output)&&output.length() > 3000) {
            output = output.substring(0, 3000);
        }
        gcHttpLog.setOutput(output);
        gcHttpLog.setToken(token);
        gcHttpLog.setMethod(method);
        gcHttpLog.setFlag(flag);
        gcHttpLog.setMessage(message);
        httpLogDao.save(gcHttpLog);
    }
    public String getStatus() {
        return status;
    }
}

+ 120 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/interceptor/XssHttpServletRequestWrapper.java

@ -0,0 +1,120 @@
package com.yihu.jw.hospital.interceptor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
 * Created by yeshijie on 2020/9/1.
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final Logger log = LoggerFactory.getLogger(getClass());
    private static String key = "select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|*|%";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString="INVALID";
    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }
    private String currentUrl;
    public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
        currentUrl = servletRequest.getRequestURI();
    }
    /**覆盖getParameter方法,将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
     * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
     */
    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }
    @Override
    public Map<String, String[]> getParameterMap(){
        Map<String, String[]> values=super.getParameterMap();
        if (values == null) {
            return null;
        }
        Map<String, String[]> result=new HashMap<>();
        for(String key:values.keySet()){
            String encodedKey=cleanXSS(key);
            int count=values.get(key).length;
            String[] encodedValues = new String[count];
            for (int i = 0; i < count; i++){
                encodedValues[i]=cleanXSS(values.get(key)[i]);
            }
            result.put(encodedKey,encodedValues);
        }
        return result;
    }
    /**
     * 覆盖getHeader方法,将参数名和参数值都做xss过滤。
     * 如果需要获得原始的值,则通过super.getHeaders(name)来获取
     * getHeaderNames 也可能需要覆盖
     */
    @Override
    public String getHeader(String name) {
//        String value = super.getHeader(name);
//        if (value == null) {
//            return null;
//        }
//        return cleanXSS(value);
        return super.getHeader(name);
    }
    private String cleanXSS(String valueP) {
        // You'll need to remove the spaces from the html entities below
        String value = valueP.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        value = cleanSqlKeyWords(value);
        return value;
    }
    private String cleanSqlKeyWords(String value) {
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            if (paramValue.length() > keyword.length() + 4
                    && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
                log.error(this.currentUrl + "已被过滤,因为参数中包含不允许sql的关键词(" + keyword
                        + ")"+";参数:"+value+";过滤后的参数:"+paramValue);
            }
        }
        return paramValue;
    }
}

+ 1856 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java

@ -0,0 +1,1856 @@
package com.yihu.jw.hospital.module.consult.controller;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.message.MessageNoticeSetting;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 患者端:三师咨询控制类
 *
 * @author George
 */
@RestController
@RequestMapping(value = "/patient/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = {RequestMethod.GET, RequestMethod.POST})
@Api(description = "患者端-患者咨询")
public class ConsultController extends EnvelopRestEndpoint {
    @Autowired
    private ConsultTeamService consultTeamService;
    //    @Autowired
//    private DoctorCommentService doctorCommentService;
//    @Autowired
//    private DoctorStatisticsService doctorStatisticsService;
    @Autowired
    private BaseDoctorInfoService doctorService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private CommonUtil CommonUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private ConsultDao consultDao;
    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private MessageService messageService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${im.data_base_name}")
    private String im;
    @Value("${spring.profiles}")
    private String springProfile;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PrescriptionDiagnosisService prescriptionDiagnosisService;
//    @Autowired
//    private ExaminationDao examinationDao;
//    @Autowired
//    private WlyyDynamicMessagesDao dynamicMessagesDao;
//    @ApiOperation("testRedis")
//    @RequestMapping(value = "testRedis",method = RequestMethod.POST)
//    public String testRedis(){
//        try{
//            String redis_key = "REDIS_KEY_REPLACER";
//            String Topics ="sessions:REDIS_KEY_REPLACER:topics";
//            String Topic= "topics:REDIS_KEY_REPLACER";
//            String Messages= "sessions:REDIS_KEY_REPLACER:messages";
//            String MessagesByTimestamp= "sessions:REDIS_KEY_REPLACER:messages_by_timestamp";
//            String sessionId = "0fab4dd67e074e16ac86db6b6c15233e_7e3da9605d064b4fa0aacca95cf683b3_2";
//
//            String setKey = Messages.replace(redis_key,sessionId);
//            System.out.println(setKey);
//            long l1= redisTemplate.boundZSetOps(setKey).zCard();
//            Set<String> range = redisTemplate.boundZSetOps(setKey).range(0, -1);
//            System.out.println(l1);
//            System.out.println(range.size());
//            return success("testRedis");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return error(-1,"挂断失败");
//    }
//    @RequestMapping(value = "sendVideoCommunication")
//    @ApiOperation("居民发起视频通讯")
//    public String sendVideoCommunication(@ApiParam(name = "patient", value = "居民code")
//                                         @RequestParam(value = "patient", required = true) String patient,
//                                         @ApiParam(name = "consult", value = "咨询code")
//                                         @RequestParam(value = "consult", required = true) String consult,
//                                         @ApiParam(name = "doctor", value = "医生code")
//                                         @RequestParam(value = "doctor", required = true) String doctor,
//                                         @ApiParam(name = "sessionId", value = "会话id")
//                                         @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);
//            if (consultTeam.getStatus() != 0) {
//                return error(-1, "该咨询已结束,无法发起视频通讯!");
//            }
//
///*            BaseDoctorDO d = doctorDao.findByCode(doctor);
//            if(d.getVideoStauts()!=null&&d.getVideoStauts()==1){
//                return error(-1, "医生在视频通讯中,无法发起视频通讯!");
//            }*/
//
//            BasePatientDO p = patientDao.findByCode(patient);
//
//            JSONObject message = new JSONObject();
//            JSONObject content = new JSONObject();
//            content.put("patient", patient);
//            content.put("patientName", p.getName());
//            content.put("consult", consult);
//            content.put("sessionId", sessionId);
//            content.put("patientName", p.getName());
//            content.put("photo", p.getPhoto());
//            message.put("id", getUID());
//            message.put("sender_id", p.getCode());
//            message.put("session_id", "system");
//            message.put("sender_name", p.getName());
//            message.put("content_type", 40);
//            message.put("timestamp", DateUtil.getStringDate());
//            message.put("content", content);
//
//            String response = imUtill.sendVideoCommunication(doctor, message.toString());
//            JSONObject jsonObject = new JSONObject(response);
//            if (1 == jsonObject.getInt("status")) {
//                return error(-1, "医生不在线无法发起视频通讯!");
//            }
////            d.setVideoStauts(1);
////            doctorDao.save(d);
//            return success("发起成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "发起失败!");
//    }
//    @ApiOperation("居民取消视频")
//    @RequestMapping(value = "cancelVideo", method = RequestMethod.POST)
//    public String cancelVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor,
//                              @ApiParam(name = "sessionId", value = "会话id")
//                              @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            BaseDoctorDO d = doctorDao.findByCode(doctor);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            BasePatientDO p = patientDao.findByCode(getUID());
//
//            JSONObject message = new JSONObject();
//            JSONObject content = new JSONObject();
//            content.put("patient", p.getCode());
//            content.put("patientName", p.getName());
//            content.put("consult", consult);
//            content.put("sessionId", sessionId);
//            content.put("patientName", p.getName());
//            content.put("photo", p.getPhoto());
//            message.put("id", getUID());
//            message.put("sender_id", p.getCode());
//            message.put("session_id", "system");
//            message.put("sender_name", p.getName());
//            message.put("content_type", 45);
//            message.put("timestamp", DateUtil.getStringDate());
//            message.put("content", content);
//
//            String response = imUtill.sendVideoCommunication(doctor, message.toString());
//
//            imUtill.sendTopicIM(p.getCode(), p.getName(), consult, "45", "居民取消视频通讯", null);
//            return success("取消成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "取消失败");
//    }
//    @ApiOperation("居民挂断视频")
//    @RequestMapping(value = "handUpVideo", method = RequestMethod.POST)
//    public String handUpVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor,
//                              @ApiParam(name = "time", value = "视频接通时长")
//                              @RequestParam(value = "time", required = true) String time) {
//        try {
//            BaseDoctorDO d = doctorDao.findById(doctor).orElse(null);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            BasePatientDO p = patientDao.findById(getUID()).orElse(null);
//            imUtill.sendTopicIM(p.getId(), p.getName(), consult, "44", time, null);
//            return success("挂断成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "挂断失败");
//    }
    /**
     * 患者咨询记录查询
     *
     * @param title    咨询标题
     * @param id
     * @param pagesize 分页大小
     * @return
     */
//    @RequestMapping(value = "records")
//    @ApiOperation("患者咨询记录查询")
//    public String consultRecords(
//            @RequestParam(required = false) String title,
//            long id,
//            int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByPatient(getRepUID(), id, pagesize, title);
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//
//                    json.put("teamCode", result[8]);
//
//                    json.put("evaluate", result[9]);
//
//                    //签约code
//                    json.put("signCode", result[10]);
//
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 获取医生的排班时间
     *
     * @param doctor
     * @param week
     * @return
     */
//    @RequestMapping(value = "/doctor_worktime/week")
//    @ApiOperation("获取医生的排班时间")
//    public String getDoctorWeekWorkTime(String doctor, String week) {
//        try {
//            JSONObject result = doctorWorkTimeService.findDoctorWeekWorkTime(doctor, week);
//
//            return write(200, "查询成功!", "data", result);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 获取医生某天的排班时间
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "/doctor_worktime")
//    @ApiOperation("获取医生某天的排班时间")
//    public String getDoctorWorkTime(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.findDoctorWorkTime(doctor);
//
//            return write(200, "查询成功!", "data", result);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 医生是否在工作
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "is_doctor_working")
//    @ApiOperation("医生是否在工作")
//    public String isDoctorAtWorking(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isDoctorWorking(doctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 患者端在发起家庭医生咨询时检查全科医生和健管师是否在工作
     *
     * @param doctor
     * @param healthDoctor
     * @return
     */
//    @RequestMapping(value = "isDoctorWorkWhenconsult", method = RequestMethod.POST)
//    @ApiOperation("全科医生和健管师是否在工作")
//    public String isDoctorWorkWhenconsult(String doctor, String healthDoctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isDoctorWorkingWhenConsult(doctor, healthDoctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 名医是否在工作
     *
     * @param doctor
     * @return
     */
//    @RequestMapping(value = "is_famous_doctor_working")
//    @ApiOperation("名医是否在工作")
//    public String isFamousDoctorAtWorking(String doctor) {
//        try {
//            JSONObject result = doctorWorkTimeService.isFamousDoctorWorking(doctor);
//            return write(200, result.getString("msg"), "data", result.getString("status"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 名医咨询剩余次数查询
     *
     * @param doctor
     * @return
     */
//    @ApiOperation("名医咨询剩余次数查询")
//    @RequestMapping(value = "/consult_times_remain")
//    public String famousDoctorTimesRemain(String doctor) {
//        try {
//            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor);
//            return write(200, "查询成功", "data", result);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 获取未完成咨询
     *
     * @return
     */
//    @RequestMapping(value = "/unfinished")
//    @ApiOperation("获取未完成咨询")
//    public String getUnFinishedConsult() {
//        try {
//            List<ConsultTeamDo> unfinishedConsult = consultTeamService.getUnfinishedConsult(getRepUID());
//            JSONArray result = new JSONArray(unfinishedConsult);
//            return write(200, "查询成功!", "data", result);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 查询居民与某个医生是否存在未结束的咨询
     *
     * @param doctor 医生
     * @return
     */
//    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
//    @ApiOperation("查询居民与某个医生是否存在未结束的咨询")
//    public String isExistsUnfinishedConsult(@RequestParam(required = true) String doctor) {
//        try {
//            List<ConsultTeamDo> consults = consultTeamService.getUnfinishedConsult(getRepUID(), doctor);
//
//            if (consults != null && consults.size() > 0) {
//                return write(200, "查询成功", "data", consults.get(0).getConsult());
//            } else {
//                return write(200, "查询成功", "data", "");
//            }
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     * 三师咨询添加接口
     *
     * @param type     咨询类型:1三师咨询,2家庭医生咨询,18康复咨询
     * @param when     发病时间
     * @param symptoms 主要症状
     * @param images   图片URL地址,多图以逗号分隔
     * @param voice    语音URL地址
     * @param times    语音秒数,多个以逗号分隔
     * @return
     */
//    @RequestMapping(value = "add")
//    @ApiOperation("三师咨询添加接口")
//    public String add(@RequestParam(required = false) Integer type,
//                      @RequestParam(required = false) String when,
//                      @RequestParam String symptoms,
//                      @RequestParam(required = false) String images,
//                      @RequestParam(required = false) String voice,
//                      @RequestParam(required = false) String times,
//                      @RequestParam(required = false) Long guidance,
//                      @RequestParam(required = false) String teamId) {
//        try {
//            if (type == null) {
//                type = 1;
//            }
//            if (type != 1 && type != 2 && type != 18 && (StringUtils.isNoneBlank(teamId) && type == 18)) {
//                return error(-1, "无效请求!");
//            }
//
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//            }
//            // 将临时图片拷贝到正式存储路径下
//            if (StringUtils.isNotEmpty(images)) {
//                images = CommonUtil.copyTempImage(images);
//            }
//            if (StringUtils.isEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//
//            ConsultTeam consult = new ConsultTeam();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询  6.名医咨询  18,康复咨询
//            consult.setType(type);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            if (StringUtils.isBlank(symptoms)) {
//                symptoms = "患者使用语音输入描述疾病和身体状况";
//            }
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//
//            consult.setIsAuthentication(0);
//            consult.setIsRefinement(0);
//            // 设置关联咨询
//            if (guidance != null && guidance > 0) {
//                consult.setGuidance(guidance);
//            }
//
//            // 保存到数据库
//            int res = 0;
//            JSONArray dts = null;
//            synchronized (getRepUID().intern()) {//新增同步方法。设备保存写在service层但是不生效,写在controller层才生效
//                JSONObject re;
//                if (type == 18) {//康复咨询
//                    re = consultTeamService.addRecoverConsult(consult, Long.parseLong(teamId), getRepUID(), getUID(), times);
//                } else {
//                    re = consultTeamService.addTeamConsult(consult, getRepUID(), getUID(), times);
//                }
//                res = re.getInt("status");
//                dts = re.has("doctor") ? re.getJSONArray("doctor") : null;
//            }
//            if (res == -1) {
//                return error(-1, "家庭签约信息不存在或已过期,无法进行家庭医生咨询!");
//            } else if (res == -2) {
//                return error(-1, "家庭签约信息不存在或已过期,无法进行三师医生咨询!");
//            } else if (res == -3) {
//                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
//            }
//
//            // 添加到统计队列
//            if (consult.getType() == 2 || consult.getType() == 18) {
//                DoctorStatisticsTask.getInstance(doctorStatisticsService).put(consult.getDoctor(), 1, 1, 0);
//            }
//
//            // 推送消息给医生
//            if (dts == null || dts.length() == 0) {
//                if (messageService.getMessageNoticeSettingByMessageType(consult.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue())) {
//                    pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
//                    BaseDoctorDO doctor = doctorDao.findByCode(consult.getDoctor());
//                    if (doctor != null && StringUtils.isNotEmpty(doctor.getOpenid())) {
//                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                        List<NameValuePair> params = new ArrayList<>();
//                        params.add(new BasicNameValuePair("type", "4"));
//                        params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
//                        params.add(new BasicNameValuePair("url", targetUrl));
//                        params.add(new BasicNameValuePair("first", doctor.getName() + "医生您好,有患者向您发起咨询"));
//                        params.add(new BasicNameValuePair("remark", "【" + consult.getSymptoms() + "】\r\n请进入手机APP查看"));
//                        String sex = consult.getSex() == 1 ? "男" : "女";
//                        String keywords = consult.getName() + "," + sex;
//                        params.add(new BasicNameValuePair("keywords", keywords));
//
//                        httpClientUtil.post(url, params, "UTF-8");
//                    }
//                }
//            } else {
//                for (int i = 0; i < dts.length(); i++) {
//                    String doctorCode = dts.getString(i);
//                    Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
//                    if (flag) {
//                        pushMsgTask.put(doctorCode, MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
//                        BaseDoctorDO doctor = doctorDao.findByCode(doctorCode);
//
//                        if (doctor != null && StringUtils.isNotEmpty(doctor.getOpenid())) {
//                            String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                            List<NameValuePair> params = new ArrayList<>();
//                            params.add(new BasicNameValuePair("type", "4"));
//                            params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
//                            params.add(new BasicNameValuePair("url", targetUrl));
//                            params.add(new BasicNameValuePair("first", doctor.getName() + "医生您好,有患者向您发起咨询"));
//                            params.add(new BasicNameValuePair("remark", "【" + consult.getSymptoms() + "】\r\n请进入手机APP查看"));
//                            String sex = consult.getSex() == 1 ? "男" : "女";
//                            String keywords = consult.getName() + "," + sex;
//                            params.add(new BasicNameValuePair("keywords", keywords));
//
//                            httpClientUtil.post(url, params, "UTF-8");
//                        }
//                    }
//                }
//            }
//
//            //门户页实时动态展示,居民发起家医咨询
//            try {
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String str = simpleDateFormat.format(new Date());
//                WlyyDynamicMessages dynamicMessages = new WlyyDynamicMessages();
//                dynamicMessages.setCreateTime(str);//当前时间
//                BasePatientDO patient = patientDao.findByCode(getUID());
//                dynamicMessages.setName(patient.getName());//居民姓名
//                String str1 = "发起咨询";
//                dynamicMessages.setCode(patient.getCode());
//                dynamicMessages.setCodeType("2");
//                dynamicMessages.setResult(str1);
//                dynamicMessages.setAddress(patient.getAddress());//居民地址
//                dynamicMessagesDao.save(dynamicMessages);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//    @RequestMapping(value = "intoTopic", method = RequestMethod.POST)
//    @ApiOperation("进入咨询")
//    public String intoTopic(@RequestParam(required = true) String consult) {
//        try {
//            int result = consultTeamService.intoTopic(consult, getRepUID(), getUID());
//            if (result == -1) {
//                return error(-1, "该咨询不是进行中");
//            }
//            JSONObject json = new JSONObject();
//            json.put("consult", consult);
//            json.put("content", "进入咨询");
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getUID(), getRepUID(), json);
//            return success("进入成功");
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "请求失败");
//        }
//    }
    /**
     * 名医咨询添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param images     图片URL地址,多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
//    @RequestMapping(value = "famousAdd")
//    @ApiOperation("名医咨询添加接口")
//    public String famousAdd(
//            @RequestParam(required = false) String when,
//            String symptoms,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            //判断医生是否是在工作时间
//            JSONObject jo = doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
//            if (!jo.get("status").equals("1")) {
//                return error(-1, jo.get("msg").toString());
//            }
//            //判断医生是否剩下咨询次数
//            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctorCode);
//            if (result == 0) {
//                return error(-1, "没有次数");
//            }
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//            }
//            // 将临时图片拷贝到正式存储路径下
//            if (StringUtils.isNotEmpty(images)) {
//                images = CommonUtil.copyTempImage(images);
//            }
//            if (StringUtils.isEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//            //判断是否已经存在还没有关闭的咨询
//            if (consultTeamService.isExistConsult(getRepUID(), doctorCode)) {
//                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
//            }
//            ConsultTeam consult = new ConsultTeam();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.名医咨询
//            consult.setType(6);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            JSONObject object = consultTeamService.famousConsult(consult, getRepUID(), "1", getUID());
//            JSONObject resultConsult = new JSONObject(consult);
//            resultConsult.put("session_id", object.getString("session_id"));
//            //名医咨询次数减一
//            doctorWorkTimeService.setDoctorCurrentConsultTimesRemain(doctorCode);
//            // 推送消息给医生
//            pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_03.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", resultConsult);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
    /**
     * 名医列表
     *
     * @return
     */
//    @RequestMapping(value = "famousDoctorList")
//    @ApiOperation("名医列表")
//    public String famousDoctorList(
//            @RequestParam(required = false) String name) {
//        try {
//            JSONArray array = new JSONArray();
//            List<Doctor> list = doctorService.famousDoctorList(name);
//            if (list != null) {
//                for (BaseDoctorDO doctor : list) {
//                    if (doctor == null) {
//                        continue;
//                    }
//
//                    // 判断名医是否在工作
//                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(doctor.getCode());
//
//                    if (isWorking == null || !isWorking.getString("status").equals("1")) {
//                        continue;
//                    }
//
//                    int num = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode());
//
//                    if (num < 1) {
//                        continue;
//                    }
//
//                    JSONObject json = new JSONObject();
//                    json.put("id", doctor.getId());
//                    // 医生标识
//                    json.put("code", doctor.getCode());
//                    // 医生性别
//                    json.put("sex", doctor.getSex());
//                    // 医生姓名
//                    json.put("name", doctor.getName());
//                    // 所在医院名称
//                    json.put("hospital", doctor.getHospital());
//                    // 所在医院名称
//                    json.put("hospital_name", doctor.getHospitalName());
//                    // 科室名称
//                    json.put("dept_name", (doctor.getDeptName() == null ||
//                            StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
//                    // 职称名称
//                    json.put("job_name", (doctor.getJobName() == null ||
//                            StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
//                    // 头像
//                    json.put("photo", doctor.getPhoto());
//                    // 简介
//                    json.put("introduce", doctor.getIntroduce());
//                    // 专长
//                    json.put("expertise", doctor.getExpertise());
//                    // 剩余咨询次数
//                    json.put("num", num);
//                    array.put(json);
//                }
//            }
//            return write(200, "获取医院医生列表成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "获取医院医生列表失败!");
//        }
//    }
//    @RequestMapping(value = "status")
//    public String status(String consult) {
//        try {
//            ConsultTeam ct = consultTeamService.findByCode(consult);
//            if (ct == null) {
//                return error(-1, "获取状态失败!");
//            } else {
//                return write(200, "获取状态成功!", "data", ct.getStatus());
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "获取状态失败!");
//        }
//    }
//    @RequestMapping(value = "evaluateStatus")
////    public String statuss(String consult) {
////        try {
////            ConsultTeam ct = consultTeamService.findByCode(consult);
////            if (ct == null) {
////                return error(-1, "获取状态失败!");
////            } else {
////                return write(200, "获取状态成功!", "data", ct.getEvaluate());
////            }
////        } catch (Exception e) {
////            error(e);
////            return invalidUserException(e, -1, "获取状态失败!");
////        }
////    }
    /**
     * 查询患者三师咨询咨询列表
     *
     * @param status   咨询状态(0未结束,1已结束,-1 已取消)
     * @param pagesize 页数
     * @return 查询结果
     */
//    @RequestMapping(value = "list")
//    @ApiOperation("查询患者三师咨询咨询列表")
//    public String list(int status, long id, int pagesize) {
//        try {
//            Page<ConsultTeam> consults = consultTeamService.findByPatient(getRepUID(), status, id, pagesize);
//            JSONArray jsonArray = new JSONArray();
//            if (consults != null) {
//                for (ConsultTeam consult : consults) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", consult.getId());
//                    // 设置咨询标志
//                    json.put("code", consult.getConsult());
//                    // 设置咨询类型:0公共咨询,1指定医生,2三师咨询
//                    json.put("type", consult.getType());
//                    // 设置标题
//                    json.put("title", consult.getSymptoms());
//                    // 设置发病时间
//                    json.put("when", consult.getWhen());
//                    // 设置患者未读数量
//                    json.put("patientRead", consult.getPatientRead());
//                    // 设置状态
//                    json.put("status", consult.getStatus());
//                    // 设置患者评价标识
//                    json.put("comment", consult.getComment());
//                    // 设置关联指导
//                    json.put("guidance", consult.getGuidance());
//                    // 设置咨询或回复时间
//                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    jsonArray.put(json);
//                }
//            }
//            return write(200, "查询成功", "list", jsonArray);
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
    /**
     * 患者取消三师咨询
     *
     * @param consult
     * @return
     */
//    @RequestMapping(value = "cancel")
//    @ApiOperation("患者取消三师咨询")
//    public String cancel(String consult) {
//        try {
//            int row = consultTeamService.cancel(consult);
//            if (row > 0) {
//                return success("咨询已取消!");
//            } else {
//                return error(-1, "咨询不能取消!");
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "操作失败!");
//        }
//    }
    /**
     * 修改状态为1的咨询记录为结束
     *
     * @param code 咨询标识
     * @return
     */
//    @RequestMapping(value = "finish")
//    @ApiOperation("修改状态为1的咨询记录为结束")
//    public String finish(@RequestParam(required = true) String code) {
//        try {
//            int row = consultTeamService.finishConsult(code, getRepUID(), 1);
//            if (row > 0) {
//                return success("操作成功!");
//            } else if (row == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "操作失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "操作失败!");
//        }
//    }
//    @RequestMapping(value = "imAppend")
//    @ApiOperation("im会话回复通用接口")
//    public String imAppend(
//            @RequestParam String sessionId,
//            @RequestParam String content,
//            @RequestParam String senderId,
//            @RequestParam String senderName,
//            @RequestParam int type,
//            @RequestParam(required = false, defaultValue = "0") Integer times) {
//        try {
//            if (type == 3) {
//                String path = fetchWxVoices();
//                JSONObject obj = new JSONObject();
//                // 将临时语音拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(path)) {
//                    content = CommonUtil.copyTempVoice(path);
//                    obj.put("path", content);
//                    obj.put("times", times);
//                    content = obj.toString();
//                }
//            } else if (type == 2) {
//                if (!"laprod".equals(springProfile)) {
//                    // 图片消息
//                    content = fetchWxImages();
//                    // 将临时图片拷贝到正式存储路径下
//                    if (StringUtils.isNotEmpty(content)) {
//                        content = CommonUtil.copyTempImage(content);
//                    }
//                    if (StringUtils.isEmpty(content)) {
//                        return error(-1, "图片上传失败!");
//                    }
//                }
//            }
//
//            imUtill.sendImMsg(senderId, senderName, sessionId, type + "", content, "1");
//            return success("成功!");
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "失败!");
//        }
//    }
    /**
     * 三师咨询追问接口
     *
     * @param consult 咨询标识
     * @param content 追问内容
     * @param type    追问内容类型:1文字,2图片,3语音  ... (im消息类型)
     * @return
     */
    @RequestMapping(value = "append")
    @ApiOperation("三师咨询追问接口")
    public String append(
            @RequestParam String consult,
            @RequestParam String content,
            @RequestParam int type,
            @RequestParam(required = false, defaultValue = "0") Integer times) {
        try {
            List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在!");
            }
            if (consultModel.getEndMsgId() != null) {
                return error(-1, "咨询已结束");
            }
            String[] arr = null;
            if (type == 3) {
                //获取微信服务器图片
//                String path = fetchWxVoices();
                String path = null;//这边后面在搬
                JSONObject obj = new JSONObject();
                // 将临时语音拷贝到正式存储路径下
                if (StringUtils.isNotEmpty(path)) {
                    content = CommonUtil.copyTempVoice(path);
                    obj.put("path", content);
                    obj.put("times", times);
                    content = obj.toString();
                }
                ConsultTeamLogDo log = new ConsultTeamLogDo();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);
            } else if (type == 2) {
                if (!"laprod".equals(springProfile)) {
                    // 图片消息 -获取微信服务器图片
//                    content = fetchWxImages();
                    String path = null;//这边后面在搬
                    // 将临时图片拷贝到正式存储路径下
                    if (StringUtils.isNotEmpty(content)) {
                        content = CommonUtil.copyTempImage(content);
                    }
                    if (StringUtils.isEmpty(content)) {
                        return error(-1, "图片上传失败!");
                    }
                }
                String[] images = content.split(",");
                for (String image : images) {
                    ConsultTeamLogDo log = new ConsultTeamLogDo();
                    log.setConsult(consult);
                    log.setContent(image);
                    log.setDel("1");
                    log.setChatType(type);
                    log.setType(type);
                    logs.add(log);
                }
            } else {
                ConsultTeamLogDo log = new ConsultTeamLogDo();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);
                arr = new String[]{content};
            }
            BasePatientDO patient = patientDao.findById(getRepUID());
            int i = 0;
            List<String> failed = new ArrayList<>();
            String agent = getUID() == getRepUID() ? null : getUID();
            for (ConsultTeamLogDo log : logs) {
                String response = imUtill.sendTopicIM(getRepUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent(), agent);
                if (StringUtils.isNotEmpty(response)) {
                    JSONObject resObj = new JSONObject(response);
                    if (resObj.getInt("status") == -1) {
                        String msg = resObj.getString("message") + "追问失败!" + resObj.getString("message");
                        return msg;
                    }
                    failed.add(String.valueOf(resObj.get("data")));
                    try {
                        String sql = "";
                        if (consultModel.getType() == 2) {
                            //家庭咨询
                            sql = "SELECT t.participant_id FROM " + im +
                                    ".participants t where t.session_id = '" +
                                    patient.getId() + "_" + consultModel.getTeam() + "_" + consultModel.getType() +
                                    "' and t.participant_role = 0";
                        } else if (consultModel.getType() == 8 || consultModel.getType() == 9 || consultModel.getType() == 11) {
                            //8-续方咨询 9-在线复诊咨询 11-上门预约服务
                            sql = "SELECT t.participant_id FROM " + im +
                                    ".participants t where t.session_id = '" +
                                    patient.getId() + "_" + consultModel.getConsult() + "_" + consultModel.getType() +
                                    "' and t.participant_role = 0";
                        } else if (consultModel.getType() == 18) {
                            //康复咨询
                            sql = "SELECT t.participant_id FROM " + im +
                                    ".participants t where t.session_id = '(SELECT session_id from " + im + ".topics WHERE id='" + consultModel.getConsult() + "')' and t.participant_role = 0";
                        }
                        if (StringUtils.isEmpty(sql)) {
                            return write(-1, "追问失败!", "data", "不存在该类型!【type】:" + type);
                        }
                        List<Map<String, Object>> participants = jdbcTemplate.queryForList(sql);
                        for (Map<String, Object> participant : participants) {
//                          //有居民、健管、全科
                            String doctorCode = participant.get("participant_id").toString();
                            if (doctorCode.equals(patient.getId())) {
                                continue;
                            }
                            //健管
                            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
                            //全科
//                            Boolean flag2 = !messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue());
                            if (flag) {
                                //            新增发送医生助手模板消息 v1.4.0 by wujunjie
                                BaseDoctorDO doctor = doctorDao.findById(doctorCode);
                                String doctorOpenID = doctor.getOpenid();
                                if (StringUtils.isNotEmpty(doctorOpenID)) {
                                    String title = "";
                                    ConsultDo consultSingle = consultDao.findByCode(log.getConsult());
                                    if (consultSingle != null) {
                                        Integer singleType = consultSingle.getType();
                                        if (singleType != null && singleType == 8) {
                                            title = consultSingle.getTitle();
                                        } else if (singleType != null && singleType != 8) {
                                            title = consultSingle.getSymptoms();
                                        }
                                        String repContent = parseContentType(type + "", content);
                                        String first = "居民" + patient.getName() + "的咨询有新的回复。";
                                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
                                        List<NameValuePair> params = new ArrayList<>();
                                        params.add(new BasicNameValuePair("type", "8"));
                                        params.add(new BasicNameValuePair("openId", doctorOpenID));
                                        params.add(new BasicNameValuePair("url", targetUrl));
                                        params.add(new BasicNameValuePair("first", first));
                                        params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
                                        String keywords = title + "," + repContent + "," + doctor.getName();
                                        params.add(new BasicNameValuePair("keywords", keywords));
                                        httpClientUtil.post(url, params, "UTF-8");
                                        System.out.println("发送对象:" + doctorCode);
                                        System.out.println("发送对象名字:" + doctor.getName());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return write(200, "追问成功!", "data", failed);
        } catch (Exception e) {
            error(e);
            return ("追问失败!" + e.getMessage());
        }
    }
    /**
     * 获取医生评价列表
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
//    @GetMapping(value = "loglist2")
//    @ApiOperation("获取医生评价列表")
//    public String loglist2(@RequestParam String consult, @RequestParam int page, @RequestParam int pagesize) {
//        try {
//            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
//            if (consultModel == null) {
//                return error(-1, "咨询记录不存在!");
//            }
//            JSONObject messageObj = imUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, getRepUID());
//
//            //过滤续签
//            consultTeamService.removeRenewPerson(messageObj, getRepUID());
//            //过滤非本次咨询专科医生
//            consultTeamService.removeSpecialist(messageObj, getRepUID(), consult);
//
//            return write(200, "查询成功", "list", messageObj);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     * @return
     */
//    @RequestMapping(value = "loglist")
//    @ApiOperation("网络咨询咨询日志查询")
//    public String loglist(@RequestParam String consult, @RequestParam int page, @RequestParam int pagesize) {
//        try {
//            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
//            if (consultModel == null) {
//                return error(-1, "咨询记录不存在!");
//            }
//            JSONObject messageObj = imUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, getRepUID());
//
//            //过滤续签
//            consultTeamService.removeRenewPerson(messageObj, getRepUID());
//
//            return write(200, "查询成功", "list", messageObj);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param pagesize 每页显示数,默认为10
     * @return
     */
//    @RequestMapping(value = "logs")
//    @ApiOperation("网络咨询咨询日志查询")
//    public String logs(@RequestParam String sessionId, @RequestParam(required = false) String startMsgId, @RequestParam(required = false) String endMsgId, @RequestParam int page, @RequestParam int pagesize) {
//        try {
//            JSONArray messageArray = imUtill.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getRepUID());
//            return write(200, "查询成功", "list", messageArray);
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "participants")
//    public String participants(@RequestParam String sessionId) {
//        try {
//            JSONArray participants = imUtill.getSessionsParticipants(sessionId);
//
//            //过滤续签
//            consultTeamService.removeRenewPerson(participants, getRepUID());
//
//            return write(200, "查询成功", "list", participants);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 查找单个咨询记录
     *
     * @param consult 咨询标识
     * @param logId   记录标识
     * @return
     */
//    @RequestMapping(value = "oneLog")
//    @ApiOperation("查找单个咨询记录")
//    public String oneLog(@RequestParam String consult, @RequestParam Long logId, @RequestParam int msgType) {
//        try {
//            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
//            if (consultModel == null) {
//                return error(-1, "咨询记录不存在!");
//            }
//
//            String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
//                    + "api/v1/chats/message";
//            String reG = httpUtil.sendGet(url, "id=" + logId + "&type=" + msgType);
//            JSONObject obj = null;
//            if (!org.springframework.util.StringUtils.isEmpty(reG)) {
//                obj = new JSONObject(new String(reG.getBytes(), "utf-8"));
//            } else {
//                return error(-1, "查询失败");
//            }
//
//            if (obj == null) {
//                return error(-1, "查询失败");
//            }
//
//            JSONObject json = new JSONObject();
//
//            json.put("id", obj.getInt("id"));
//            if (!obj.getString("from").equals(getRepUID())) {
//                BaseDoctorDO doc = doctorService.findDoctorByCode(obj.getString("from"));
//                // 设置回复医生姓名
//                json.put("doctorName", doc.getName());
//                json.put("photo", doc.getPhoto());
//            } else {
//                BasePatientDO p = patientDao.findByCode(obj.getString("from"));
//                // 设置回复医生姓名
//                json.put("doctorName", p.getName());
//                json.put("photo", p.getPhoto());
//            }
//
//            // 设置回复内容
//            json.put("content", obj.getString("content"));
//            // 设置咨询或回复时间
//            json.put("time", DateUtil.dateToStr(new Date(obj.getLong("timestamp")), DateUtil.YYYY_MM_DD_HH_MM_SS));
//            // 设置记录类型:1文字,2图片,3语音
//            json.put("msgType", obj.getInt("contentType"));
//            // 设置类型:0患者问,1医生回复,2患者追问,3患者评价
//            if (!obj.getString("from").equals(getRepUID())) {
//                json.put("type", 1);
//            } else {
//                json.put("type", obj.getInt("contentType") == 6 ? 0 : 2);
//            }
//
//            // 返回结果
//            return write(200, "查询成功", "consult", json);
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
    /**
     * 三师咨询评论
     *
     * @param consult 咨询标识
     * @param content 评价内容
     * @param star    星级
     * @return 操作结果
     */
//    @RequestMapping(value = "comment")
//    @ApiOperation("三师咨询评论")
//    public String comment(String consult, String content, int star) {
//        try {
//            // 保存评价
//            JSONArray array = doctorCommentService.consultComment(getRepUID(), consult, content, star, 2);
//            // 添加到统计队列
//            if (array != null) {
//                //新增判断 续方咨询暂不统计
//                ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//                if (consultTeam.getType() != 8) {
//                    DoctorStatisticsTask.getInstance(doctorStatisticsService).put(array);
//                }
//            }
//            // 添加评价记录
//            ConsultTeamLogDo log = new ConsultTeamLogDo();
//            log.setConsult(consult);
//            log.setContent(content);
//            log.setChatType(1);
//            log.setDel("1");
//            log.setType(3);
//            log = consultTeamService.reply(log, getRepUID(), null, log.getType());
//            return success("感谢您的评价!");
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "评价失败!");
//        }
//
//    }
//    @RequestMapping(value = "getTopic")
//    public String getTopic(String consult) {
//        try {
//            return success(imUtill.getTopic(consult).get("data").toString());
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, e.getMessage());
//        }
//    }
//    @RequestMapping(value = "getConsult")
//    public String getConsult(String consult) {
//        try {
//            ConsultTeam consultTeam = consultTeamService.findByConsultCode(consult);
//            return write(200, "查询成功", "data", consultTeam);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, e.getMessage());
//        }
//    }
    /*===========================================续方咨询==============================================================*/
//    @RequestMapping(value = "isPrescriptionConsult", method = RequestMethod.GET)
//    @ApiOperation("是否可以续方咨询")
//    public String isPrescriptConsult(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            JSONObject json = consultTeamService.isPrescriptConsult(patient);
//            if (json.has("msg")) {
//                return error(-1, json.getString("msg"));
//            }
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
//    @RequestMapping(value = "addPrescriptionConsult", method = RequestMethod.POST)
//    @ApiOperation("添加续方咨询")
//    public String addPrescriptionConsult(@ApiParam(name = "jwCode", value = "基位处方code", defaultValue = "10")
//                                         @RequestParam(value = "jwCode", required = true) String jwCode,
//                                         @ApiParam(name = "doctor", value = "咨询医生(开方医生、审核医生)", defaultValue = "86225d1365e711e69f7c005056850d66")
//                                         @RequestParam(value = "doctor", required = true) String doctor,
//                                         @ApiParam(name = "type", value = "咨询类型(1、高血压-续方咨询;2、糖尿病-续方咨询,3、高糖-续方咨询 4、其他疾病咨询)", defaultValue = "1")
//                                         @RequestParam(value = "type", required = true) Integer type,
//                                         @ApiParam(name = "adminTeamId", value = "签约行政团队id", defaultValue = "224")
//                                         @RequestParam(value = "adminTeamId", required = true) Long adminTeamId,
//                                         @ApiParam(name = "reason", value = "续方说明", defaultValue = "续方申请")
//                                         @RequestParam(value = "reason", required = false) String reason,
//                                         @ApiParam(name = "signTag", value = "0为家签续方,1未非家签约", defaultValue = "0")
//                                         @RequestParam(value = "signTag", required = false) Integer signTag,
//                                         @ApiParam(name = "hospital", value = "机构CODE")
//                                         @RequestParam(value = "hospital", required = false) String hospital,
//                                         @ApiParam(name = "systolic", value = "收缩压")
//                                         @RequestParam(value = "systolic", required = false) String systolic,
//                                         @ApiParam(name = "diastolic", value = "舒张压")
//                                         @RequestParam(value = "diastolic", required = false) String diastolic,
//                                         @ApiParam(name = "bloodSugar", value = "血糖")
//                                         @RequestParam(value = "bloodSugar", required = false) String bloodSugar,
//                                         @ApiParam(name = "bloodSugarType", value = "血糖类型")
//                                         @RequestParam(value = "bloodSugarType", required = false) String bloodSugarType,
//                                         @ApiParam(name = "hospitalName", value = "机构名称")
//                                         @RequestParam(value = "hospitalName", required = false) String hospitalName,
//                                         @ApiParam(name = "ratType", value = "费别类型 zy_common_dict表IV_RATE_TYPE_DICT")
//                                         @RequestParam(value = "ratType", required = false) String ratType,
//                                         @RequestParam(required = true) @ApiParam(value = "配送方式:1 自取 2快递配送 3健管师配送 4网格员派送", name = "dispensaryType") int dispensaryType,
//                                         @RequestParam(required = true) @ApiParam(value = "配送地址json", name = "addressJson", defaultValue = "{\"townName\":\"海沧区\",\"code\":\"3502050100\",\"address\":" +
//                                                 "\"冰岛\",\"cityName\":\"厦门市\",\"townCode\":\"350205\",\"provinceCode\":\"350000\",\"cityCode\":\"350200\",\"name\":\"海沧区嵩屿街道社区卫生服务中心\"," +
//                                                 "\"provinceName\":\"福建省\",\"streeCode\":\"35020501\",\"streeName\":\"皇后大道东\",\"phone\":\"13253541190\"}") String addressJson) {
//        try {
//            ConsultTeam consult = new ConsultTeam();
//            consult.setType(8);//续方咨询
//            consult.setAdminTeamId(adminTeamId);
//
//            //增加体征数据上传发送IM消息标识:1血压 2血糖 3血压+血糖---huangwenjie 2017.11.06
//            consult.setHealthindexType(type);
//            // 保存到数据库
//            int res = 0;
//            synchronized (jwCode.intern()) {
//                res = consultTeamService.addPrescriptionConsult(jwCode, getRepUID(), getUID(), doctor, consult, reason, type,
//                        addressJson, dispensaryType, signTag, hospital, hospitalName, adminTeamId, systolic, diastolic, bloodSugar, bloodSugarType, ratType);
//            }
//            if (res == -1) {
//                return error(-1, "该处方存在未审核的续方,无法进行续方咨询!");
//            }
//            if (res == -2) {
//                return error(-1, "您还未签约,不能发起续方咨询!");
//            }
//            if (res == -3) {
//                return error(-1, "您当天有未完成的续方,不能发起续方咨询!");
//            }
//
//            if (messageService.getMessageNoticeSettingByMessageType(doctor, "1", MessageNoticeSetting.MessageTypeEnum.prescriptionSwitch.getValue())) {
//                // 推送消息给医生
//                pushMsgTask.put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.D_CT_05.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.续方咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_PRESCRIPTION.您有新的续方咨询.name(), consult.getConsult());
//                try {
//                    //续方消息应该发给居民签约的团队长,modify by hmf
//                    SignFamily signFamily = signFamilyDao.findByPatient(getRepUID());
//                    BaseDoctorDO doctor1 = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//                    //            新增发送医生助手模板消息 v1.4.0 by wujunjie
//                    BasePatientDO patient = patientDao.findByCode(getRepUID());
//                    String doctorOpenID = doctor1.getOpenid();
//                    if (StringUtils.isNotEmpty(doctorOpenID)) {
//                        String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                        List<NameValuePair> params = new ArrayList<>();
//                        params.add(new BasicNameValuePair("type", "9"));
//                        params.add(new BasicNameValuePair("openId", doctorOpenID));
//                        params.add(new BasicNameValuePair("url", targetUrl));
//                        params.add(new BasicNameValuePair("first", doctor1.getName() + "医生您好。您的签约居民" + patient.getName() + "申请线上续方,请尽快审核。"));
//                        params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
//                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
//                        String keywords = "续方审核" + "," + doctor1.getHospitalName() + "," + doctor1.getName();
//                        params.add(new BasicNameValuePair("keywords", keywords));
//
//                        httpClientUtil.post(url, params, "UTF-8");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
//
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "添加失败");
//        }
//    }
//    @RequestMapping(value = "getPreConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getPreConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                    @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) long id,
//                                    @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType(getRepUID(), id, pagesize, 8, title);//8表示续方咨询
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,8 续方咨询
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//                    json.put("evaluate", result[8]);
//                    String relationCode = result[9] == null ? "" : result[9].toString();
//                    json.put("prescriptionCode", relationCode);//续方code
//                    json.put("prescriptionDt", prescriptionDiagnosisService.getPrescriptionDiagnosis(relationCode));//续方疾病类型
//                    json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(relationCode));//续方药品信息
//
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "prescriptionDetail", method = RequestMethod.GET)
//    @ApiOperation("获取续方信息")
//    public String prescriptionDetail(@ApiParam(name = "consult", value = "咨询code") @RequestParam(required = true) String consult) {
//        try {
//            JSONObject json = new JSONObject();
//
//            Consult consult1 = consultDao.findByCode(consult);
//
//            String prescriptionCode = consult1.getRelationCode();
//            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//            json.put("status", prescription.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
//            json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
//            json.put("symptoms", consult1.getSymptoms());//咨询类型--- 1高血压,2糖尿病
//            json.put("jwCode", prescription.getJwCode());//基位处方code
//            json.put("code", prescription.getCode());//续方code
//            json.put("viewJiancha", prescription.getViewJiancha());//检查
//            json.put("viewTizhen", prescription.getViewTizhen());//体征
//            json.put("viewChufang", prescription.getViewChufang());//处方
//            json.put("viewXufang", prescription.getViewXufang());//续方
//            json.put("viewWenjuan", prescription.getViewWenjuan());//问卷
//            json.put("viewSuifang", prescription.getViewSuifang());//随访
//
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "remainConsultTimes", method = RequestMethod.GET)
//    @ApiOperation("获取剩余家庭咨询次数")
//    public String countRemainConsult() {
//        try {
//            String patient = getRepUID();
//            JSONObject result = consultTeamService.countRemainConsult(patient);
//            if (result.has("count") && result.has("amount")) {
//                return write(200, "查询成功!", "data", result);
//            } else if (result.has("count") && !result.has("amount")) {
//                return error(-1, "您的签约已到期,请重新申请");
//            } else {
//                return error(-1, "查询失败!");
//            }
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 解析contentType
     * PlainText: 1,   // 信息
     * Image: 2,       // 图片信息
     * Audio: 3,       // 语音信息
     * Article: 4,     // 文章信息
     * GoTo: 5,        // 跳转信息,求组其他医生或者邀请其他医生发送的推送消息
     * TopicBegin: 6,  // 议题开始
     * TopicEnd: 7,    // 议题结束 10 11 系统发送的会话消息
     * TopicInto: 14,    // 进入议题 系统发送的会话消息
     * Video:12,//视频
     * System:13,//系统消息
     * PrescriptionCheck:15,//续方审核消息消息
     * PrescriptionBloodStatus:16,//续方咨询血糖血压咨询消息
     * PrescriptionFollowupContent:17,//续方咨询随访问卷消息
     *
     * @param contentType 消息类型
     * @return
     */
    private String parseContentType(String contentType, String content) {
        String responseContent = "";
        try {
            switch (contentType) {
                case "1":
                    responseContent = content;
                    break;
                case "2":
                    responseContent = "[图片消息]";
                    break;
                case "3":
                    responseContent = "[语音消息]";
                    break;
                case "4":
                    responseContent = "[文章消息]";
                    break;
                case "5":
                    responseContent = "[跳转链接消息]";
                    break;
                case "6":
                    responseContent = content;
                    break;
                case "7":
                    responseContent = content;
                    break;
                case "10":
                    responseContent = content;
                    break;
                case "11":
                    responseContent = content;
                    break;
                case "12":
                    responseContent = "[视频消息]";
                    break;
                case "13":
                    responseContent = content;
                    break;
                case "14":
                    responseContent = content;
                    break;
                case "15":
                    responseContent = "[续方审核消息]";
                    break;
                case "16":
                    responseContent = "[体征记录咨询消息]";
                    break;
                case "17":
                    responseContent = "[随访问卷咨询消息]";
                    break;
                default:
                    responseContent = "[咨询消息]";
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseContent;
    }
//    @RequestMapping(value = "addExaminationConsult", method = RequestMethod.POST)
//    @ApiOperation("添加在线复诊咨询")
//    public String addExaminationConsult(@ApiParam(name = "visitNo", value = "健康档案处方ID", defaultValue = "10")
//                                        @RequestParam(value = "visitNo", required = true) String visitNo,
//                                        @ApiParam(name = "doctor", value = "咨询医生(开方医生、审核医生)", defaultValue = "86225d1365e711e69f7c005056850d66")
//                                        @RequestParam(value = "doctor", required = true) String doctor,
//                                        @ApiParam(name = "adminTeamId", value = "签约行政团队id", defaultValue = "224")
//                                        @RequestParam(value = "adminTeamId", required = false) Long adminTeamId,
//                                        @ApiParam(name = "reason", value = "续方说明", defaultValue = "续方申请")
//                                        @RequestParam(value = "reason", required = false) String reason,
//                                        @ApiParam(name = "diagnosis", value = "处方诊断", defaultValue = "处方诊断")
//                                        @RequestParam(value = "diagnosis", required = false) String diagnosis) {
//        try {
//            ConsultTeam consult = new ConsultTeam();
//            consult.setType(9);//在线复诊咨询
//
//            int res = 0;
//            synchronized (visitNo.intern()) {
//                res = consultTeamService.addExaminationConsult(visitNo, getRepUID(), getUID(), doctor, consult, reason, diagnosis);
//            }
//            if (res == -1) {
//                return error(-1, "该处方存在未审核的续方,无法进行续方咨询!");
//            }
//            if (res == -3) {
//                return error(-1, "您当天有未完成的续方,不能发起续方咨询!");
//            }
//
//            pushMsgTask.put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_EXAMINATION.D_CT_06.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_EXAMINATION.在线复诊咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_EXAMINATION.您有新的复诊咨询.name(), consult.getConsult());
//
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "添加失败");
//        }
//    }
//    @RequestMapping(value = "addDoorServiceConsult", method = RequestMethod.POST)
//    @ApiOperation("添加上门服务咨询")
//    public String addDoorServiceConsult(@ApiParam(name = "orderId", value = "服务工单id") @RequestParam(value = "orderId", required = true) String orderId) {
//        try {
//            ConsultTeamDo consultTeam = null;
//            int count = consultDao.countByRelationCode(orderId);
//            if (count > 0) {
//                return error(-1, "当前工单已经发起过咨询,不可重复发起!");
//            }
//            // 保存到数据库
//            synchronized (orderId.intern()) {
//                JSONObject result = consultTeamService.addDoorServiceConsult(orderId);
//                if (Integer.parseInt(result.get(ResponseContant.resultFlag).toString()) == ResponseContant.fail) {
//                    return error(-1, result.getString(ResponseContant.resultMsg));
//                }
//                consultTeam = (ConsultTeam) result.get(ResponseContant.resultMsg);
//            }
//
//            if (null == consultTeam) {
//                return error(-1, "无法保存咨询详情,添加失败!");
//            }
//
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consultTeam));
//            return write(200, "提交成功", "data", consultTeam);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "添加失败");
//        }
//    }
//    @RequestMapping(value = "queryByRelationCode", method = RequestMethod.GET)
//    @ApiOperation("根据关联业务code查询咨询记录")
//    public String queryByRelationCode(@ApiParam(name = "code", value = "咨询关联业务code") @RequestParam(value = "code", required = true) String code) {
//        try {
//            ConsultTeam consultTeam = consultTeamService.queryByRelationCode(code);
//            return write(200, "提交成功", "data", consultTeam);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "添加失败");
//        }
//    }
//    @RequestMapping(value = "queryByConsultCode", method = RequestMethod.GET)
//    @ApiOperation("根据咨询code查询关联业务项详情")
//    public String queryByConsultCode(@ApiParam(name = "code", value = "咨询code") @RequestParam(value = "code", required = true) String code,
//                                     @ApiParam(name = "type", value = "咨询类型") @RequestParam(value = "type", required = true) Integer type) {
//        try {
//            com.alibaba.fastjson.JSONObject detail = consultTeamService.queryByConsultCode(code, type);
//            return write(200, "查询成功", "data", detail.get("data"));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    @RequestMapping(value = "updateMsg", method = RequestMethod.POST)
    @ApiOperation("修改会话消息内容")
    public String queryByConsultCode(@ApiParam(name = "sessionId", value = "会话id") @RequestParam(value = "sessionId", required = true) String sessionId,
                                     @ApiParam(name = "sessionType", value = "会话类型") @RequestParam(value = "sessionType", required = true) String sessionType,
                                     @ApiParam(name = "msgId", value = "消息id") @RequestParam(value = "msgId", required = true) String msgId,
                                     @ApiParam(name = "content", value = "消息内容") @RequestParam(value = "content", required = true) String content) {
        org.json.JSONObject result = null;
        try {
            result = consultTeamService.updateIMMsg(sessionId, sessionType, msgId, content);
            if (result.getInt("status") != -1) {
                return write(200, "修改成功", "data", result.get("data"));
            }
        } catch (Exception e) {
            error(e);
        }
        return error(-1, result.getString("data"));
    }
//    @RequestMapping(value = "examinationDetail", method = RequestMethod.GET)
//    @ApiOperation("获取在线复诊信息")
//    public String examinationDetail(@ApiParam(name = "consult", value = "咨询code") @RequestParam(required = true) String consult) {
//        try {
//            JSONObject json = new JSONObject();
//
//            Consult consult1 = consultDao.findByCode(consult);
//
//            String examinationCode = consult1.getRelationCode();
//            Examination examination = examinationDao.findByCode(examinationCode);
//            json.put("status", examination.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
//            json.put("symptoms", consult1.getSymptoms());//咨询类型--- 1高血压,2糖尿病
//            json.put("visitNo", examination.getVisitNo());//基位处方code
//            json.put("code", examination.getCode());//续方code
//
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
//    @RequestMapping(value = "getKangFuConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getKangFuConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                       @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) long id,
//                                       @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType(getRepUID(), id, pagesize, 18, title);//18表示康复咨询
//            if (data != null) {
//                for (Object consult : data.getContent()) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    Object[] result = (Object[]) consult;
//                    JSONObject json = new JSONObject();
//                    json.put("id", result[0]);
//                    // 设置咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,8 续方咨询  18康复咨询
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//                    json.put("evaluate", result[8]);
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败!");
//        }
//    }
    /**
     * 获取患者发起咨询时可选择的专科医生团队列表,
     *
     * @param patientCode 患者code
     * @return
     */
//    @RequestMapping(value = "getConsultDoctorForConsulting", method = RequestMethod.GET)
//    @ApiOperation("获取咨询医生团队列表列表")
//    public String getConsultDoctorForConsulting(@RequestParam("patientCode") String patientCode) {
//        try {
//            return write(200, "查询成功", "data", consultTeamService.getConsultDoctorForConsulting(patientCode));
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "查询失败");
//        }
//    }
    /**
     *
     */
    @RequestMapping(value = "/isConsultFinished", method = RequestMethod.POST)
    public String isConsultFinished(@RequestParam String consult) {
        try {
            ConsultTeamDo ct = consultTeamDao.findByConsult(consult);
            return write(200, "查询咨询状态成功", "data", ct.getStatus());
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

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

@ -0,0 +1,381 @@
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
    ) throws Exception {
        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);
        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;
//        }
//    }
}

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

@ -0,0 +1,3484 @@
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.findOne(orderId);
        String patient = doorServiceOrderDO.getPatient();
        String doctor = doorServiceOrderDO.getDispatcher();
        String doctorName = doorServiceOrderDO.getDispatcherName();
        int orderStatus = doorServiceOrderDO.getStatus();
        //添加咨询记录
        BasePatientDO patientDO = patientService.findPatientById(patient);
        if (null == patientDO) {
            throw new Exception("当前居民不存在");
        }
        //咨询记录
        String title = patientDO.getName() + "-发起了服务咨询";
        ConsultDo consult = addConsult(patient, title, doorServiceOrderDO.getServeDesc(), patientDO.getPhone(), 11);
        //咨询详细信息
        ConsultTeamDo consultTeam = new ConsultTeamDo();
        consultTeam.setType(11);  //上门服务咨询
//        consultTeam.setAdminTeamId(signFamily.getAdminTeamId());//签约团队的信息-这边没有
        consultTeam.setRelationCode(doorServiceOrderDO.getId()); //关联业务code
        consultTeam.setSymptoms(doorServiceOrderDO.getServeDesc());
        consultTeam.setPatient(patient);
        consultTeam.setName(patientDO.getName());
        consultTeam.setBirthday(patientDO.getBirthday());
        consultTeam.setSex(patientDO.getSex());
        consultTeam.setPhoto(patientDO.getPhoto());
        consultTeam.setCzrq(new Date());
        consultTeam.setDel("1");
        consultTeam.setStatus(0);
        consultTeam.setEvaluate(0);
        consultTeam.setDoctorRead(1); // 医生未读数量为1
        consult.setRelationCode(doorServiceOrderDO.getId());//关联业务code
        consultTeam.setConsult(consult.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 = 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, ImUtil.SESSION_TYPE_ONDOOR_NURSING);
//        if (imResponseJson == null || imResponseJson.getString("status").equals("-1")) {
//            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
//            throw new Exception(failMsg);
//        }
        if (imResponseJson != null && imResponseJson.get("start_msg_id") != null) {
            consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        }
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
//    @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);
        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.findOne(String.valueOf(logId));
    }
//    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);
//        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);
//        // 设置医生姓名
//        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());
//            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 JSONObject getSessionId(String patient) {
        JSONObject re = new 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) {
        JSONObject re = new 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);
            JSONObject json = new 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 org.json.JSONObject updateIMMsg(String sessionId, String sessionType, String msgId, String content) {
        org.json.JSONObject result = new org.json.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;
        }
        org.json.JSONObject contentJsonObj = null;
        try {
            contentJsonObj = new org.json.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 org.json.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;
//    }
}

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

@ -0,0 +1,186 @@
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;
import java.net.URLDecoder;
/**
 * 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;
    /**
     * 参数:
     * auditorType: 2
     * status: 0
     * page: 1
     * pageSize: 15
     */
    @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());
        }
    }
    /**
     * 参数:
     * id=9e1204850bf4437e8ebf2c182db34f0e
     */
    @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());
        }
    }
    /**
     * 代审核
     * 参数:
     * {
     * "startTime":"2023-10-19 00:00:00","endTime":"2023-10-19 00:00:00","patient":"915ceabb-5b1d-11e6-8344-fa163e8aee56",
     * "status":2,"id":"","patientName":"王银汉","patientIdcard":"350211195808274534","patientAddr":"G.福建省厦门市海沧区海沧街道囷瑶村石岑社5组5号(高友网)",
     * "patientPhone":"13950088528","applicationDescribe":"测试",
     * "wlyyDoorServiceVoucherDos":[{"patientCode":"915ceabb-5b1d-11e6-8344-fa163e8aee56","type":"6","typeValue":"其他"}]
     * }
     */
    @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 {
            //解码
            jsonData = URLDecoder.decode(jsonData, "UTF-8");
            if (StringUtils.isBlank(doctorCode)) {
                doctorCode = getRepUID();
            }
            WlyyDoorServiceApplicationDo wlyyDoorServiceApplicationDo = doorServiceApplicationService.create("2", jsonData, doctorCode);
            return success("获取成功", wlyyDoorServiceApplicationDo);
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
}

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 1420 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java


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

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

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 340 - 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);
}

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

@ -0,0 +1,25 @@
package com.yihu.jw.hospital.module.door.dao;
import com.yihu.jw.entity.door.WlyyDoorCommentDoctorDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
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 WlyyDoorCommentDoctorDao extends PagingAndSortingRepository<WlyyDoorCommentDoctorDO, Integer>, JpaSpecificationExecutor<WlyyDoorCommentDoctorDO> {
    @Query("select t from WlyyDoorServiceOrderDO t where t.id = ?1")
    WlyyDoorServiceOrderDO selectOrder(String orderId);
}

+ 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);
}

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


이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.