Browse Source

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

wangzhinan 1 year ago
parent
commit
8e25b65862
71 changed files with 9906 additions and 2375 deletions
  1. 3 0
      business/base-service/src/main/java/com/yihu/jw/area/dao/BaseCityDao.java
  2. 3 0
      business/base-service/src/main/java/com/yihu/jw/area/dao/BaseProvinceDao.java
  3. 4 0
      business/base-service/src/main/java/com/yihu/jw/area/dao/BaseStreetDao.java
  4. 13 0
      business/base-service/src/main/java/com/yihu/jw/area/dao/BaseTownDao.java
  5. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/specialist/rehabilitation/RehabilitationPlanTemplateDao.java
  6. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/specialist/rehabilitation/RehabilitationTemplateDetailDao.java
  7. 46 12
      business/base-service/src/main/java/com/yihu/jw/hospital/disease/service/BaseDiseaseHospitalService.java
  8. 97 0
      business/base-service/src/main/java/com/yihu/jw/hospital/jw/JwArchiveRecordBaseService.java
  9. 124 58
      business/base-service/src/main/java/com/yihu/jw/hospital/message/service/SystemMessageService.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/ConsultOrderDao.java
  13. 2 2
      business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java
  14. 7 47
      business/base-service/src/main/java/com/yihu/jw/wlyy/service/WlyyBusinessService.java
  15. 3 1
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultDao.java
  16. 944 927
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  17. 171 1
      common/common-entity/src/db/2023.sql
  18. 121 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServiceItemPlanDO.java
  19. 11 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServicePackageSubItemDO.java
  20. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorOrderItemDO.java
  21. 30 0
      common/common-entity/src/main/java/com/yihu/jw/entity/door/WlyyDoorServiceOrderDO.java
  22. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/ehr/resource/RsResource.java
  23. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/ehr/resource/RsResourceMetadata.java
  24. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/message/WlyyDynamicMessages.java
  25. 12 1
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/qvo/ParamQvo.java
  26. 236 2
      common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java
  27. 2 0
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java
  28. 1 19
      gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/PostFilter.java
  29. 3 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/specialist/rehabilitation/RehabilitationPlanController.java
  30. 7 5
      svr/svr-base/src/main/java/com/yihu/jw/base/service/specialist/rehabilitation/RehabilitationPlanService.java
  31. 109 5
      svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceIntegratedController.java
  32. 307 1
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/ResourceBrowseDao.java
  33. 25 1
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/ResourceBrowseMetadataDao.java
  34. 58 2
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/ResourceBrowseService.java
  35. 56 8
      svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/ResourceIntegratedService.java
  36. 64 0
      svr/svr-basic/src/main/java/com/yihu/jw/basic/util/WorkbookUtil.java
  37. 22 21
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/consult/DoctorConsultController.java
  38. 57 12
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java
  39. 1 1
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/consult/ConsultTeamService.java
  40. 46 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/CommonItemController.java
  41. 1998 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java
  42. 1667 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/DoctorConsultController.java
  43. 8 13
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java
  44. 125 138
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  45. 100 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/district/controller/DistrictController.java
  46. 249 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/district/service/DistrictService.java
  47. 31 6
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoctorDoorServiceAuditController.java
  48. 197 126
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  49. 126 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/PatientDoorServiceApplicationController.java
  50. 81 58
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java
  51. 27 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/ServiceItemPlanDao.java
  52. 4 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDoctorDao.java
  53. 258 216
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java
  54. 27 7
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorServiceApplicationService.java
  55. 102 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorCommentService.java
  56. 634 484
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java
  57. 1 3
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java
  58. 2 2
      business/base-service/src/main/java/com/yihu/jw/jw/service/JwArchivesService.java
  59. 2 2
      business/base-service/src/main/java/com/yihu/jw/jw/service/JwSmjkService.java
  60. 891 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/message/DoctorMessageController.java
  61. 0 23
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPlanTemplateDao.java
  62. 0 18
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationTemplateDetailDao.java
  63. 28 32
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/PatientRecordService.java
  64. 72 73
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java
  65. 2 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java
  66. 88 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/controller/DoorCommentController.java
  67. 124 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/service/DoorCommentService.java
  68. 1 1
      business/base-service/src/main/java/com/yihu/jw/system/dao/SystemDictDao.java
  69. 2 39
      business/base-service/src/main/java/com/yihu/jw/system/service/SystemDictService.java
  70. 223 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/CommonUtil.java
  71. 3 4
      common/common-util/src/main/java/com/yihu/jw/util/DoctorAssistantUtil.java

+ 3 - 0
business/base-service/src/main/java/com/yihu/jw/area/dao/BaseCityDao.java

@ -31,4 +31,7 @@ public interface BaseCityDao extends JpaRepository<BaseCityDO, Integer>, JpaSpec
    @Query("select a from BaseCityDO a where a.province = ?1 order by id")
    Iterable<BaseCityDO> findByProvince(String province);
    @Query("select p from BaseCityDO p where p.name = ?1")
    BaseCityDO findByName(String name);
}

+ 3 - 0
business/base-service/src/main/java/com/yihu/jw/area/dao/BaseProvinceDao.java

@ -20,4 +20,7 @@ import org.springframework.data.repository.query.Param;
public interface BaseProvinceDao extends JpaRepository<BaseProvinceDO, Integer>, JpaSpecificationExecutor<BaseProvinceDO> {
    @Query("select name from BaseProvinceDO where code =:code")
    String getNameByCode(@Param("code") String code);
    @Query("select p from BaseProvinceDO p where p.name = ?1")
    BaseProvinceDO findByName(String name);
}

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

@ -4,6 +4,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.yihu.jw.entity.base.area.BaseStreetDO;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
@ -22,4 +23,7 @@ import java.util.List;
public interface BaseStreetDao extends JpaRepository<BaseStreetDO, Integer>, JpaSpecificationExecutor<BaseStreetDO>  {
    List<BaseStreetDO> findByTown(String town);
    @Query("select p from BaseStreetDO p where p.name = ?1")
    BaseStreetDO findByName(String name);
}

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

@ -30,4 +30,17 @@ public interface BaseTownDao extends JpaRepository<BaseTownDO, Integer>, JpaSpec
    @Query("select a from BaseTownDO a where a.city = ?1 order by id")
    List<BaseTownDO> findByCityCode(String city);
    @Query("select a from BaseTownDO a where a.city = ?1 order by id")
    Iterable<BaseTownDO> findByCity(String province);
    @Query("select p from BaseTownDO p where p.name = ?1")
    BaseTownDO findByName(String name);
    @Query("select p from BaseTownDO p where p.name = ?1 and p.city = ?2")
    BaseTownDO findByNameAndCity(String name,String city);
}

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/dao/specialist/rehabilitation/RehabilitationPlanTemplateDao.java

@ -1,4 +1,4 @@
package com.yihu.jw.base.dao.specialist.rehabilitation;
package com.yihu.jw.hospital.disease.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPlanTemplateDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/dao/specialist/rehabilitation/RehabilitationTemplateDetailDao.java

@ -1,4 +1,4 @@
package com.yihu.jw.base.dao.specialist.rehabilitation;
package com.yihu.jw.hospital.disease.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationTemplateDetailDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

+ 46 - 12
business/base-service/src/main/java/com/yihu/jw/hospital/disease/service/BaseDiseaseHospitalService.java

@ -1,28 +1,25 @@
package com.yihu.jw.hospital.disease.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.knowledge.BaseKnowledgeQuestion;
import com.yihu.jw.entity.specialist.BaseDiseaseHospitalDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPlanTemplateDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationTemplateDetailDO;
import com.yihu.jw.hospital.disease.dao.BaseDiseaseHospitalDao;
import com.yihu.jw.hospital.disease.dao.RehabilitationPlanTemplateDao;
import com.yihu.jw.hospital.disease.dao.RehabilitationTemplateDetailDao;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.network.HttpResponse;
import com.yihu.jw.util.network.HttpUtils;
import com.yihu.jw.utils.AES;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
import jdk.nashorn.internal.scripts.JS;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -35,7 +32,10 @@ public class BaseDiseaseHospitalService extends BaseJpaService<BaseDiseaseHospit
    private BaseDiseaseHospitalDao diseaseHospitalDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private RehabilitationPlanTemplateDao templateDao;
    @Autowired
    private RehabilitationTemplateDetailDao templateDetailDao;
    @Autowired
    private WlyyBusinessService wlyyBusinessService;
@ -51,7 +51,42 @@ public class BaseDiseaseHospitalService extends BaseJpaService<BaseDiseaseHospit
        }else {
            diseaseHospitalDO.setCreateTime(new Date());
            diseaseHospitalDO.setSort(maxSort("base_disease_hospital")+1);
            return diseaseHospitalDao.save(diseaseHospitalDO);
            diseaseHospitalDO = diseaseHospitalDao.save(diseaseHospitalDO);
            //新增专病默认配置康复计划
            defaultRehabilitationPlan(diseaseHospitalDO.getId());
            return diseaseHospitalDO;
        }
    }
    public void defaultRehabilitationPlan(String diseaseId){
        String templateId = "system";
        RehabilitationPlanTemplateDO templateDO = templateDao.findById(templateId).orElse(null);
        if(templateDO==null){
            return;
        }
        List<RehabilitationTemplateDetailDO> details = templateDetailDao.findTemplateDetailByTemplateId(templateId);
        if(details.size()==0){
            return;
        }
        RehabilitationPlanTemplateDO templateDONew = new RehabilitationPlanTemplateDO();
        BeanUtils.copyProperties(templateDO,templateDONew);
        templateDONew.setCreateTime(new Date());
        templateDONew.setId(null);
        templateDONew.setDiseaseId(diseaseId);
        templateDONew.setType("2");
        templateDONew = templateDao.save(templateDONew);
        String templateDONewId = templateDONew.getId();
        List<RehabilitationTemplateDetailDO> detailsNew = new ArrayList<>();
        for (RehabilitationTemplateDetailDO detailDO:details){
            RehabilitationTemplateDetailDO detail = new RehabilitationTemplateDetailDO();
            BeanUtils.copyProperties(detailDO,detail);
            detail.setId(null);
            detail.setTemplateId(templateDONewId);
            detail.setCreateTime(new Date());
            detailsNew.add(detail);
        }
        if(detailsNew.size()>0){
            templateDetailDao.saveAll(detailsNew);
        }
    }
@ -69,7 +104,6 @@ public class BaseDiseaseHospitalService extends BaseJpaService<BaseDiseaseHospit
            if (rstotal.get(0).get("sort")!=null){
                count = Integer.parseInt(rstotal.get(0).get("sort").toString());
            }
        }
        return count;
    }

File diff suppressed because it is too large
+ 97 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/jw/JwArchiveRecordBaseService.java


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

@ -1,5 +1,6 @@
package com.yihu.jw.hospital.message.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
@ -15,12 +16,11 @@ import com.yihu.jw.hospital.message.dao.MessageNoticeSettingDao;
import com.yihu.jw.hospital.message.dao.SpecialistDynamicMessagesDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.YkyySMSService;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -29,6 +29,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
@ -38,7 +39,7 @@ import java.util.Map;
 */
@Service
@Transactional
public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemMessageDao> {
public class SystemMessageService extends BaseJpaService<SystemMessageDO, SystemMessageDao> {
    @Autowired
    private SystemMessageDao systemMessageDao;
@ -60,18 +61,18 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    private MessageNoticeSettingDao messageNoticeSettingDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    SystemDictService systemDictService;
    @Autowired
    SpecialistDynamicMessagesDao specialistDynamicMessagesDao;
    /**
     * 新增线上就诊消息
     *
     * @param systemMessageDO
     * @return
     * @throws Exception
     */
    public SystemMessageDO addMessage(SystemMessageDO systemMessageDO) throws Exception{
    public SystemMessageDO addMessage(SystemMessageDO systemMessageDO) throws Exception {
        systemMessageDO.setIsRead("0");
        systemMessageDO.setDel("1");
        systemMessageDO.setCreateTime((new Date()));
@ -82,22 +83,23 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    /**
     * 更新线上就诊消息
     *
     * @param id
     * @param read
     * @param del
     * @return
     * @throws Exception
     */
    public SystemMessageDO updateMessage(String id,String read,String del) throws Exception{
    public SystemMessageDO updateMessage(String id, String read, String del) throws Exception {
        SystemMessageDO systemMessageDO = systemMessageDao.findById(id).orElse(null);
        if (null == systemMessageDO){
        if (null == systemMessageDO) {
            return null;
        }
        if (!StringUtil.isEmpty(read)){
        if (!StringUtil.isEmpty(read)) {
            systemMessageDO.setIsRead(read);
            systemMessageDO.setReadTime(new Date());
        }
        if (!StringUtil.isEmpty(del)){
        if (!StringUtil.isEmpty(del)) {
            systemMessageDO.setDel(del);
        }
        systemMessageDao.save(systemMessageDO);
@ -107,10 +109,11 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    /**
     * 保存线上就诊消息(外部调用)
     *
     * @param systemMessageDO
     * @throws Exception
     */
    public void saveMessage(SystemMessageDO systemMessageDO) throws Exception{
    public void saveMessage(SystemMessageDO systemMessageDO) throws Exception {
        systemMessageDO.setIsRead("0");
        systemMessageDO.setDel("1");
        systemMessageDO.setCreateTime(new Date());
@ -120,11 +123,12 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    /**
     * 根据id查询消息详情
     *
     * @param id
     * @return
     * @throws Exception
     */
    public  SystemMessageDO queryById(String id) throws Exception{
    public SystemMessageDO queryById(String id) throws Exception {
        SystemMessageDO systemMessageDO = systemMessageDao.queryById(id);
        return systemMessageDO;
    }
@ -132,12 +136,12 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    /**
     * 发送系统消息通用接口
     */
    public  SystemMessageDO commenSystemMessage(String jsonParam,String jsonContent) throws Exception{
        if (StringUtils.isNoneBlank(jsonParam)){
            SystemMessageDO systemMessageDO = objectMapper.readValue(jsonParam,SystemMessageDO.class);
    public SystemMessageDO commenSystemMessage(String jsonParam, String jsonContent) throws Exception {
        if (StringUtils.isNoneBlank(jsonParam)) {
            SystemMessageDO systemMessageDO = objectMapper.readValue(jsonParam, SystemMessageDO.class);
            systemMessageDO.setDel("1");
            systemMessageDO.setIsRead("0");
            if (StringUtils.isNoneBlank(jsonContent)){
            if (StringUtils.isNoneBlank(jsonContent)) {
                JSONObject jsonObject = JSONObject.parseObject(jsonContent);
                systemMessageDO.setData(jsonObject.toJSONString());
            }
@ -146,24 +150,25 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
        }
        return null;
    }
    public String  sendDoctorRemindSms(ConsultDo consultDo){
    public String sendDoctorRemindSms(ConsultDo consultDo) {
        String msg = "";
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            if (consultDo!=null){
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            if (consultDo != null) {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(consultDo.getRelationCode()).orElse(null);
                if (wlyyOutpatientDO!=null){
                if (wlyyOutpatientDO != null) {
                    BaseDoctorDO baseDoctorDO = baseDoctorDao.findByIdAndDel(wlyyOutpatientDO.getDoctor());
                    if (baseDoctorDO!=null){
                        ykyySMSService.sendSmsByTempcode("message_remind_paitent",wlyyOutpatientDO,null,baseDoctorDO.getMobile());
                        msg="发送成功";
                    }else{
                        msg="发送失败,医生不存在";
                    if (baseDoctorDO != null) {
                        ykyySMSService.sendSmsByTempcode("message_remind_paitent", wlyyOutpatientDO, null, baseDoctorDO.getMobile());
                        msg = "发送成功";
                    } else {
                        msg = "发送失败,医生不存在";
                    }
                }else {
                    msg="发送失败,门诊不存在";
                } else {
                    msg = "发送失败,门诊不存在";
                }
            }else {
                msg="发送失败,consult不存在";
            } else {
                msg = "发送失败,consult不存在";
            }
        }
@ -202,22 +207,22 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    }*/
    /**
     * 获取消息提示开关
     *
     * @param user
     * @param type
     * @param messageType
     * @return (1开,0关)
     * @return (1开 , 0关)
     */
    public Boolean getMessageNoticeSettingByMessageType(String user,String type,String messageType){
    public Boolean getMessageNoticeSettingByMessageType(String user, String type, String messageType) {
        Integer re = 0;
        com.alibaba.fastjson.JSONObject setting = getMessageNoticSetting(user,type);
        com.alibaba.fastjson.JSONObject setting = getMessageNoticSetting(user, type);
        Integer masterSwitch = setting.getInteger("masterSwitch");
        if(masterSwitch==0){
        if (masterSwitch == 0) {
            return false;
        }
        switch (messageType){
        switch (messageType) {
            case "masterSwitch":
                //总开关
                re = masterSwitch;
@ -229,7 +234,7 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
            case "familyTopicSwitch":
                //健管师邀请后推送开关
                Integer imSwitch = setting.getInteger("imSwitch");
                if(imSwitch==1){
                if (imSwitch == 1) {
                    re = setting.getInteger("familyTopicSwitch");
                }
                break;
@ -265,23 +270,24 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
                break;
        }
        return re==1;
        return re == 1;
    }
    /**
     * 获取消息提醒设置
     *
     * @param user
     * @param type
     * @return
     */
    public com.alibaba.fastjson.JSONObject getMessageNoticSetting(String user, String type){
    public com.alibaba.fastjson.JSONObject getMessageNoticSetting(String user, String type) {
        com.alibaba.fastjson.JSONObject re = null;
        String key = MESSAGE_NOTICESETTING+user+":"+type;
        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){
        if (StringUtils.isBlank(response)) {
            MessageNoticeSetting messageNoticeSetting = messageNoticeSettingDao.findByUserAndType(user, type);
            if (messageNoticeSetting == null) {
                messageNoticeSetting = new MessageNoticeSetting();
                messageNoticeSetting.setCreateTime(new Date());
                messageNoticeSetting.setFamilyTopicSwitch(0);
@ -299,7 +305,7 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
                messageNoticeSettingDao.save(messageNoticeSetting);
            }
            response = com.alibaba.fastjson.JSONObject.toJSONString(messageNoticeSetting);
            redisTemplate.opsForValue().set(key,response);
            redisTemplate.opsForValue().set(key, response);
        }
        re = com.alibaba.fastjson.JSONObject.parseObject(response);
        return re;
@ -307,7 +313,7 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    //添加专科动态消息
    public void addSpecialistDynamicMessages(BasePatientDO patient, BaseDoctorDO specialist, BaseDoctorDO doctor, String result, String disease, String type, SignFamily signFamily){
    public void addSpecialistDynamicMessages(BasePatientDO patient, BaseDoctorDO specialist, BaseDoctorDO doctor, String result, String disease, String type, SignFamily signFamily) {
        try {
            String patientName = patient.getName();
            String doctorName = "";
@ -317,32 +323,33 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
            specialistDynamicMessages.setResult(result);
            specialistDynamicMessages.setName(patientName);
            specialistDynamicMessages.setCode(patient.getId());
            if(doctor!=null){
            //这边需要修改医生的信息-20231019
//            if (doctor != null) {
//                specialistDynamicMessages.setDoctor(doctor.getCode());
//                specialistDynamicMessages.setHospital(doctor.getHospital());
                doctorName = doctor.getName();
            }else if(signFamily!=null){
                specialistDynamicMessages.setDoctor(signFamily.getDoctor());
                specialistDynamicMessages.setHospital(signFamily.getHospital());
                doctorName = signFamily.getDoctorName();
            }
//            specialistDynamicMessages.setSpecialist(specialist.getCode());
//            specialistDynamicMessages.setSpecialistHospital(specialist.getHospital());
//                doctorName = doctor.getName();
//            }
//            else if (signFamily != null) {
//                specialistDynamicMessages.setDoctor(signFamily.getDoctor());
//                specialistDynamicMessages.setHospital(signFamily.getHospital());
//                doctorName = signFamily.getDoctorName();
//            }
            specialistDynamicMessages.setDiseaseType(disease);
            specialistDynamicMessages.setCodeType("2");
            specialistDynamicMessages.setCreateTime(DateUtil.getStringDate());
            specialistDynamicMessages.setType(type);
            Map<String,String> copywritingMap = systemDictService.getDictMap("DynamicMessages"+type);
            //这边后面改成用sql查-20231019
//            Map<String, String> copywritingMap = systemDictService.getDictMap("DynamicMessages" + type);
            Map<String, String> copywritingMap = null;
            //获取文案模板
            String content = copywritingMap.get("doctor");
            content = content.replace("【医生】",specialistName).replace("【居民】",patientName);
            content = content.replace("【医生】", specialistName).replace("【居民】", patientName);
            //【医生】专科医生给您下转了居民【居民】
            //您代居民【居民】预约了【医生】专科医生的门诊
            //您向【医生】专科医生的发起了专科协同,居民【居民】
            //您向【医生】专科医生的发起了咨询求助,居民【居民】
            String specialistContent = copywritingMap.get("specialist");
            specialistContent = specialistContent.replace("【医生】",doctorName).replace("【居民】",patientName);
            specialistContent = specialistContent.replace("【医生】", doctorName).replace("【居民】", patientName);
            //您给社区医生【医生】下转了居民【居民】
            //【医生】社区医生代居民【居民】预约了您的门诊
            //【医生】社区医生向您发起了专科协同,居民【居民】
@ -351,11 +358,70 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
            specialistDynamicMessages.setSpecialistContent(specialistContent);
            specialistDynamicMessagesDao.save(specialistDynamicMessages);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取待接单的接口
     *
     * @param message {"read":1,"over":0}
     * @param page    页码
     * @param size    分页大小
     * @return
     * @throws Exception
     */
    public org.json.JSONObject getWaitingMessages(
            SystemMessageDO message, String types, Integer page, Integer size
    ) throws Exception {
        String sqlList = " SELECT a.*, b.`status` AS appliStatus ";
        String sqlCount = " select count(*) as total ";
        String sql = " FROM wlyy_message a " +
                " LEFT JOIN wlyy_door_service_application b ON a.relation_code = b.code ";
        sql += " where 1=1 AND a.state = 1 AND a.over = 1 ";
        if (!StringUtils.isEmpty(message.getReceiver())) {
            sql += " AND a.receiver = '" + message.getReceiver() + "'";
        }
        if (!StringUtils.isEmpty(types)) {
            sql += " AND a.type IN (" + types + ")";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlCount + sql);
        sql += " ORDER BY a.create_time DESC LIMIT " + (page - 1) * size + "," + size;
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sqlList + sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        JSONArray jsonArray = new JSONArray();
        for (Map<String, Object> one : mapList) {
            org.json.JSONObject object = new org.json.JSONObject();
            object.put("over", one.get("over"));
            object.put("code", one.get("code"));
            object.put("receiver", one.get("receiver"));
            object.put("del", one.get("del"));
            object.put("title", one.get("title"));
            object.put("type", one.get("type"));
            object.put("content", one.get("content"));
            object.put("sender", one.get("sender"));
            object.put("id", one.get("id"));
            object.put("state", one.get("state"));
            object.put("relation_code", one.get("relation_code"));
            object.put("has_read", one.get("has_read"));
            object.put("appliStatus", one.get("appliStatus"));
            Date date = (Date) one.get("create_time");
            object.put("create_time", DateUtil.dateToStr(date, "yyyy-MM-dd HH:mm:ss"));
            Date date1 = (Date) one.get("czrq");
            object.put("czrq", DateUtil.dateToStr(date1, "yyyy-MM-dd HH:mm:ss"));
            jsonArray.add(object);
        }
        org.json.JSONObject object = new org.json.JSONObject();
        object.put("total", count);
        object.put("waitingMessages", jsonArray);
        object.put("currPage", page);
        object.put("pageSize", size);
        return object;
    }
}

+ 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.hospital.message.dao.MessageNoticeSettingDao;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.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/ConsultOrderDao.java

@ -11,7 +11,8 @@ import org.springframework.data.repository.PagingAndSortingRepository;
 * @author huangwenjie
 */
public interface ConsultOrderDao extends JpaRepository<ConsultDo, String>, JpaSpecificationExecutor<ConsultDo> {
	
//	@Query("from ConsultDo a where a.relationCode = ?1")
//	ConsultDo findByRelationCode(String outpatientid);
@ -28,4 +29,6 @@ public interface ConsultOrderDao extends JpaRepository<ConsultDo, String>, JpaSp
//	// 查询患者咨询记录
//	@Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate,a.signCode  from ConsultDo a,ConsultTeamDo b where a.code = b.consult and a.patient = ?1 and a.del = '1' and a.type<>8 order by a.czrq desc")
//	Page<Object> findByPatient(String patient, Pageable pageRequest);
    ConsultDo queryByIdAndType(String id,Integer type);
}

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

@ -9,12 +9,12 @@ import com.yihu.jw.entity.hospital.prescription.WlyyInspectionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.healthCare.service.HealthCareService;
import com.yihu.jw.hospital.jw.JwArchiveRecordBaseService;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.dao.WlyyInspectionDao;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.jw.service.JwArchivesService;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientGroupDao;
@ -91,7 +91,7 @@ public class BasePatientService<T, R extends CrudRepository> extends BaseJpaServ
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    JwArchivesService jwArchivesService;
    JwArchiveRecordBaseService jwArchivesService;
    @Value("${wechat.id}")
    private String wxId;

+ 7 - 47
business/base-service/src/main/java/com/yihu/jw/wlyy/service/WlyyBusinessService.java

@ -830,56 +830,16 @@ public class WlyyBusinessService {
    /**
     * 获取十大专病信息
     * 获取ijk十大专病信息
     * @return
     */
    public JSONObject getSpecialList(){
        JSONObject re = wlyyHttpService.sendWlyyMesGet("getSpecialList","");
        if (re!=null){
            if (re.getString("status").equalsIgnoreCase("200")){
                JSONArray array = re.getJSONArray("data");
                for (int i=0;i<array.size();i++){
                    JSONObject object = array.getJSONObject(i);
                    String code = object.getString("code");
                    switch (code){
                        case "11"://肺癌
                            code = "fa";
                            break;
                        case "3"://冠心病
                            code="gxb";
                            break;
                        case "17"://慢性妇科炎症
                            code="mxfkyz";
                            break;
                        case "10"://慢性前列腺
                            code="mxqlx";
                            break;
                        case "13"://慢性乳腺疾病
                            code="mxrxjb";
                            break;
                        case "12"://慢性肾病
                            code="mxsb";
                            break;
                        case "14"://慢性肠胃病
                            code="mxcwb";
                            break;
                        case "15"://慢性阻塞性肺病
                            code="mxzsxfb";
                            break;
                        case "9"://脑卒中
                            code="ncz";
                            break;
                        case "16"://脂肪肝
                            code="zfg";
                            break;
                        default:
                            break;
                    }
                    object.put("code",code);
                }
            }
        }
        return re;
        JSONObject json = new JSONObject();
        String sql = "SELECT dict_code code,dict_value name from wlyy_hospital_sys_dict WHERE dict_name = 'ijkSpecialList' ORDER BY sort";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        json.put("msg","success");
        json.put("data",list);
        return json;
    }

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

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

+ 944 - 927
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -17,954 +17,971 @@ import java.util.List;
/**
 * IM工具类
 *
 * @author huangwenjie
 */
@Component
public class ImUtil {
	@Autowired
	private HttpClientUtil HttpClientUtil;
	@Value("${im.im_list_get}")
	private String im_host;
	public enum ContentType {
		plainText("信息", "1"),
		image("图片信息", "2"),
		audio("创建处方", "3"),
		article("文章信息", "4"),
		goTo("跳转信息,求组其他医生或者邀请其他医生发送的推送消息", "5"),
		topicBegin("议题开始", "6"),
		topicEnd("议题结束", "7"),
		personalCard("个人名片", "18"),
		messageForward("消息转发", "19"),
		topicInto("进入议题", "14"),
		video("视频", "12"),
		system("系统消息", "13"),
		prescriptionCheck("续方审核消息消息", "15"),
		prescriptionBloodStatus("续方咨询血糖血压咨询消息", "16"),
		prescriptionFollowupContent("续方咨询随访问卷消息", "17"),
		Rehabilitation("康复计划发送","20"),
		Reservation("转诊预约发送","21"),
		Know("已知悉","22"),
		KnowCommonQuestion("知识库-常见问题","3001"),
		KnowCommonCustomer("知识库-客服欢迎","3008"),
		KnowCommonQuestions("知识库-常见问题集","3002"),
		KnowCommonDict("知识库-字典","3003"),
		KnowDeptDoctor("知识库-科室医生","3004"),
		KnowSymptomsDisease("知识库-疾病症状","3005"),
		KnowSymptomsDiseaseQ("知识库-疾病症状问题","3006"),
		KnowSymptomsDiseaseA("知识库-疾病症状回答","3007");
		private String name;
		private String value;
		ContentType(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 sendMDTSocketMessageToDoctor(String targetUserId, String message) {
		String imAddr = im_host + "api/v2/message/doctorSystemMessage";
		JSONObject params = new JSONObject();
		params.put("targetUserId", targetUserId);
		params.put("message", message);
		String response = HttpClientUtil.postBody(imAddr,params);
		return response;
	}
	public String sendPcManageMessageToPc(String clientType, String message) {
		String imAddr = im_host + "api/v2/message/cloudCarePcManageMessage";
		JSONObject params = new JSONObject();
		params.put("clientType", clientType);
		params.put("message", message);
		String response = HttpClientUtil.postBody(imAddr,params);
		return response;
	}
	public String sendPatientSystemMessage(String targetUserId, String message) {
		String imAddr = im_host + "api/v2/message/patientSystemMessage";
		JSONObject params = new JSONObject();
		params.put("targetUserId", targetUserId);
		params.put("message", message);
		String response = HttpClientUtil.postBody(imAddr,params);
		return response;
	}
	/**
	 * 发送消息
	 * @param senderId 发送者的code
	 * @param receiverId 接受者code
	 * @param contentType 消息类型 1二维码内容
	 * @param content 消息内容
	 * @return
	 */
	public String sendMessage(String senderId,String receiverId,String contentType,String content){
		String imAddr = im_host + "api/v2/message/send";
		JSONObject params = new JSONObject();
		params.put("sender_id", senderId);
		params.put("sender_name", receiverId);
		params.put("content_type", contentType);
		params.put("content", content);
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	/**
	 * 获取医生统计数据
	 * status reply 为空值是是该医生总咨询量
	 *
	 * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param adminTeamCode
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getConsultData(String user, Integer adminTeamCode, Integer status, Integer reply) {
		String imAddr = im_host + "api/v2/sessions/topics/count/reply";
		imAddr = imAddr + "?user=" + user;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (adminTeamCode != null) {
			imAddr += ("&adminTeamCode=" + adminTeamCode);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	public void updateTopics(String topicId, String jsonValue) {
		String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("data", jsonValue);
		HttpClientUtil.putBody(imAddr, params);
	}
	/**
	 * 当前医生下当前团队列表接口
	 * 获取团队内医生的健康咨询状况
	 * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 *
	 * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param adminTeamCode 行政团队code
	 * @param page
	 * @param pagesize
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getTeamConsultByStatus(String user, Integer adminTeamCode, Integer status, Integer reply, int page, int pagesize) {
		String imAddr = im_host + "api/v2/sessions/healthTeamTopics";
		imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
		if (adminTeamCode != null) {
			imAddr += ("&adminTeamCode=" + adminTeamCode);
		}
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	/**
	 * 列表接口
	 * 获取团队内医生的健康咨询状况
	 * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 *
	 * @param user     团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param page
	 * @param pagesize
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getConsultByStatus(String user, Integer status, Integer reply, int page, int pagesize) {
		String imAddr = im_host + "api/v2/sessions/healthTopics";
		imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	/**
	 * 咨询列表
	 * @param user
	 * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 * @param reply
	 * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public String getConsultByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime,int page,int pagesize){
		String imAddr = im_host + "api/v2/sessions/topicListByType";
		imAddr = imAddr + "?user="+user + "&page=" + page + "&pagesize=" + pagesize;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		if (type != null) {
			imAddr += ("&type=" + type);
		}
		if (patientName != null) {
			imAddr += ("&patientName=" + patientName);
		}
		if (startTime != null) {
			imAddr += ("&startTime=" + startTime);
		}
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	/**
	 * 咨询列表总数
	 * @param user
	 * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 * @param reply
	 * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
	 * @return
	 */
	public String getConsultCountByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime){
		String imAddr = im_host + "api/v2/sessions/topicListCountByType";
		imAddr = imAddr + "?user="+user;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		if (type != null) {
			imAddr += ("&type=" + type);
		}
		if (patientName != null) {
			imAddr += ("&patientName=" + patientName);
		}
		if (startTime != null) {
			imAddr += ("&startTime=" + startTime);
		}
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @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";
		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",extend);
		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) {
    @Autowired
    private HttpClientUtil HttpClientUtil;
    @Value("${im.im_list_get}")
    private String im_host;
    public enum ContentType {
        plainText("信息", "1"),
        image("图片信息", "2"),
        audio("创建处方", "3"),
        article("文章信息", "4"),
        goTo("跳转信息,求组其他医生或者邀请其他医生发送的推送消息", "5"),
        topicBegin("议题开始", "6"),
        topicEnd("议题结束", "7"),
        personalCard("个人名片", "18"),
        messageForward("消息转发", "19"),
        topicInto("进入议题", "14"),
        video("视频", "12"),
        system("系统消息", "13"),
        prescriptionCheck("续方审核消息消息", "15"),
        prescriptionBloodStatus("续方咨询血糖血压咨询消息", "16"),
        prescriptionFollowupContent("续方咨询随访问卷消息", "17"),
        Rehabilitation("康复计划发送", "20"),
        Reservation("转诊预约发送", "21"),
        Know("已知悉", "22"),
        KnowCommonQuestion("知识库-常见问题", "3001"),
        KnowCommonCustomer("知识库-客服欢迎", "3008"),
        KnowCommonQuestions("知识库-常见问题集", "3002"),
        KnowCommonDict("知识库-字典", "3003"),
        KnowDeptDoctor("知识库-科室医生", "3004"),
        KnowSymptomsDisease("知识库-疾病症状", "3005"),
        KnowSymptomsDiseaseQ("知识库-疾病症状问题", "3006"),
        KnowSymptomsDiseaseA("知识库-疾病症状回答", "3007");
        private String name;
        private String value;
        ContentType(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 sendMDTSocketMessageToDoctor(String targetUserId, String message) {
        String imAddr = im_host + "api/v2/message/doctorSystemMessage";
        JSONObject params = new JSONObject();
        params.put("targetUserId", targetUserId);
        params.put("message", message);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    public String sendPcManageMessageToPc(String clientType, String message) {
        String imAddr = im_host + "api/v2/message/cloudCarePcManageMessage";
        JSONObject params = new JSONObject();
        params.put("clientType", clientType);
        params.put("message", message);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    public String sendPatientSystemMessage(String targetUserId, String message) {
        String imAddr = im_host + "api/v2/message/patientSystemMessage";
        JSONObject params = new JSONObject();
        params.put("targetUserId", targetUserId);
        params.put("message", message);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 发送消息
     *
     * @param senderId    发送者的code
     * @param receiverId  接受者code
     * @param contentType 消息类型 1二维码内容
     * @param content     消息内容
     * @return
     */
    public String sendMessage(String senderId, String receiverId, String contentType, String content) {
        String imAddr = im_host + "api/v2/message/send";
        JSONObject params = new JSONObject();
        params.put("sender_id", senderId);
        params.put("sender_name", receiverId);
        params.put("content_type", contentType);
        params.put("content", content);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 获取医生统计数据
     * status reply 为空值是是该医生总咨询量
     *
     * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
     * @param adminTeamCode
     * @param status
     * @param reply
     * @return
     */
    public String getConsultData(String user, Integer adminTeamCode, Integer status, Integer reply) {
        String imAddr = im_host + "api/v2/sessions/topics/count/reply";
        imAddr = imAddr + "?user=" + user;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (adminTeamCode != null) {
            imAddr += ("&adminTeamCode=" + adminTeamCode);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    public void updateTopics(String topicId, String jsonValue) {
        String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id", topicId);
        params.put("data", jsonValue);
        HttpClientUtil.putBody(imAddr, params);
    }
    /**
     * 当前医生下当前团队列表接口
     * 获取团队内医生的健康咨询状况
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
     * @param adminTeamCode 行政团队code
     * @param page
     * @param pagesize
     * @param status
     * @param reply
     * @return
     */
    public String getTeamConsultByStatus(String user, Integer adminTeamCode, Integer status, Integer reply, int page, int pagesize) {
        String imAddr = im_host + "api/v2/sessions/healthTeamTopics";
        imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
        if (adminTeamCode != null) {
            imAddr += ("&adminTeamCode=" + adminTeamCode);
        }
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 列表接口
     * 获取团队内医生的健康咨询状况
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @param user     团队就把团队的医生合并起来用,隔开(医生编码)
     * @param page
     * @param pagesize
     * @param status
     * @param reply
     * @return
     */
    public String getConsultByStatus(String user, Integer status, Integer reply, int page, int pagesize) {
        String imAddr = im_host + "api/v2/sessions/healthTopics";
        imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 咨询列表
     *
     * @param user
     * @param status   status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * @param reply
     * @param type     1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
     * @param page
     * @param pagesize
     * @return
     */
    public String getConsultByStatusAndType(String user, Integer status, Integer reply, Integer type, String patientName, String startTime, String endTime, int page, int pagesize) {
        String imAddr = im_host + "api/v2/sessions/topicListByType";
        imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        if (type != null) {
            imAddr += ("&type=" + type);
        }
        if (patientName != null) {
            imAddr += ("&patientName=" + patientName);
        }
        if (startTime != null) {
            imAddr += ("&startTime=" + startTime);
        }
        if (endTime != null) {
            imAddr += ("&endTime=" + endTime);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 咨询列表总数
     *
     * @param user
     * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * @param reply
     * @param type   1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
     * @return
     */
    public String getConsultCountByStatusAndType(String user, Integer status, Integer reply, Integer type, String patientName, String startTime, String endTime) {
        String imAddr = im_host + "api/v2/sessions/topicListCountByType";
        imAddr = imAddr + "?user=" + user;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        if (type != null) {
            imAddr += ("&type=" + type);
        }
        if (patientName != null) {
            imAddr += ("&patientName=" + patientName);
        }
        if (startTime != null) {
            imAddr += ("&startTime=" + startTime);
        }
        if (endTime != null) {
            imAddr += ("&endTime=" + endTime);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @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";
        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", extend);
        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 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 = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
		return response;
	}
	/**
	 * 更新会话状态
	 *
	 * @param sessionId 会话ID
	 * @param status    状态
	 */
	public String updateSessionStatus(String sessionId, String status) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
		JSONObject params = new JSONObject();
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	/**
	 * 更新会话状态
	 *
	 * @param sessionId 会话ID
	 * @param status    状态
	 */
	public String updateTopicEvaluate(String sessionId, String status) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
		JSONObject params = new JSONObject();
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent) {
		String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("sender_name", fromName);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("topic_id", topicId);
		params.put("agent", agent);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent,String patient_name,int patient_sex,int patient_age) {
		String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("sender_name", fromName);
		params.put("patient_name", patient_name);
		params.put("patient_sex", patient_sex);
		params.put("patient_age", patient_age);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("topic_id", topicId);
		params.put("agent", agent);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	/**
	 * 发送进入im消息
	 * IM: ParticipantUpdate:'/:session_id/participant/update'
	 *
	 * @param from
	 * @param sessionId
	 * @param topicId
	 * @return
	 */
	public String sendIntoTopicIM(String from, String sessionId, String topicId, String content, String intoUser, String intoUserName) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/into";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("topic_id", topicId);
		params.put("into_user", intoUser);
		params.put("into_user_name", intoUserName);
		params.put("content", content);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	/**
	 * 更新会话成员(新增或删除)
	 * @param sessionId 会话id
	 * @param user 新增的成员id
	 * @param oldUserId  删除的成员id
	 */
	public String updateParticipant(String sessionId, String user,String oldUserId) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId );
		params.put("user_id", user );
		if(!StringUtils.isEmpty(oldUserId)){
			params.put("old_user_id", oldUserId);
		}
		return HttpClientUtil.postBody(imAddr, params);
	}
	/**
	 * 更新会话成员(新增或删除) 活跃成员
	 * @param sessionId 会话id
	 * @param user 新增的成员id
	 * @param oldUserId  删除的成员id
	 */
	public String updateParticipantNew(String sessionId, String user,String oldUserId) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/updateNew";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId );
		params.put("user_id", user );
		if(!StringUtils.isEmpty(oldUserId)){
			params.put("old_user_id", oldUserId);
		}
		return HttpClientUtil.postBody(imAddr, params);
	}
	/**
	 * 更新消息内容
	 * @param sessionId 会话id
	 * @param sessionType 会话类型
	 * @param msgId  消息id
	 * @param content  消息内容
	 */
	public String updateMessage(String sessionId, String sessionType,String msgId,String content) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages/"+ msgId +"/update";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId );
		params.put("session_type", sessionType );
		params.put("message_id", msgId );
		params.put("content", content );
		return HttpClientUtil.postBody(imAddr, params);
	}
	/**
	 * 结束议题
	 *
	 * @param topicId     议题ID
	 * @param endUser     结束人
	 * @param endUserName 结束人名字
	 * @param sessionId   会话ID
	 */
	public JSONObject endTopics(String sessionId, String endUser, String endUserName, String topicId) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/ended";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId);
		params.put("end_user", endUser);
		params.put("end_user_name", endUserName);
		params.put("topic_id", topicId);
		String ret = HttpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	/**
	 * 议题邀请人员
	 *
	 * @param user      结束人名字
	 * @param sessionId 会话ID
	 */
	public void updateTopicUser(String sessionId, String user) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
		JSONObject params = new JSONObject();
		params.put("user", user + ":" + 0);
		HttpClientUtil.putBody(imAddr, params);
	}
	/**
	 * 创建议题
	 *
	 * @param topicId      议题ID
	 * @param topicName    议题名称
	 * @param participants 成员
	 */
	public JSONObject createTopics(String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
		String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("topic_name", topicName);
		params.put("participants", participants.toString());
		params.put("messages", messages.toString());
		params.put("session_id", sessionId);
		params.put("session_type", sessionType);
		String ret = HttpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	/**
	 * 判断会话是否存在
	 */
	public Boolean sessionIsExist(String sessionId) {
		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");
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
			if(obj.getInteger("status") ==200&&sessionId.equals(obj.getString("sessionId"))){
				String sessionStatus = obj.getString("sessionId");
				if (StringUtils.isNoneBlank(sessionStatus)){
					String sessionStatusUrl = im_host + "api/v2/sessions/"+sessionId+"/status?status=0&sessionId="+sessionId;
					JSONObject object = new JSONObject();
					String rs = HttpClientUtil.postBody(sessionStatusUrl, object);
				}
				re = true;
			}
		} catch (Exception e) {
			return null;
		}
		return re;
	}
	public Integer sessionStatus(String sessionId) {
		String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
		String ret = HttpClientUtil.get(url, "UTF-8");
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
			if(obj.getInteger("status") ==200&&sessionId.equals(obj.getString("sessionId"))){
				String session_id = obj.getString("sessionId");
				Integer sessionStatus = obj.getInteger("sessionStatus");
				return sessionStatus;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
	/**
	 * 创建会话(system)
	 */
	public static JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
        String response = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
        return response;
    }
    /**
     * 更新会话状态
     *
     * @param sessionId 会话ID
     * @param status    状态
     */
    public String updateSessionStatus(String sessionId, String status) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
        JSONObject params = new JSONObject();
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 更新会话状态
     *
     * @param sessionId 会话ID
     * @param status    状态
     */
    public String updateTopicEvaluate(String sessionId, String status) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
        JSONObject params = new JSONObject();
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent) {
        String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("topic_id", topicId);
        params.put("agent", agent);
        String response = HttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent, String patient_name, int patient_sex, int patient_age) {
        String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("patient_name", patient_name);
        params.put("patient_sex", patient_sex);
        params.put("patient_age", patient_age);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("topic_id", topicId);
        params.put("agent", agent);
        String response = HttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 发送进入im消息
     * IM: ParticipantUpdate:'/:session_id/participant/update'
     *
     * @param from
     * @param sessionId
     * @param topicId
     * @return
     */
    public String sendIntoTopicIM(String from, String sessionId, String topicId, String content, String intoUser, String intoUserName) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/into";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("topic_id", topicId);
        params.put("into_user", intoUser);
        params.put("into_user_name", intoUserName);
        params.put("content", content);
        String response = HttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 更新会话成员(新增或删除)
     *
     * @param sessionId 会话id
     * @param user      新增的成员id
     * @param oldUserId 删除的成员id
     */
    public String updateParticipant(String sessionId, String user, String oldUserId) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("user_id", user);
        if (!StringUtils.isEmpty(oldUserId)) {
            params.put("old_user_id", oldUserId);
        }
        return HttpClientUtil.postBody(imAddr, params);
    }
    /**
     * 更新会话成员(新增或删除) 活跃成员
     *
     * @param sessionId 会话id
     * @param user      新增的成员id
     * @param oldUserId 删除的成员id
     */
    public String updateParticipantNew(String sessionId, String user, String oldUserId) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/updateNew";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("user_id", user);
        if (!StringUtils.isEmpty(oldUserId)) {
            params.put("old_user_id", oldUserId);
        }
        return HttpClientUtil.postBody(imAddr, params);
    }
    /**
     * 更新消息内容
     *
     * @param sessionId   会话id
     * @param sessionType 会话类型
     * @param msgId       消息id
     * @param content     消息内容
     */
    public String updateMessage(String sessionId, String sessionType, String msgId, String content) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages/" + msgId + "/update";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("session_type", sessionType);
        params.put("message_id", msgId);
        params.put("content", content);
        return HttpClientUtil.postBody(imAddr, params);
    }
    /**
     * 结束议题
     *
     * @param topicId     议题ID
     * @param endUser     结束人
     * @param endUserName 结束人名字
     * @param sessionId   会话ID
     */
    public JSONObject endTopics(String sessionId, String endUser, String endUserName, String topicId) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/ended";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("end_user", endUser);
        params.put("end_user_name", endUserName);
        params.put("topic_id", topicId);
        String ret = HttpClientUtil.postBody(imAddr, params);
        JSONObject obj = null;
        try {
            obj = JSON.parseObject(ret);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    /**
     * 议题邀请人员
     *
     * @param user      结束人名字
     * @param sessionId 会话ID
     */
    public void updateTopicUser(String sessionId, String user) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
        JSONObject params = new JSONObject();
        params.put("user", user + ":" + 0);
        HttpClientUtil.putBody(imAddr, params);
    }
    /**
     * 创建议题
     *
     * @param topicId      议题ID
     * @param topicName    议题名称
     * @param participants 成员
     */
    public JSONObject createTopics(String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
        JSONObject obj = new JSONObject();
        try {
            String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
            JSONObject params = new JSONObject();
            params.put("topic_id", topicId);
            params.put("topic_name", topicName);
            params.put("participants", participants.toString());
            params.put("messages", messages.toString());
            params.put("session_id", sessionId);
            params.put("session_type", sessionType);
            String ret = HttpClientUtil.postBody(imAddr, params);
            obj = JSON.parseObject(ret);
            return obj;
        } catch (Exception e) {
            System.out.println("创建议题失败:topicId=>" + topicId);
            return null;
        }
    }
    /**
     * 判断会话是否存在
     */
    public Boolean sessionIsExist(String sessionId) {
        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");
        JSONObject obj = null;
        try {
            obj = JSON.parseObject(ret);
            if (obj.getInteger("status") == 200 && sessionId.equals(obj.getString("sessionId"))) {
                String sessionStatus = obj.getString("sessionId");
                if (StringUtils.isNoneBlank(sessionStatus)) {
                    String sessionStatusUrl = im_host + "api/v2/sessions/" + sessionId + "/status?status=0&sessionId=" + sessionId;
                    JSONObject object = new JSONObject();
                    String rs = HttpClientUtil.postBody(sessionStatusUrl, object);
                }
                re = true;
            }
        } catch (Exception e) {
            return null;
        }
        return re;
    }
    public Integer sessionStatus(String sessionId) {
        String url = im_host + "api/v2/sessions/isExist?session_id=" + sessionId;
        String ret = HttpClientUtil.get(url, "UTF-8");
        JSONObject obj = null;
        try {
            obj = JSON.parseObject(ret);
            if (obj.getInteger("status") == 200 && sessionId.equals(obj.getString("sessionId"))) {
                String session_id = obj.getString("sessionId");
                Integer sessionStatus = obj.getInteger("sessionStatus");
                return sessionStatus;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
    /**
     * 创建会话(system)
     */
    public static JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
//		String imAddr = im_host + "api/v2/sessions";
		String imAddr = ImService.im_host + "/sessions";
		JSONObject params = new JSONObject();
		params.put("participants", participants.toString());
		params.put("session_name", sessionName);
		params.put("session_type", sessionType);
		params.put("session_id", sessionId);
        String imAddr = ImService.im_host + "/sessions";
        JSONObject params = new JSONObject();
        params.put("participants", participants.toString());
        params.put("session_name", sessionName);
        params.put("session_type", sessionType);
        params.put("session_id", sessionId);
//		String ret = HttpClientUtil.postBody(imAddr, params);
		String ret = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	/**
	 * 获取会话实例的消息对象
	 *
	 * @param senderId
	 * @param senderName
	 * @param title
	 * @param description
	 * @param images
	 * @param agent
	 * @return
	 */
	public JSONObject getCreateTopicMessage(String senderId, String senderName, String title, String description, String images, String agent) {
		JSONObject messages = new JSONObject();
		messages.put("description", description);
		messages.put("title", title);
		messages.put("img", images);
		messages.put("sender_id", senderId);
		messages.put("sender_name", senderName);
		messages.put("agent", agent);
		return messages;
	}
	public JSONObject getTopicMessage(String topicId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
				+ "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException(obj.getString("message"));
			} else {
				return obj.getJSONObject("data");
			}
		} catch (Exception e) {
			return null;
		}
	}
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			JSONArray obj = JSON.parseArray(ret);
			return obj;
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 删除对应的成员信息在MUC模式中
	 *
	 * @param userId
	 * @param oldUserId
	 * @param sessionId
	 * @return
	 */
	public JSONObject deleteMucUser(String userId, String oldUserId, String sessionId) throws Exception {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
		try {
			JSONObject params = new JSONObject();
			params.put("user_id", userId);
			params.put("old_user_id", oldUserId);
			params.put("session_id", sessionId);
			String ret = HttpClientUtil.postBody(url, params);
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("人员更换失败!");
			} else {
				return obj;
			}
		} catch (Exception e) {
			throw new RuntimeException("人员更换失败!");
		}
	}
	/**
	 * 删除会话人员
	 * @param sessionId
	 * @param participants
	 * @return
	 */
	public JSONObject deleteParticipants(String sessionId,String participants){
		String url  = im_host+"api/v2/sessions/"+sessionId+"/participants/"+participants;
		String rs = com.yihu.jw.util.http.HttpClientUtil.doDelete(url,null,null);
		JSONObject obj = JSONObject.parseObject(rs);
		if (obj.getInteger("status")==-1){
			throw new RuntimeException("删除会话人员失败!");
		}else {
			return obj;
		}
	}
	/**
	 * 获取议题
	 *
	 * @param topicId
	 * @return
	 */
	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");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("获取议题失败!");
			} else {
				return obj;
			}
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
		}
	}
	/**
	 * 获取会话成员
	 *
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	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");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
	/**
	 * 获取会话成员
	 *
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	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");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
		}
	}
	public JSONObject cleanMessageToRedis(String sessionId){
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
		}
	}
	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");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
		}
	}
	/**
	 * 根据session和userid获取单个会话
	 * @param sessionId
	 * @param userId
	 * @return
	 */
	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");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
		}
	}
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param to
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendIM(String from, String to, String contentType, String content) {
		String imAddr = im_host + "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;
	}
	public static final String SESSION_TYPE_MUC = "1";
	public static final String SESSION_TYPE_P2P = "2";
	public static final String SESSION_TYPE_GROUP = "3";
	public static final String SESSION_TYPE_SYSTEM = "0";
	public static final String SESSION_TYPE_PRESCRIPTION = "8";//续方
	public static final String SESSION_TYPE_KANGFU = "18";//续方
	public static final String SESSION_TYPE_EXAMINATION = "9";//在线复诊-图文
	public static final String SESSION_TYPE_ONDOOR_NURSING = "11";//上门护理
	public static final String SESSION_TYPE_COLLABORATION_HOSPITAL = "12";///互联网医院协同门诊
	public static final String SESSION_TYPE_GUIDANCE_HOSPITAL = "14";//互联网医院居民导诊聊天
	public static final String SESSION_TYPE_GENERAL_EXPERT = "15";//全科医生发起求助专科医生的专家咨询
	public static final String SESSION_TYPE_EXAMINATION_VIDEO = "16";//在线复诊-视频
	public static final String SESSION_TYPE_MUC_VIDEO = "17";//专家-视频
	public static final String SESSION_TYPE_GUIDANCE_ASSISTANT = "18";//导诊助手
	public static final String SESSION_STATUS_PROCEEDINGS = "0";
	public static final String SESSION_STATUS_END = "1";
	public static final String SESSION_TYPE_EMERGENCY_ASSISTANCE = "20";//紧急救助
	public static final String SESSION_TYPE_DOOR_COACH = "21";//上门辅导(上门预约)
	public static final String SESSION_TYPE_SECURITY_WARN = "22";//安防咨询
	public static final String SESSION_TYPE_ONLINE = "23";//新生儿在线咨询
	public static final String SESSION_TYPE_ONLINEAged = "24";//老人在线咨询
	public static final String SESSION_TYPE_HealthConsult = "25";//老人在线咨询
	public static final String CONTENT_TYPE_TEXT = "1";
	/**
	 *按会话类型获取会话总数
	 * @param userid
	 * @param type
	 * @param status
	 * @return
	 */
	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");
		JSONObject obj = JSON.parseObject(ret);
		if(obj.getInteger("status") ==200){
			return obj.getInteger("count");
		}else{
			return 0;
		}
	}
	public Integer SessionsUnreadMessageCountByUserId(String userid){
		String url = im_host + "api/v2/sessions/unread_message_count?user_id="+userid;
        String ret = com.yihu.jw.util.http.HttpClientUtil.postBodyStatic(imAddr, params);
        JSONObject obj = null;
        try {
            obj = JSON.parseObject(ret);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    /**
     * 获取会话实例的消息对象
     *
     * @param senderId
     * @param senderName
     * @param title
     * @param description
     * @param images
     * @param agent
     * @return
     */
    public JSONObject getCreateTopicMessage(String senderId, String senderName, String title, String description, String images, String agent) {
        JSONObject messages = new JSONObject();
        messages.put("description", description);
        messages.put("title", title);
        messages.put("img", images);
        messages.put("sender_id", senderId);
        messages.put("sender_name", senderName);
        messages.put("agent", agent);
        return messages;
    }
    public JSONObject getTopicMessage(String topicId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
        String url = im_host
                + "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
                + "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
        try {
            String ret = HttpClientUtil.get(url, "UTF-8");
            JSONObject obj = JSON.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException(obj.getString("message"));
            } else {
                return obj.getJSONObject("data");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
        try {
            String ret = HttpClientUtil.get(url, "UTF-8");
            JSONArray obj = JSON.parseArray(ret);
            return obj;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 删除对应的成员信息在MUC模式中
     *
     * @param userId
     * @param oldUserId
     * @param sessionId
     * @return
     */
    public JSONObject deleteMucUser(String userId, String oldUserId, String sessionId) throws Exception {
        String url = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
        try {
            JSONObject params = new JSONObject();
            params.put("user_id", userId);
            params.put("old_user_id", oldUserId);
            params.put("session_id", sessionId);
            String ret = HttpClientUtil.postBody(url, params);
            JSONObject obj = JSON.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException("人员更换失败!");
            } else {
                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException("人员更换失败!");
        }
    }
    /**
     * 删除会话人员
     *
     * @param sessionId
     * @param participants
     * @return
     */
    public JSONObject deleteParticipants(String sessionId, String participants) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/participants/" + participants;
        String rs = com.yihu.jw.util.http.HttpClientUtil.doDelete(url, null, null);
        JSONObject obj = JSONObject.parseObject(rs);
        if (obj.getInteger("status") == -1) {
            throw new RuntimeException("删除会话人员失败!");
        } else {
            return obj;
        }
    }
    /**
     * 获取议题
     *
     * @param topicId
     * @return
     */
    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");
            JSONObject obj = JSON.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException("获取议题失败!");
            } else {
                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException("获取议题失败!");
        }
    }
    /**
     * 获取会话成员
     *
     * @param sessionId
     * @return
     * @throws Exception
     */
    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");
            return JSON.parseArray(ret);
        } catch (Exception e) {
            throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
        }
    }
    /**
     * 获取会话成员
     *
     * @param sessionId
     * @return
     * @throws Exception
     */
    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");
            return JSON.parseArray(ret);
        } catch (Exception e) {
            throw new RuntimeException("获取议题失败!");
        }
    }
    public JSONObject cleanMessageToRedis(String sessionId) {
        String url = im_host + "api/v2/message/dataMessage?sessionId=" + sessionId;
        try {
            String ret = HttpClientUtil.get(url, "utf-8");
            return JSON.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("操作失败!");
        }
    }
    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");
            return JSON.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("操作失败!");
        }
    }
    /**
     * 根据session和userid获取单个会话
     *
     * @param sessionId
     * @param userId
     * @return
     */
    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");
            return JSON.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("操作失败!");
        }
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param to
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public String sendIM(String from, String to, String contentType, String content) {
        String imAddr = im_host + "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;
    }
    public static final String SESSION_TYPE_MUC = "1";
    public static final String SESSION_TYPE_P2P = "2";
    public static final String SESSION_TYPE_GROUP = "3";
    public static final String SESSION_TYPE_SYSTEM = "0";
    public static final String SESSION_TYPE_PRESCRIPTION = "8";//续方
    public static final String SESSION_TYPE_KANGFU = "18";//续方
    public static final String SESSION_TYPE_EXAMINATION = "9";//在线复诊-图文
    public static final String SESSION_TYPE_ONDOOR_NURSING = "11";//上门护理
    public static final String SESSION_TYPE_COLLABORATION_HOSPITAL = "12";///互联网医院协同门诊
    public static final String SESSION_TYPE_GUIDANCE_HOSPITAL = "14";//互联网医院居民导诊聊天
    public static final String SESSION_TYPE_GENERAL_EXPERT = "15";//全科医生发起求助专科医生的专家咨询
    public static final String SESSION_TYPE_EXAMINATION_VIDEO = "16";//在线复诊-视频
    public static final String SESSION_TYPE_MUC_VIDEO = "17";//专家-视频
    public static final String SESSION_TYPE_GUIDANCE_ASSISTANT = "18";//导诊助手
    public static final String SESSION_STATUS_PROCEEDINGS = "0";
    public static final String SESSION_STATUS_END = "1";
    public static final String SESSION_TYPE_EMERGENCY_ASSISTANCE = "20";//紧急救助
    public static final String SESSION_TYPE_DOOR_COACH = "21";//上门辅导(上门预约)
    public static final String SESSION_TYPE_SECURITY_WARN = "22";//安防咨询
    public static final String SESSION_TYPE_ONLINE = "23";//新生儿在线咨询
    public static final String SESSION_TYPE_ONLINEAged = "24";//老人在线咨询
    public static final String SESSION_TYPE_HealthConsult = "25";//老人在线咨询
    public static final String CONTENT_TYPE_TEXT = "1";
    /**
     * 按会话类型获取会话总数
     *
     * @param userid
     * @param type
     * @param status
     * @return
     */
    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");
        JSONObject obj = JSON.parseObject(ret);
        if (obj.getInteger("status") == 200) {
            return obj.getInteger("count");
        } else {
            return 0;
        }
    }
    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");
		JSONObject obj = JSON.parseObject(ret);
        String ret = HttpClientUtil.get(url, "utf-8");
        JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
        return obj.getInteger("count");
//		}else{
//			return 0;
//		}
	}
	/**
	 *获取所有会话未读消息数。
	 * @param userid
	 * @param type
	 * @return
	 */
	public Integer SessionsUnreadMessageCount(String userid,String type){
		String url = im_host + "api/v2/sessions/unread_message_count?user_id="+userid+"&type="+type;
		String ret = HttpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
    }
    /**
     * 获取所有会话未读消息数。
     *
     * @param userid
     * @param type
     * @return
     */
    public Integer SessionsUnreadMessageCount(String userid, String type) {
        String url = im_host + "api/v2/sessions/unread_message_count?user_id=" + userid + "&type=" + type;
        String ret = HttpClientUtil.get(url, "utf-8");
        JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
        return obj.getInteger("count");
//		}else{
//			return 0;
//		}
	}
	/**
	 *获取某个会话某个对象的未读消息数。
	 * @param
	 * @return
	 */
	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");
		JSONObject obj = JSON.parseObject(ret);
    }
    /**
     * 获取某个会话某个对象的未读消息数。
     *
     * @param
     * @return
     */
    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");
        JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
        return obj.getInteger("count");
//		}else{
//			return 0;
//		}
	}
	/**
	 * 获取会话未读消息数量
	 * @param sessionId
	 * @param userId
	 * @return
	 */
	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");
			return  JSONObject.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
	/**
	 * 获取在线人数
	 * helper 社工,teacher 教师,child 幼儿,olderWx 老人公众号,olderPad 老人平板
	 */
	public String getOnlineCountByType(String type) {
		String url = im_host + "api/v2/sessions/getOnlineCountByType?type="+type;
		String ret = HttpClientUtil.get(url, "UTF-8");
		return ret;
	}
	/**
	 * 获取在线人数列表
	 * helper 社工,teacher 教师,child 幼儿,olderWx 老人公众号,olderPad 老人平板
	 */
	public String getOnlineListByType(String type) {
		String url = im_host + "api/v2/sessions/getOnlineListByType?type="+type;
		String ret = HttpClientUtil.get(url, "UTF-8");
		return ret;
	}
	/**
	 * 获取在线状态
	 * helper 社工,teacher 教师,child 幼儿,older 老人
	 * 返回 {"status":200,"data":1} data>0 说明在线 data =0 不在线
	 */
	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");
		return ret;
	}
	/**
	 *按会话类型、会话状态获取会话列表
	 * @param user_id
	 * @param page
	 * @param size
	 * @param type
	 * @param status 不传为获取所有状态
	 * @param name
	 * @param search_type 仅当type为2时有效 1与医生p2p会话 2与患者p2p
	 * @return
	 */
	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");
		return ret;
	}
    }
    /**
     * 获取会话未读消息数量
     *
     * @param sessionId
     * @param userId
     * @return
     */
    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");
            return JSONObject.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
        }
    }
    /**
     * 获取在线人数
     * helper 社工,teacher 教师,child 幼儿,olderWx 老人公众号,olderPad 老人平板
     */
    public String getOnlineCountByType(String type) {
        String url = im_host + "api/v2/sessions/getOnlineCountByType?type=" + type;
        String ret = HttpClientUtil.get(url, "UTF-8");
        return ret;
    }
    /**
     * 获取在线人数列表
     * helper 社工,teacher 教师,child 幼儿,olderWx 老人公众号,olderPad 老人平板
     */
    public String getOnlineListByType(String type) {
        String url = im_host + "api/v2/sessions/getOnlineListByType?type=" + type;
        String ret = HttpClientUtil.get(url, "UTF-8");
        return ret;
    }
    /**
     * 获取在线状态
     * helper 社工,teacher 教师,child 幼儿,older 老人
     * 返回 {"status":200,"data":1} data>0 说明在线 data =0 不在线
     */
    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");
        return ret;
    }
    /**
     * 按会话类型、会话状态获取会话列表
     *
     * @param user_id
     * @param page
     * @param size
     * @param type
     * @param status      不传为获取所有状态
     * @param name
     * @param search_type 仅当type为2时有效 1与医生p2p会话 2与患者p2p
     * @return
     */
    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");
        return ret;
    }
}

+ 171 - 1
common/common-entity/src/db/2023.sql

@ -50,4 +50,174 @@ ALTER table base_team add COLUMN `dept_name` varchar(50) DEFAULT NULL COMMENT '
ALTER table base_team add COLUMN `img` varchar(255) DEFAULT NULL COMMENT '图片';
-- 2023-02-27
base_patient_doctor 暂时用来代替 wlyy_sign_family
base_patient_doctor 暂时用来代替 wlyy_sign_family
==========================开始==================================
ALTER TABLE `base`.`wlyy_rehabilitation_plan_template`
ADD COLUMN `disease_id` varchar(50) NULL COMMENT '病种code' AFTER `update_time`,
ADD COLUMN `disease_name` varchar(50) NULL COMMENT '病种name' AFTER `update_time`,
ADD COLUMN `status` varchar(10) NULL COMMENT '状态是否生效' AFTER `disease_id`;
ALTER TABLE `base`.`wlyy_rehabilitation_plan_template`
ADD COLUMN `type` varchar(255) NULL COMMENT 'template表示模板,plan表示计划' AFTER `status`;
ALTER TABLE `base`.`wlyy_rehabilitation_template_detail`
ADD COLUMN `assess_type` varchar(10) NULL COMMENT '项目评价' AFTER `expense`,
ADD COLUMN `booking_type` varchar(10) NULL COMMENT '是否预约' AFTER `assess_type`,
ADD COLUMN `late_serve_type` varchar(10) NULL COMMENT '是否运行逾期服务' AFTER `booking_type`,
ADD COLUMN `plan_start_time_type` varchar(10) NULL COMMENT '计划开始时间类型' AFTER `late_serve_type`,
ADD COLUMN `server_time_type` varchar(10) NULL COMMENT '服务方法' AFTER `plan_start_time_type`,
ADD COLUMN `server_count` varchar(10) NULL COMMENT '服务次数' AFTER `server_time_type`,
ADD COLUMN `pricing_units_code` varchar(10) NULL COMMENT '计价单位' AFTER `server_count`;
ADD COLUMN `pricing_units_name` varchar(10) NULL COMMENT '计价单位名称' AFTER `pricing_units_name`;
ALTER TABLE `base`.`base_service_package_item`
ADD COLUMN `leased_code` varchar(100) NULL COMMENT '租户code' AFTER `topic_item`,
ADD COLUMN `leased_name` varchar(50) NULL COMMENT '租户name' AFTER `leased_code`,
ADD COLUMN `sub_item_type` varchar(10) NULL COMMENT '是否包含子项目' AFTER `leased_name`;
ALTER TABLE `base`.`base_service_package_item`
ADD COLUMN `template_type` varchar(20) NULL COMMENT '模板的类型-目前是随访为1' AFTER `sub_item_type`,
ADD COLUMN `template_code` varchar(255) NULL COMMENT '对应模板的id' AFTER `template_type`;
CREATE TABLE `base`.`base_service_item_config`  (
  `id` varchar(100) NOT NULL COMMENT '主键',
  `package_id` varchar(100) NULL COMMENT '服务包id',
  `server_item_id` varchar(100) NULL COMMENT '服务项id',
  `assess_type` varchar(100) NULL COMMENT '项目评价',
  `booking_type` varchar(100) NULL COMMENT '是否预约',
  `late_serve_type` varchar(100) NULL COMMENT '是否运行逾期服务',
  `plan_start_time_type` varchar(100) NULL COMMENT '计划开始时间类型',
  `server_time_type` varchar(100) NULL COMMENT '服务方法',
  `server_count` varchar(100) NULL COMMENT '服务次数',
  `template_type` varchar(100) NULL COMMENT '模板的类型-目前是随访为1',
  `template_code` varchar(100) NULL COMMENT '对应模板的id',
  PRIMARY KEY (`id`)
);
CREATE TABLE `template_json` (
  `id`  varchar(100)  NOT NULL COMMENT '主键',
  `template_id` varchar(100) DEFAULT NULL COMMENT '模板id',
  `template_name` varchar(50) DEFAULT NULL COMMENT '模板名称',
  `template_json` text COMMENT '模板json',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `create_user` varchar(255) DEFAULT NULL COMMENT '创建人',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE `base`.`base_service_package`
ADD COLUMN `leased_code` varchar(50) NULL COMMENT '租户code' AFTER `org_name`,
ADD COLUMN `leased_name` varchar(50) NULL COMMENT '租户name' AFTER `leased_code`,
ADD COLUMN `server_time_type` varchar(20) NULL COMMENT '服务时间类型' AFTER `leased_name`,
ADD COLUMN `server_time` varchar(50) NULL COMMENT '服务期限' AFTER `server_time_type`,
ADD COLUMN `server_time_description` varchar(255) NULL COMMENT '服务时间说明' AFTER `server_time`,
ADD COLUMN `create_user` varchar(50) NULL COMMENT '创建人code' AFTER `server_time_description`,
ADD COLUMN `create_user_name` varchar(20) NULL COMMENT '创建人name' AFTER `create_user`,
ADD COLUMN `update_user` varchar(50) NULL COMMENT '更新人code' AFTER `create_user_name`,
ADD COLUMN `update_user_name` varchar(50) NULL COMMENT '更新人name' AFTER `update_user`,
ADD COLUMN `update_time` datetime NULL COMMENT '更新时间' AFTER `create_time`;
CREATE TABLE `base`.`base_service_package_sub_item`  (
  `id` varchar(100) NOT NULL COMMENT '主键',
  `name` varchar(100) NULL COMMENT '名称',
  `item_id` varchar(100) NULL COMMENT '项目的id',
  `introduce` varchar(255) NULL COMMENT '说明',
  `status` varchar(10) NULL COMMENT '状态',
  `sort` varchar(10) NULL,
  `leased_code` varchar(100) NULL,
  `leased_name` varchar(100) NULL,
  `org_code` varchar(100) NULL COMMENT '机构code',
  `org_name` varchar(100) NULL COMMENT '机构name',
  `photo` varchar(100) NULL COMMENT '照片',
  `create_time` varchar(100) NULL COMMENT '照片',
  `create_time` datetime ;
  PRIMARY KEY (`id`)
);
ALTER TABLE `base`.`base_service_package_sub_item`
ADD COLUMN `item_id` varchar(100) NULL COMMENT '父项目id' AFTER `id`;
CREATE TABLE `base`.`base_service_package_item_relational`  (
  `id` varchar(100) NOT NULL COMMENT '主键',
  `item_id` varchar(100) NULL COMMENT '项目id',
  `sub_item_id` varchar(100) NULL COMMENT '子项目id',
  PRIMARY KEY (`id`)
);
CREATE TABLE `base`.`base_followup_template`  (
  `id` varchar(100) NOT NULL,
  `template_name` varchar(255) NULL,
  `followup_statrt_time_type` varchar(100) NULL,
  `followup_count` varchar(10) NULL,
  `description` varchar(255) NULL,
  `template_detail_json` text NULL,
  `status` varchar(10) NULL,
  `leased_code` varchar(100) NULL,
  `leased_name` varchar(100) NULL,
  `org_code` varchar(100) NULL,
  `org_name` varchar(255) NULL,
  `create_time` datetime NULL,
  `update_time` datetime NULL,
  `create_user` varchar(100) NULL,
  `create_user_name` varchar(100) NULL,
  `update_user` varchar(100) NULL,
  `update_user_name` varchar(100) NULL,
  PRIMARY KEY (`id`)
);
ALTER TABLE `base`.`base_disease_hospital`
ADD COLUMN `rehabilitation_type` varchar(100) NULL COMMENT '是否开通诊后康复 0否 1是' AFTER `sort`,
ADD COLUMN `rehabilitation_down_type` varchar(100) NULL COMMENT '康复下转 1自动 2手动' AFTER `rehabilitation_type`,
ADD COLUMN `rehabilitation_template_id` varchar(100) NULL COMMENT '康复计划模板id' AFTER `rehabilitation_down_type`;
ALTER TABLE `base`.`base_service_package_sub_item`
CHANGE COLUMN `item_id` `dict_item_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '字典配置的服务项的id' AFTER `id`;
ALTER TABLE `base`.`base_service_package_item`
ADD COLUMN `service_package_item_id` varchar(50) NULL COMMENT '创建服务项的id。也是本表的id。system那些数据' AFTER `service_package_id`;
ALTER TABLE `base`.`wlyy_rehabilitation_template_detail`
ADD COLUMN `template_type` varchar(100) NULL COMMENT '随访模板类型' AFTER `pricing_units_name`,
ADD COLUMN `template_code` varchar(100) NULL COMMENT '随访模板id' AFTER `template_type`;
ALTER TABLE `base`.`base_service_item_config`
ADD COLUMN `pricing_units_code` varchar(100) NULL COMMENT '计价单位' AFTER `template_code`,
ADD COLUMN `pricing_units_name` varchar(100) NULL COMMENT '计价单位名称' AFTER `pricing_units_code`;
ALTER TABLE `base`.`base_service_item_config`
ADD COLUMN `frequency_code` varchar(100) NULL COMMENT '频次' AFTER `pricing_units_name`;
===========================结束=================================
-- 2023-10-31 ysj 计算百分比函数
CREATE FUNCTION percentage(numerator FLOAT, denominator FLOAT) RETURNS VARCHAR(255)
    NO SQL
BEGIN
  DECLARE result VARCHAR(255);
	IF numerator IS NULL OR numerator=0 THEN
    SET result = '0%';
  ELSEIF (denominator = 0 OR denominator is null) AND numerator > 0 THEN
    SET result = '100%';
  ELSEIF denominator IS NULL THEN
    SET result = '0%';
ELSE
    SET result = CONCAT(ROUND((numerator / denominator) * 100, 2), '%');
END IF;
RETURN result;
END;

+ 121 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServiceItemPlanDO.java

@ -0,0 +1,121 @@
package com.yihu.jw.entity.base.servicePackage;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 服务项执行计划
 * Created by yeshijie on 2023/10/28.
 */
@Entity
@Table(name = "base_service_item_plan")
public class ServiceItemPlanDO extends UuidIdentityEntityWithCreateTime {
    private String patient;//居民id
    private String status;//状态0未完成 1已完成
    private String planTime;//计划时间
    private String completeTime;//完成时间
    private String signId;//签约id
    private String servicePackId;//服务包id
    private String serviceItemId;//服务项id
    private String itemConfigId;//服务项配置id
    private String name;//服务项名称
    private String relationCode;//关联业务id
    private String relationType;//关联业务类型 doorService上门服务
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "status")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @Column(name = "sign_id")
    public String getSignId() {
        return signId;
    }
    public void setSignId(String signId) {
        this.signId = signId;
    }
    @Column(name = "service_pack_id")
    public String getServicePackId() {
        return servicePackId;
    }
    public void setServicePackId(String servicePackId) {
        this.servicePackId = servicePackId;
    }
    @Column(name = "service_item_id")
    public String getServiceItemId() {
        return serviceItemId;
    }
    public void setServiceItemId(String serviceItemId) {
        this.serviceItemId = serviceItemId;
    }
    @Column(name = "item_config_id")
    public String getItemConfigId() {
        return itemConfigId;
    }
    public void setItemConfigId(String itemConfigId) {
        this.itemConfigId = itemConfigId;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
    }
    public void setRelationCode(String relationCode) {
        this.relationCode = relationCode;
    }
    @Column(name = "relation_type")
    public String getRelationType() {
        return relationType;
    }
    public void setRelationType(String relationType) {
        this.relationType = relationType;
    }
    public String getPlanTime() {
        return planTime;
    }
    @Column(name = "plan_time")
    public void setPlanTime(String planTime) {
        this.planTime = planTime;
    }
    public String getCompleteTime() {
        return completeTime;
    }
    @Column(name = "complete_time")
    public void setCompleteTime(String completeTime) {
        this.completeTime = completeTime;
    }
}

+ 11 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServicePackageSubItemDO.java

@ -6,6 +6,7 @@ import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
@ -49,6 +50,16 @@ public class ServicePackageSubItemDO extends UuidIdentityEntity implements java.
    @Column(name = "create_time")
    private Date createTime;
    @Column(name = "price")
    private BigDecimal price;
    public BigDecimal getPrice() {
        return price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    public String getName() {
        return name;

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

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

@ -214,6 +214,12 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    }
    private String packageId;//服务包的id
    private String feeAfter;//服务后收费标识(1是0否)
    private String signId;//签约id
    /**
     * 服务编号
     */
@ -1259,4 +1265,28 @@ public class WlyyDoorServiceOrderDO extends UuidIdentityEntityWithOperator {
    public void setNursingStaffType(String nursingStaffType) {
        this.nursingStaffType = nursingStaffType;
    }
    public String getPackageId() {
        return packageId;
    }
    public void setPackageId(String packageId) {
        this.packageId = packageId;
    }
    public String getFeeAfter() {
        return feeAfter;
    }
    public void setFeeAfter(String feeAfter) {
        this.feeAfter = feeAfter;
    }
    public String getSignId() {
        return signId;
    }
    public void setSignId(String signId) {
        this.signId = signId;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/ehr/resource/RsResource.java

@ -27,7 +27,7 @@ public class RsResource extends BaseAssignedEntity {
    private String grantType;
    // 描述
    private String description;
    // 资源类型
    // 资源类型 1档案数据 2指标统计
    private Integer dataSource;
    //指标视图展示类型
    private String echartType;

+ 10 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/ehr/resource/RsResourceMetadata.java

@ -17,6 +17,7 @@ public class RsResourceMetadata implements Serializable {
    private String groupType;
    private String groupData;
    private String description;
    private Integer sort;//排序 从小到大
    private String dictId;
    private String stdCode;
@ -85,6 +86,15 @@ public class RsResourceMetadata implements Serializable {
        this.groupData = groupData;
    }
    @Column(name="sort")
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    @Transient
    public String getDictId() {
        return dictId;

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

+ 12 - 1
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/qvo/ParamQvo.java

@ -22,12 +22,23 @@ public class ParamQvo {
    private String dictItemId;//字典服务项id
    private String configureIf;//是否是配置
    private String pageIf;//是否分页
    private int page = 1;//是否分页
    private int pageSize = 20;//数量
    private String loginUserCode;//登录人的code
    public String getLoginUserCode() {
        return loginUserCode;
    }
    public void setLoginUserCode(String loginUserCode) {
        this.loginUserCode = loginUserCode;
    }
    public String getDictItemId() {
        return dictItemId;
    }

+ 236 - 2
common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java

@ -1,10 +1,35 @@
package com.yihu.jw.util.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.jw.entity.util.SystemConfEntity;
import com.yihu.jw.util.fastdfs.FastDFSUtil;
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.beans.factory.annotation.Value;
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 java.io.File;
import java.io.UnsupportedEncodingException;
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;
@ -15,8 +40,22 @@ 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("-", "");
    }
@ -104,4 +143,199 @@ public class CommonUtil {
        }
        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;
        }
    }
}

+ 2 - 0
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/BasicZuulFilter.java

@ -109,6 +109,7 @@ public class BasicZuulFilter extends ZuulFilter {
                url.contains("/weixin")||
                url.contains("/excelControl")||
                url.contains("/open/gc")||
                url.contains("/exportExcel")||
                url.contains("/prescription/pushListWrite")||
                url.contains("/prescription/pushListDrug")||
                url.contains("/open/noLogin/pushYkCardCharge")||
@ -141,6 +142,7 @@ public class BasicZuulFilter extends ZuulFilter {
                || url.contains("/sms_gateway/send")//发送短信
                || url.contains("/accountAppeal/create")
                || url.contains("/open/")//开放接口
                || url.contains("/exportExcel/")//导出
                || url.contains("/cloudCare/noLogin/")//医疗云开放接口
                || url.contains("/image/")//获取默认图片
                ||url.contains("/weixin")||

+ 1 - 19
gateway/ag-basic/src/main/java/com/yihu/jw/gateway/filter/PostFilter.java

@ -1,20 +1,9 @@
package com.yihu.jw.gateway.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yihu.jw.entity.base.dict.BaseExceptionLogDO;
import com.yihu.jw.entity.base.dict.BaseExceptionServerDictDO;
import com.yihu.jw.entity.hospital.prescription.BaseAdviceTreatmentDO;
import com.yihu.jw.gateway.AesEncryptUtils;
import com.yihu.jw.gateway.methlog.BaseExceptionService;
import com.yihu.jw.gateway.security.BeanUtil;
import com.yihu.jw.restmodel.exception.dao.BaseExceptionLogDao;
import com.yihu.jw.restmodel.exception.dao.BaseExceptionServerDictDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ -22,9 +11,6 @@ import org.springframework.util.StreamUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
@ -67,12 +53,8 @@ public class PostFilter extends ZuulFilter {
                url.contains("/open/noLogin/pushArticleCountExcel")||
                url.contains("/prescription/searchRecordWrite")||
                url.contains("/Funds/reconciliationExcel")||
                url.contains("/exportExcel/")||
                url.contains("/servicePackageSubItem/exportSubItemExcel")|| //导出
                url.contains("/Funds/deviceInfoExcel")){
            return true;
        }

+ 3 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/specialist/rehabilitation/RehabilitationPlanController.java

@ -146,6 +146,9 @@ public class RehabilitationPlanController extends EnvelopRestEndpoint {
    public ObjEnvelop deleteRehabilitationPlanTemplate(
            @ApiParam(name = "id", value = "康复模板id") @RequestParam(value = "id", required = true) String id) {
        try {
            if("system".equals(id)){
                return ObjEnvelop.getError("系统模板不允许删除");
            }
            return rehabilitationPlanService.deleteRehabilitationPlanTemplate(id);
        } catch (Exception e) {
            e.printStackTrace();

+ 7 - 5
svr/svr-base/src/main/java/com/yihu/jw/base/service/specialist/rehabilitation/RehabilitationPlanService.java

@ -7,12 +7,13 @@ import com.yihu.jw.base.dao.specialist.rehabilitation.*;
import com.yihu.jw.base.service.specialist.SpecialistHospitalServiceItemService;
import com.yihu.jw.base.service.specialist.SpecialistService;
import com.yihu.jw.base.vo.TemplateDetailVo;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.rehabilitation.RehabilitationPlanningDO;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.disease.dao.RehabilitationPlanTemplateDao;
import com.yihu.jw.hospital.disease.dao.RehabilitationTemplateDetailDao;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.qvo.ParamQvo;
import com.yihu.jw.restmodel.specialist.PatientSignInfoVO;
@ -27,7 +28,6 @@ import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -586,10 +586,12 @@ public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlan
    }
    public ListEnvelop findFrequencyList() {
        String sql = " SELECT * FROM `base`.`wlyy_frequency` WHERE del='1' ";
        List<Frequency> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Frequency.class));
//        String sql = " SELECT * FROM `base`.`wlyy_frequency` WHERE del='1' ";
//        List<Frequency> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Frequency.class));
//        return ListEnvelop.getSuccess(SpecialistMapping.api_success, list);
        String sql = " SELECT dict_code 'code',dict_value 'name' from wlyy_hospital_sys_dict WHERE dict_name = 'plan_frequency' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return ListEnvelop.getSuccess(SpecialistMapping.api_success, list);
    }
}

+ 109 - 5
svr/svr-basic/src/main/java/com/yihu/jw/basic/agadmin/controller/resource/ResourceIntegratedController.java

@ -1,11 +1,12 @@
package com.yihu.jw.basic.agadmin.controller.resource;
import com.yihu.jw.basic.resource.dao.ResourceBrowseMetadataDao;
import com.yihu.jw.basic.resource.service.ResourceBrowseService;
import com.yihu.jw.basic.resource.service.ResourceIntegratedService;
import com.yihu.jw.basic.resource.service.RsResourceDefaultParamService;
import com.yihu.jw.basic.resource.service.RsResourceService;
import com.yihu.jw.basic.util.WorkbookUtil;
import com.yihu.jw.entity.ehr.id.BizObject;
import com.yihu.jw.entity.ehr.resource.RsResource;
import com.yihu.jw.entity.ehr.resource.RsResourceDefaultParam;
@ -16,28 +17,28 @@ import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.NumberUtil;
import com.yihu.jw.util.network.HttpResponse;
import com.yihu.jw.util.network.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.Cell;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
/**
 * Controller - 资源综合查询服务控制器
@ -62,6 +63,10 @@ public class ResourceIntegratedController extends EnvelopRestEndpoint {
    private RsResourceService rsResourceService;
    @Autowired
    private ResourceBrowseService resourceBrowseService;
    @Autowired
    private ResourceBrowseMetadataDao resourceBrowseMetadataDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 综合查询档案数据列表树 zuul
@ -102,13 +107,63 @@ public class ResourceIntegratedController extends EnvelopRestEndpoint {
     * @return
     */
    @GetMapping("/metadata")
    public Envelop getMetadataList1(String categoryId, String filters, String dataSource) throws Exception {
        String url = "/resource/api/v1.0/resources/integrated/metadata";
        //标准分类
//        long start = System.currentTimeMillis();
        List<Map<String, Object>> list = resourcesIntegratedService.metadata(categoryId,  filters,dataSource);
//        List<Map<String, Object>> list = resourcesIntegratedService.intMetadata(categoryId, "*", "*", "standard", filters);
//        long end = System.currentTimeMillis();
//        System.out.println("newTime:"+(end-start));
        return ListEnvelop.getSuccess("查询成功",list);
    }
    /**
     * 综合查询档案数据资源列表 zuul
     * @param filters
     * @return
     */
    @GetMapping("/metadataOld")
    public Envelop getMetadataList(String categoryId, String filters, HttpServletRequest request) throws Exception {
        String url = "/resource/api/v1.0/resources/integrated/metadata";
        //标准分类
        long start = System.currentTimeMillis();
        List<Map<String, Object>> list = resourcesIntegratedService.intMetadata(categoryId, "*", "*", "standard", filters);
        long end = System.currentTimeMillis();
        System.out.println("time:"+(end-start));
        return ListEnvelop.getSuccess("查询成功",list);
    }
    @GetMapping("findDict")
    @ApiOperation("字典")
    public Envelop findDict(@ApiParam(name = "dictName", value = "字典名称 groupScreeningStatus1分组,town区 org等级医院 hospital社区医院 copdgroup管理状态")
                            @RequestParam(value = "dictName", required = true) String dictName,
                            @ApiParam(name = "type", value = "类型 1具体字典 2分类字典")
                            @RequestParam(value = "type", required = true) String type){
        try {
            String sql = "";
            if("1".equals(type)){
                if("town".equals(dictName)){
                    sql = "SELECT code,name from wlyy.dm_town WHERE city = '350200'";
                }else if ("org".equals(dictName)){
                    sql = "SELECT DISTINCT class_name code,table_name name  from wlyy.copd_followup_dict WHERE dict_name='hospital_community_relation'";
                }else if ("hospital".equals(dictName)){
                    sql = "SELECT DISTINCT code,value name  from wlyy.copd_followup_dict WHERE dict_name='hospital_community_relation' ORDER BY code";
                }else {
                    sql = "SELECT DISTINCT code,`value` name from wlyy.copd_followup_dict WHERE dict_name = '"+dictName+"'";
                }
            }else {
                sql = "SELECT code,`value` name from system_dict WHERE dict_name = '"+dictName+"'";
            }
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            return ListEnvelop.getSuccess("获取成功",list);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("获取失败");
        }
    }
    /**
     * 综合查询档案数据检索 zuul
     * @param resourcesCode
@ -373,6 +428,55 @@ public class ResourceIntegratedController extends EnvelopRestEndpoint {
        return envelop;
    }
    //basic/resourceIntegrated/searchMetadataData
    @ApiOperation("档案数据导出")
    @RequestMapping(value = "exportExcel/archiveDataExport", method = RequestMethod.GET)
    public void archiveDataExport(
            @ApiParam(name = "resourcesCode", value = "资源code")
            @RequestParam(value = "resourcesCode", required = true) String resourcesCode,
            @ApiParam(name = "metaData", value = "数据元")
            @RequestParam(value = "metaData", required = true) String metaData,
            @ApiParam(name = "type", value = "类型 1全部 2当前页(默认全部)", required = false)
            @RequestParam(value = "type", required = false) String type,
            @ApiParam(name = "searchParams", value = "查询条件")
            @RequestParam(value = "searchParams", required = false) String searchParams, HttpServletResponse response) {
        try {
            int size = 99999;
            if("2".equals(type)){
                size = 50;
            }
            Page<Map<String, Object>> result = resourceBrowseService.getCustomizeDataMysql(resourcesCode,metaData,searchParams,1, size);
            List<Map<String, Object>> listMap = result.toList();
            //导出
            String fileName = "档案数据导出";
            response.setContentType("octets/stream");
            response.setCharacterEncoding("utf-8");
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + new String(".xls"));
            OutputStream os = response.getOutputStream();
            WorkbookUtil workbookUtil = new WorkbookUtil();
            //获取表头
            List<String> codeList = (List<String>) objectMapper.readValue(resourcesCode, List.class);
            String resourcesCodes = org.apache.commons.lang.StringUtils.join(codeList,"','");
            List<Map<String,Object>> metadatas = resourceBrowseMetadataDao.getMetadatas(resourcesCodes);
            Map<String,String> metadataMap = metadatas.stream().collect(Collectors.toMap(e->e.get("ehr_id").toString(),e->e.get("name").toString()));
            metaData = metaData.replaceAll(",","\",\"");
            List<String> customizeList = (List<String>) objectMapper.readValue(metaData, List.class);
            Map<Integer, String> columnMap = new HashMap<>();
            String[] header = new  String[customizeList.size()];
            for (int i=0;i<customizeList.size();i++){
                String key = customizeList.get(i);
                columnMap.put(i, key);
                header[i] = metadataMap.get(key);
            }
            workbookUtil.write(Workbook.createWorkbook(os), listMap, columnMap, header);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 综合查询档案数据导出
     * @param request

+ 307 - 1
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/ResourceBrowseDao.java

@ -15,6 +15,7 @@ import com.yihu.jw.mysql.sqlparser.ParserSql;
import com.yihu.jw.profile.core.ResourceCore;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
@ -638,7 +639,8 @@ public class ResourceBrowseDao {
     * @return
     * @throws Exception
     */
    public Page<Map<String, Object>> getMysqlDataAndCondition(String sql,String queryParam,String sortParam,Integer page, Integer size,List<String> resourcesCodes) throws Exception {
    public Page<Map<String, Object>> getMysqlDataAndCondition(String sql,String queryParam,String sortParam,Integer page,
                                                              Integer size,List<String> resourcesCodes,int dataSource) throws Exception {
        String sortOrder = "";
        String sortOrderSql = "";
        if (StringUtils.isNoneBlank(sortParam)){
@ -660,6 +662,9 @@ public class ResourceBrowseDao {
        if (StringUtils.isNoneBlank(queryParam)){
            queryParam =" where 1=1 "+ queryParam;
        }
//        if(dataSource==2){
//            queryParam = "";
//        }
        //判定是否完整sql语句
        sql =sql+queryParam+sortOrderSql;
        //查询总条数
@ -801,6 +806,307 @@ public class ResourceBrowseDao {
        return new PageImpl<>(list, PageRequest.of(page - 1, size), count);
    }
    public String transforParamValue(String paramValue){
        if(StringUtils.isBlank(paramValue)){
            return paramValue;
        }
        paramValue = paramValue.replaceAll("filterAreaCode","");
        paramValue = paramValue.replaceAll("filterCreateTimeF","");
        paramValue = paramValue.replaceAll("filterCreateTimeR","");
        paramValue = paramValue.replaceAll("filterCreateTime","");
        paramValue = paramValue.replaceAll("filterManagedTimeShort","");
        paramValue = paramValue.replaceAll("filterExitTimeShort","");
        paramValue = paramValue.replaceAll("filterLostVisitTimeShort","");
        paramValue = paramValue.replaceAll("filterUnmanagedTimeShort","");
        paramValue = paramValue.replaceAll("filterEntryTimeShort","");
        paramValue = paramValue.replaceAll("filterAssignTimeShort","");
        paramValue = paramValue.replaceAll("filterEndTime","");
        paramValue = paramValue.replaceAll("filterFollowupDate","");
        paramValue = paramValue.replaceAll("filterExamineTime","");
        paramValue = paramValue.replaceAll("filterCheckTime","");
        paramValue = paramValue.replaceAll("filterDateHH","");
        paramValue = paramValue.replaceAll("filterWatchTime","");
        paramValue = paramValue.replaceAll("filterYesterday","");
        return paramValue;
    }
    /**
     * 参数处理
     * copdgroup	管理状态
     * date	时间
     * groupScreeningStatus1	分组
     * hospital	社区医院
     * orgCode	等级医院
     * town	区
     * @param paramValue
     * @param dataMap
     * @return
     */
    public String transforParamValue(String paramValue,Map<String,String> dataMap){
        if(StringUtils.isBlank(paramValue)){
            return paramValue;
        }
        String filterAreaCode = "";
        String filterCreateTime= "";
        String filterCreateTimeF= "";// f.create_time
        String filterCreateTimeR= "";// r.create_time
        String filterFollowupDate= "";// f.followup_date
        String filterExamineTime= "";// a.examine_time
        String filterCheckTime= "";// a.check_time
        String filterDateHH= "";// hh.date
        String filterWatchTime= "";// a.watch_time
        String filterManagedTimeShort= "";//a.managed_time_short `status`='1'
        String filterExitTimeShort= "";//a.exit_time_short `status`='3'
        String filterLostVisitTimeShort= "";//a.lost_visit_time_short `status`='2'
        String filterUnmanagedTimeShort= "";//a.unmanaged_time_short `status`='4'
        String filterEntryTimeShort= "";//a.entry_time_short
        String filterAssignTimeShort= "";//a.assign_time_short
        String filterEndTime= "";//r.end_time
        String filterYesterday= "";// yesterdayWatchNum
        String startDate = dataMap.get("startDate");//结束时间
        String endDate = dataMap.get("endDate");//开始时间
        String filterCommon = "";
        if(StringUtils.isNotBlank(startDate)){
            String startDateShort = startDate.replaceAll("-","");
            String startDate2 = startDate.replace("-", "/");
            filterCreateTime += " and a.create_time>='"+startDate+"' ";
            filterExamineTime += " and a.examine_time>='"+startDate+"' ";
            filterCheckTime += " and a.check_time>='"+startDate+"' ";
            filterCreateTimeF += " and f.create_time>='"+startDate+"' ";
            filterCreateTimeR += " and r.create_time>='"+startDate+"' ";
            filterFollowupDate += " and f.followup_date>='"+startDate+"' ";
            filterWatchTime += " and a.watch_time>='"+startDate+"' ";
            filterDateHH += " and hh.date>='"+startDate+"' ";
            filterManagedTimeShort += " and a.managed_time_short>='"+startDateShort+"' ";
            filterExitTimeShort += " and a.exit_time_short>='"+startDateShort+"' ";
            filterLostVisitTimeShort += " and a.lost_visit_time_short>='"+startDateShort+"' ";
            filterUnmanagedTimeShort += " and a.unmanaged_time_short>='"+startDateShort+"' ";
            filterEntryTimeShort += " and a.entry_time_short>='"+startDateShort+"' ";
            filterAssignTimeShort += " and a.assign_time_short>='"+startDateShort+"' ";
            filterEndTime += " and r.end_time>='"+startDate2+"' ";
        }
        if(StringUtils.isNotBlank(endDate)){
            String endDateShort = endDate.replaceAll("-","");
            String endDate2 = endDate.replace("-", "/");
            filterCreateTime += " and a.create_time<='"+endDate+" 23:59:59' ";
            filterExamineTime += " and a.examine_time<='"+endDate+" 23:59:59' ";
            filterCheckTime += " and a.check_time<='"+endDate+" 23:59:59' ";
            filterCreateTimeF += " and f.create_time<='"+endDate+" 23:59:59' ";
            filterCreateTimeR += " and r.create_time<='"+endDate+" 23:59:59' ";
            filterFollowupDate += " and f.followup_date<='"+endDate+" 23:59:59' ";
            filterWatchTime += " and a.watch_time<='"+endDate+" 23:59:59' ";
            filterDateHH += " and hh.date<='"+endDate+" 23:59:59' ";
            filterManagedTimeShort += " and a.managed_time_short<='"+endDateShort+"' ";
            filterExitTimeShort += " and a.exit_time_short<='"+endDateShort+"' ";
            filterLostVisitTimeShort += " and a.lost_visit_time_short<='"+endDateShort+"' ";
            filterUnmanagedTimeShort += " and a.unmanaged_time_short<='"+endDateShort+"' ";
            filterEntryTimeShort += " and a.entry_time_short<='"+endDateShort+"' ";
            filterAssignTimeShort += " and a.assign_time_short<='"+endDateShort+"' ";
            filterEndTime += " and r.end_time<='"+endDate2+"' ";
            filterYesterday = DateUtil.getNextDay(endDate,-1);
        }else {
            filterYesterday = DateUtil.getNextDay(new Date(),-1);
        }
        for (Map.Entry<String,String> entry : dataMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if("copdgroup".equals(key)){
                //管理状态
                filterCommon += " and a.status='"+value+"' ";
            }
            if("groupScreeningStatus1".equals(key)){
                //分组
                filterCommon += " and a.group_screening_status='"+value+"' ";
            }
            if("town".equals(key)){
                //区
                filterAreaCode += " and h.town = '"+value+"' ";
            }
            if("orgCode".equals(key)){
                //等级医院
                filterAreaCode += " and d.class_name = '"+value+"' ";
            }
            if("hospital".equals(key)){
                //社区医院
                filterAreaCode += " and h.code = '"+value+"' ";
            }
        }
        filterCreateTime += filterCommon;
        paramValue = paramValue.replaceAll("filterAreaCode",filterAreaCode);
        paramValue = paramValue.replaceAll("filterCreateTimeF",filterCreateTimeF);
        paramValue = paramValue.replaceAll("filterCreateTimeR",filterCreateTimeR);
        paramValue = paramValue.replaceAll("filterCreateTime",filterCreateTime);
        paramValue = paramValue.replaceAll("filterManagedTimeShort",filterManagedTimeShort);
        paramValue = paramValue.replaceAll("filterExitTimeShort",filterExitTimeShort);
        paramValue = paramValue.replaceAll("filterLostVisitTimeShort",filterLostVisitTimeShort);
        paramValue = paramValue.replaceAll("filterUnmanagedTimeShort",filterUnmanagedTimeShort);
        paramValue = paramValue.replaceAll("filterEntryTimeShort",filterEntryTimeShort);
        paramValue = paramValue.replaceAll("filterAssignTimeShort",filterAssignTimeShort);
        paramValue = paramValue.replaceAll("filterEndTime",filterEndTime);
        paramValue = paramValue.replaceAll("filterFollowupDate",filterFollowupDate);
        paramValue = paramValue.replaceAll("filterExamineTime",filterExamineTime);
        paramValue = paramValue.replaceAll("filterCheckTime",filterCheckTime);
        paramValue = paramValue.replaceAll("filterDateHH",filterDateHH);
        paramValue = paramValue.replaceAll("filterWatchTime",filterWatchTime);
        paramValue = paramValue.replaceAll("filterYesterday",filterYesterday);
        return paramValue;
    }
    //参数处理
    public String transforParam(String paramSql,String tableSql,Map<String,String> dataMap){
        if(StringUtils.isBlank(paramSql)){
            return tableSql;
        }
        String params[] = paramSql.split(",");
        for (int i=0;i<params.length;i++){
            String param = params[i];
            String key = "";
            String str[] = param.split("-");
            if(str.length>1){
                key = str[1];
            }else {
                key = str[0];
            }
            tableSql = tableSql.replaceAll(param,getDefaultValue(key,dataMap));
        }
        return tableSql;
    }
    //获取默认值
    public String getDefaultValue(String key,Map<String,String> dataMap){
        if(StringUtils.isBlank(key)){
            return "";
        }
        String defaultStartDate = "2023-06-26";
        String defaultStartDateTime = "2023-06-26 00:00:00";
        String defaultEndDate = DateUtil.getStringDateShort();
        String defaultEndDateTime = DateUtil.getStringDate();
        String result = "";
        switch (key){
            case "dateTimeStart":
                result = defaultStartDateTime;
                break;
            case "dateTimeEnd":
                result = defaultEndDate +" 23:59:59";
                break;
            case "dateTimeStartShort":
                result = defaultStartDateTime.replaceAll("-","");
                break;
            case "dateTimeEndShort":
                result = defaultEndDateTime.replaceAll("-","");
                break;
            case "dateStart":
                result = defaultStartDate;
                break;
            case "dateEnd":
                result = defaultEndDate;
                break;
            case "dateStartShort":
                result = defaultStartDate.replaceAll("-","");
                break;
            case "dateEndShort":
                result = defaultEndDate.replaceAll("-","");
                break;
            case "year_months":
                result = defaultEndDate.substring(0,7);
                break;
            default:
                break;
        }
        return result;
    }
    /**
     * 获取Mysql配置库 指标统计数据
     * getMysqlStatistics
     * @param resourcesCode
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    public Page<Map<String, Object>> getMysqlStatistics(String resourcesCode, Integer page, Integer size) throws Exception {
        String sql ="";
        String sortOrder = "";
        String sortOrderSql = "";
        String tableSql = "";
        String paramSql = "";//入参
        //通过资源代码获取默认参数
        List<RsResourceDefaultParam> paramsList = resourceDefaultParamDao.findByResourcesCode(resourcesCode);
        for (RsResourceDefaultParam param : paramsList) {
            if (param.getParamKey().equals("sort")) {
                Map<String, String> temp = objectMapper.readValue(param.getParamValue(), Map.class);
                for (Map.Entry<String, String> entry:temp.entrySet()){
                    String key = entry.getKey();
                    String value = entry.getValue();
                    sortOrder ="T."+key+" "+ value+",";
                }
            }else if (param.getParamKey().equals("table")){
                tableSql = "("+param.getParamValue()+") T ";
            }else if (param.getParamKey().equals("param")){
                paramSql = param.getParamValue();
            }
        }
        if (StringUtils.isNoneBlank(sortOrder)){
            sortOrderSql +=" order by "+sortOrder.substring(0,sortOrder.length()-1);
        }
        tableSql = transforParamValue(tableSql);
        tableSql = transforParam(paramSql,tableSql,null);
        //判定是否完整sql语句
        sql = "select T.* from " + tableSql +sortOrderSql;
        //查询总条数
        ParserSql parser = ParserFactory.getParserSql();
        String sqlCount = parser.getCountSql(sql);
        long count = jdbcTemplate.queryForObject(sqlCount, Long.class);
        //默认第一页
        if (page == null) {
            page = defaultPage;
        }
        //默认行数
        if (size == null) {
            size = defaultSize;
        }
        //分页查询
        List<Map<String, Object>> list;
        if (count > size) {
            String sqlList = parser.getPageSql(sql, page, size);
            list = jdbcTemplate.queryForList(sqlList);
        } else {
            list = jdbcTemplate.queryForList(sql);
        }
        if(list.size()>0){
            //字典翻译
            List<DtoResourceMetadata> resourceMetadataList = resourceBrowseMetadataDao.getResourceMetadataHasDict(resourcesCode);
            if(resourceMetadataList.size()>0){
                Map<String,String> fieldDictMap = resourceMetadataList.stream().collect(Collectors.toMap(DtoResourceMetadata::getStdCode,DtoResourceMetadata::getDictCode));
                Map<String,Map<String,String>> dictMap = new HashMap<>();
                String dictSql = "select * from rs_dictionary_entry where DICT_CODE = ?";
                for (DtoResourceMetadata metadata:resourceMetadataList){
                    String dictCode = metadata.getDictCode();
                    if(!dictMap.containsKey(dictCode)){
                        List<RsDictionaryEntry> dictionaryEntries = jdbcTemplate.query(dictSql,new Object[]{dictCode},new BeanPropertyRowMapper<>(RsDictionaryEntry.class));
                        Map<String,String> tmpMap = dictionaryEntries.stream().collect(Collectors.toMap(RsDictionaryEntry::getCode,RsDictionaryEntry::getName));
                        dictMap.put(dictCode,tmpMap);
                    }
                }
                for (Map<String, Object> map:list){
                    for (Map.Entry<String, String> entry : fieldDictMap.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        if(map.get(key)!=null){
                            String dictValue =  dictMap.get(value).get(map.get(key));
                            map.put(key,dictValue);
                        }
                    }
                }
            }
        }
        return new PageImpl<>(list, PageRequest.of(page - 1, size), count);
    }
    /**
     * 获取Mysql配置库数据

+ 25 - 1
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/dao/ResourceBrowseMetadataDao.java

@ -31,6 +31,18 @@ public class ResourceBrowseMetadataDao {
        return jdbcTemplate.query(sql, rowMapper);
    }
    /**
     * 获取某资源所有数据元
     */
    public List<Map<String,Object>> getAllMetadata(String resourcesCode) throws Exception {
        String sql = "SELECT m.EHR_ID,m.name,m.DICT_CODE ,d.name dictName,m.COLUMN_TYPE columnType  " +
                "FROM rs_resource_metadata a, rs_resource b, rs_metadata m LEFT JOIN rs_dictionary d on m.dict_code=d.code " +
                "WHERE a.resources_id = b.id " +
                "AND a.metadata_id = m.ehr_id " +
                "AND b.code = '" + resourcesCode + "'";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 获取某资源所有数据元
     */
@ -39,7 +51,7 @@ public class ResourceBrowseMetadataDao {
                "FROM rs_resource_metadata a, rs_resource b, rs_metadata m " +
                "WHERE a.resources_id = b.id " +
                "AND a.metadata_id = m.ehr_id " +
                "AND b.code = '" + resourcesCode + "'";
                "AND b.code = '" + resourcesCode + "' ORDER BY a.sort";
        RowMapper rowMapper = BeanPropertyRowMapper.newInstance(DtoResourceMetadata.class);
        return jdbcTemplate.query(sql, rowMapper);
    }
@ -57,6 +69,18 @@ public class ResourceBrowseMetadataDao {
        return jdbcTemplate.query(sql, rowMapper);
    }
    /**
     * 获取某资源
     */
    public List<Map<String,Object>> getMetadatas(String resourcesCodes) throws Exception {
        String sql = "SELECT m.ehr_id, m.name " +
                "      FROM rs_resource_metadata a, rs_resource b, rs_metadata m " +
                "      WHERE a.resources_id = b.id " +
                "      AND a.metadata_id = m.ehr_id " +
                "AND b.code in ('" + resourcesCodes + "')  ";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 获取某资源有字典的数据元
     */

+ 58 - 2
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/ResourceBrowseService.java

@ -327,11 +327,16 @@ public class ResourceBrowseService extends BaseJpaService {
            }
            String method = rsResources.getRsInterface();
            Class clazz = resourceBrowseDao.getClass();
            if(method.equalsIgnoreCase("getMysqlData")){
                Method _method = clazz.getMethod(method, new Class[]{ String.class, Integer.class, Integer.class});
                _method.setAccessible(true);
                return _method.invoke(resourceBrowseDao, rsResources.getCode(), page, size);
            }{
            }else if(method.equalsIgnoreCase("getMysqlStatistics")){
                Method _method = clazz.getMethod(method, new Class[]{ String.class, Integer.class, Integer.class});
                _method.setAccessible(true);
                return _method.invoke(resourceBrowseDao, rsResources.getCode(), page, size);
            }else {
                Method _method = clazz.getMethod(method, new Class[]{String.class, String.class, String.class, String.class, Integer.class, Integer.class});
                _method.setAccessible(true);
                return _method.invoke(resourceBrowseDao, resourcesCode, roleId, saas.toString(), queryParams, page, size);
@ -500,15 +505,27 @@ public class ResourceBrowseService extends BaseJpaService {
        //获取资源编码列表
        List<String> codeList = (List<String>) objectMapper.readValue(resourcesCodes, List.class);
        String tableName = "";
        String paramSql = "";
        String where = "";
        Map<String,Integer> relationMap = new HashMap<>();//多视图关联
        Map<String,String> filedMap = new HashMap<>();//参数加别名
        Map<String,String> dataMap = new HashMap<>();
        if (!StringUtils.isEmpty(queryCondition)) {
            dataMap = parseConditionMap(queryCondition);
        }
        int dataSource = 0;
        //资源判空检查
        for (String code : codeList) {
            RsResource rsResources = rsResourceService.getResourceByCategory(code,"standard");
            if (rsResources == null) {
                throw new ApiException( "无效的资源编码" + code,ErrorCode.BAD_REQUEST.value());
            }
            if(dataSource==0){
                dataSource = rsResources.getDataSource();
            }
            if(rsResources.getDataSource()==2&&codeList.size()>1){
                throw new ApiException("指标统计,只能选择单个指标");
            }
            List<RsResourceMetadata> resourceMetadataList = resourceBrowseMetadataDao.findResourceMetadata(code);
            for (RsResourceMetadata metadata:resourceMetadataList){
                filedMap.put(metadata.getMetadataId(),code);
@ -526,6 +543,7 @@ public class ResourceBrowseService extends BaseJpaService {
                        sortOrder ="T."+key+" "+ value+",";
                    }
                }else if ("table".equals(paramKey)){
                    paramValue = resourceBrowseDao.transforParamValue(paramValue,dataMap);
                    tableName += " ("+paramValue+") "+ code +",";
                }else if("relation".equals(paramKey)){
                    String relate[] = paramValue.split(",");
@ -536,6 +554,8 @@ public class ResourceBrowseService extends BaseJpaService {
                            relationMap.put(re,1);
                        }
                    }
                }else if (param.getParamKey().equals("param")){
                    paramSql = param.getParamValue();
                }
            }
        }
@ -553,6 +573,10 @@ public class ResourceBrowseService extends BaseJpaService {
        }
        tableName = tableName.substring(0,tableName.length()-1);
        if(!StringUtils.isEmpty(paramSql)){
            tableName = resourceBrowseDao.transforParam(paramSql,tableName,dataMap);
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (!StringUtils.isEmpty(queryCondition)) {
            stringBuffer = parseCondition1(queryCondition);
@ -565,7 +589,12 @@ public class ResourceBrowseService extends BaseJpaService {
        List<String> customizeList = (List<String>) objectMapper.readValue(metaData, List.class);
        //参数集合
        List<String> paramList = new ArrayList<>(customizeList.size() * 2);
        Map<String,Integer> fieldMap = new HashMap<>();//去除重复的列
        for (String id : customizeList) {
            if(fieldMap.containsKey(id)){
                continue;
            }
            fieldMap.put(id,1);
            String codeTmp = filedMap.get(id);
            if(id.contains("-")){
                String tmp = id.substring(id.lastIndexOf("-")+1);
@ -579,7 +608,7 @@ public class ResourceBrowseService extends BaseJpaService {
        String queryString = org.apache.commons.lang3.StringUtils.join(paramList, ",");
        String sql = " select "+queryString+" from "+tableName;
        String sortParam = "";
        return resourceBrowseDao.getMysqlDataAndCondition(sql, stringBuffer.toString(),sortParam, page, size,codeList);
        return resourceBrowseDao.getMysqlDataAndCondition(sql, stringBuffer.toString(),sortParam, page, size,codeList,dataSource);
    }
    /**
@ -735,6 +764,33 @@ public class ResourceBrowseService extends BaseJpaService {
        return stringBuffer;
    }
    /**
     * 查询条件转换
     *
     * @param queryCondition
     * @return
     * @throws Exception
     */
    private Map<String,String> parseConditionMap(String queryCondition) throws Exception {
        Map<String,String> map = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Map.class);
        List<Map<String, Object>> list = objectMapper.readValue(queryCondition, javaType);
        if (list != null && list.size() > 0) {
            for (Map<String, Object> item : list) {
                String andOr = String.valueOf(item.get("andOr")).trim();
                String field = String.valueOf(item.get("field")).trim();
                if(field.contains("-")){
                    field = field.substring(field.lastIndexOf("-")+1);
                }
                String cond = String.valueOf(item.get("condition")).trim();
                String value = String.valueOf(item.get("value"));
                map.put(field,value);
            }
        }
        return map;
    }
    /**
     * 新增参数
     *

+ 56 - 8
svr/svr-basic/src/main/java/com/yihu/jw/basic/resource/service/ResourceIntegratedService.java

@ -82,21 +82,24 @@ public class ResourceIntegratedService extends BaseJpaService {
     * @return
     */
    @Transactional(readOnly = true)
    public List<RsResource> findFileMasterList(String categoryId, String ids, String filters, String categoryCode) {
    public List<RsResource> findFileMasterList(String categoryId, String ids, String filters, String categoryCode,String rs_interface) {
        if(rs_interface==null){
            rs_interface = "getMysqlData";
        }
        String sql;
        if (filters != null) {
            if (ids != null) {
                sql = "SELECT rr.id, rr.code, rr.name, rr.category_id, rr.rs_interface, rr.grant_type FROM rs_resource rr ,rs_resource_category rrc  WHERE" +
                        " rr.category_id=rrc.ID AND rrc. CODE = '" + categoryCode + "' " +
                        "AND rr.category_id = '" + categoryId + "' " +
                        "AND rr.rs_interface = 'getMysqlData' " +
                        "AND rr.rs_interface = '"+rs_interface+"' " +
                        "AND (rr.id IN (" + ids + ")) " + "OR rr.grant_type = '0') " +
                        "AND rr.name like " + "'%" + filters + "%'";
            } else {
                sql = "SELECT rr.id, rr.code, rr.name, rr.category_id, rr.rs_interface, rr.grant_type FROM rs_resource rr ,rs_resource_category rrc   WHERE" +
                        " rr.category_id=rrc.ID AND rrc. CODE = '" + categoryCode + "' " +
                        "AND rr.category_id = '" + categoryId + "'" +
                        "AND rr.rs_interface = 'getMysqlData' " +
                        "AND rr.rs_interface = '"+rs_interface+"' " +
                        "AND rr.name like " + "'%" + filters + "%'";
            }
        } else {
@ -104,13 +107,13 @@ public class ResourceIntegratedService extends BaseJpaService {
                sql = "SELECT rr.id, rr.code, rr.name, rr.category_id, rr.rs_interface, rr.grant_type FROM rs_resource rr ,rs_resource_category rrc   WHERE" +
                        " rr.category_id=rrc.ID AND rrc. CODE = '" + categoryCode + "' " +
                        "AND rr.category_id = '" + categoryId + "'" +
                        "AND rr.rs_interface = 'getMysqlData' " +
                        "AND rr.rs_interface = '"+rs_interface+"' " +
                        "AND rr.id IN (" + ids + ")) " + "OR rr.grant_type = '0') ";
            } else {
                sql = "SELECT rr.id, rr.code, rr.name, rr.category_id, rr.rs_interface, rr.grant_type FROM rs_resource rr ,rs_resource_category rrc   WHERE" +
                        " rr.category_id=rrc.ID AND rrc. CODE = '" + categoryCode + "' " +
                        "AND rr.category_id = '" + categoryId + "'" +
                        "AND rr.rs_interface = 'getMysqlData'";
                        "AND rr.rs_interface = '"+rs_interface+"' ";
            }
        }
        RowMapper rowMapper = BeanPropertyRowMapper.newInstance(RsResource.class);
@ -376,6 +379,51 @@ public class ResourceIntegratedService extends BaseJpaService {
        return cateMapList;
    }
    /**
     * 综合查询档案数据列表树(新)
     *
     * @param filters
     * @return
     */
    @Transactional(readOnly = true)
    public List<Map<String, Object>> metadata(String categoryId, String filters,String dataSource) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String rs_interface = "getMysqlData";
        if("2".equals(dataSource)){
            rs_interface = "getMysqlStatistics";
        }
        List<RsResource> rrList = findFileMasterList(categoryId, null, filters, "standard",rs_interface);
        if (rrList != null) {
            for (RsResource rsResources : rrList) {
                Map<String, Object> masterMap = new HashMap<String, Object>();
                masterMap.put("level", "2");
                masterMap.put("code", rsResources.getCode());
                masterMap.put("name", rsResources.getName());
                masterMap.put("id", rsResources.getId());
                List<Map<String,Object>> rmList = resourceBrowseMetadataDao.getAllMetadata(rsResources.getCode());
                if (rmList != null) {
                    List<Map<String, Object>> metadataList = new ArrayList<Map<String, Object>>();
                    for (Map<String,Object> rsMetadata : rmList) {
                        Map<String, Object> metadataMap = new HashMap<String, Object>();
                        metadataMap.put("level", "3");
                        metadataMap.put("code", rsMetadata.get("EHR_ID"));
                        metadataMap.put("name", rsMetadata.get("name"));
                        metadataMap.put("columnType", rsMetadata.get("columnType"));
                        metadataMap.put("id", UUID.randomUUID().toString());
                        metadataMap.put("dictCode", rsMetadata.get("DICT_CODE"));
                        metadataMap.put("dictName", rsMetadata.get("dictName"));
                        metadataList.add(metadataMap);
                    }
                    masterMap.put("children", metadataList);
                }
                resultList.add(masterMap);
            }
        }
        return resultList;
    }
    /**
     * 综合查询档案数据列表树
     *
@ -387,7 +435,7 @@ public class ResourceIntegratedService extends BaseJpaService {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<RsResource> rrList;
        if (userResource.equals("*")) {
            rrList = findFileMasterList(categoryId, null, filters, categoryCode);
            rrList = findFileMasterList(categoryId, null, filters, categoryCode,null);
        } else {
            //授权资源
            List<String> userResourceList = objectMapper.readValue(userResource, List.class);
@ -399,9 +447,9 @@ public class ResourceIntegratedService extends BaseJpaService {
            }
            String ids = builder.toString();
            if (StringUtils.isEmpty(ids)) {
                rrList = findFileMasterList(categoryId, "''", filters, categoryCode);
                rrList = findFileMasterList(categoryId, "''", filters, categoryCode,null);
            } else {
                rrList = findFileMasterList(categoryId, ids.substring(0, ids.length() - 1), filters, categoryCode);
                rrList = findFileMasterList(categoryId, ids.substring(0, ids.length() - 1), filters, categoryCode,null);
            }
        }
        if (rrList != null) {

+ 64 - 0
svr/svr-basic/src/main/java/com/yihu/jw/basic/util/WorkbookUtil.java

@ -0,0 +1,64 @@
package com.yihu.jw.basic.util;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
 * Created by janseny on 2018/11/28.
 */
public class WorkbookUtil {
    /**
     * excel 文件导出
     * @param wwb
     * @param listMap 数据
     * @param columnMap 每列对应的数据集中的key
     * @param header  表头
     * @throws Exception
     */
    public void write(WritableWorkbook wwb, List<Map<String,Object>> listMap,Map<Integer,String> columnMap,String [] header) throws Exception {
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet",1);
            addHeader(ws,header);
            int i = 1;
            for (Map<String,Object> map : listMap ) {
                for(int key :columnMap.keySet()){
                    String cloumn = columnMap.get(key);
                    if(map.get(cloumn) != null){
                        addCell(ws, i, key, map.get(cloumn).toString());
                    }
                }
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) {
                wwb.close();
            }
            throw e;
        }
    }
    public void addHeader(WritableSheet ws,String[] header) throws WriteException {
        int i = 0;
        for (String h : header) {
            addCell(ws, 0, i, h);//表名,行,列,header
            i++;
        }
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column,  String data) throws WriteException {
        Label label = new Label(column ,row, data);
        ws.addCell(label);
    }
}

+ 22 - 21
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/consult/DoctorConsultController.java

@ -3,33 +3,22 @@ package com.yihu.rehabilitation.controller.consult;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.dao.SignFamilyDao;
import com.yihu.rehabilitation.service.consult.ConsultTeamService;
import com.yihu.rehabilitation.service.followUp.FollowUpService;
import com.yihu.rehabilitation.util.BusinessLogs;
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.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -48,25 +37,28 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
    private ConsultTeamService consultTeamService;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private SystemMessageService messageService;
    @Autowired
    protected HttpServletRequest request;
    @RequestMapping(value = "getKangFuConsultList",method = RequestMethod.GET)
    @RequestMapping(value = "getKangFuConsultList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取续方咨询列表")
    public Envelop getKangFuConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
                                        @ApiParam(name = "patient", value = "居民CODE") @RequestParam(required = false) String patient,
                                        @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) Integer id,
                                        @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize){
                                        @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
        try {
            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType("a663d0cf7f8c4d38a8327cedc921e65f", id, pagesize,8, title);//8表示续方咨询
            List<Map<String,Object>> data = consultTeamService.findConsultRecordByType(patient, id, pagesize,18, title);//18表示康复咨询
            BasePatientDO patientobj = basePatientDao.findById(patient);
            List<Map<String, Object>> data = consultTeamService.findConsultRecordByType(patient, id, pagesize, 18, title);//18表示康复咨询
            BasePatientDO patientobj = basePatientDao.findById(patient).orElse(null);
            if (data != null) {
                for (Map<String,Object> consult : data) {
                for (Map<String, Object> consult : data) {
                    if (consult == null) {
                        continue;
                    }
@ -87,12 +79,12 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
                    // 设置咨询日期
                    json.put("czrq", DateUtil.dateToStrLong((Date) consult.get("czrq")));
                    // 咨询状态
                    json.put("doctorCode",consult.get("doctor"));
                    json.put("doctorCode", consult.get("doctor"));
                    json.put("evaluate", consult.get("evaluate"));
                    array.put(json);
                }
            }
            return success( "查询成功!",  array);
            return success("查询成功!", array);
        } catch (Exception e) {
            e.printStackTrace();
            return failedException(e);
@ -105,9 +97,9 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
        try {
            ConsultTeamDo ct = consultTeamService.findByCode(consult);
            if (ct == null) {
                return failed( "获取状态失败!");
                return failed("获取状态失败!");
            } else {
                return success( "获取状态成功!",  ct.getEvaluate());
                return success("获取状态成功!", ct.getEvaluate());
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -115,6 +107,15 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
        }
    }
    @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();
        }
    }
}

+ 57 - 12
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java

@ -1,12 +1,16 @@
package com.yihu.rehabilitation.controller.message;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.rehabilitation.service.message.RehabilitationMessageService;
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.stereotype.Controller;
@ -15,12 +19,18 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping(value = "/doctor/message",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = {RequestMethod.GET,RequestMethod.POST})
@RequestMapping(value = "/doctor/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = {RequestMethod.GET, RequestMethod.POST})
@Api(description = "医生端-消息")
public class DoctorMessageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationMessageService messageService;
    private RehabilitationMessageService rehabilitationMessageService;
    @Autowired
    private SystemMessageService messageService;
    /**
     * 设置待办消息已处理
@ -29,20 +39,55 @@ public class DoctorMessageController extends EnvelopRestEndpoint {
     * @param type
     * @return
     */
    @RequestMapping(value = "setSpecialistOver",method = RequestMethod.POST)
    @RequestMapping(value = "setSpecialistOver", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("设置待办消息已处理" )
    public Envelop setSpecialistOver(@ApiParam(name = "id",value = "消息id")
                                    @RequestParam(value = "id")String  id,
                                     @ApiParam(name = "type",value = "消息类型")
                                    @RequestParam(value = "type")Integer type) {
    @ApiOperation("设置待办消息已处理")
    public Envelop setSpecialistOver(@ApiParam(name = "id", value = "消息id")
                                     @RequestParam(value = "id") String id,
                                     @ApiParam(name = "type", value = "消息类型")
                                     @RequestParam(value = "type") Integer type) {
        try {
            return success( "获取消息总数成功!",  messageService.setSpecialistOver(id,type));
            return success("获取消息总数成功!", rehabilitationMessageService.setSpecialistOver(id, type));
        } catch (Exception e) {
          e.printStackTrace();
            return failed( e.getMessage());
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value = "getWaitingMessages", method = RequestMethod.GET)
    @ApiOperation("获取服务工单待接单列表")
    @ResponseBody
    public String getWaitingMessages(
            @ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
            @ApiParam(name = "types", value = "消息类型") @RequestParam(value = "types", required = true) String types,
            @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
            @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize
    ) {
        if (StringUtils.isBlank(pageSize)) {
            pageSize = "10";
        }
        if (page.equals("0")) {
            page = "1";
        }
        String[] split = StringUtils.split(types, ",");
        List<Integer> typeList = new ArrayList<>();
        for (String s : split) {
            typeList.add(Integer.valueOf(s));
        }
        SystemMessageDO message1 = new SystemMessageDO();
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
        message1.setOver(object.getString("over"));
        message1.setIsRead(object.getInteger("read").toString());
        message1.setReceiver(getUID());
        try {
            JSONObject waitingMessages = messageService.getWaitingMessages(message1, types, Integer.valueOf(page), Integer.valueOf(pageSize));
            return write(200, "查询成功", "data", waitingMessages);
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

+ 1 - 1
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/consult/ConsultTeamService.java

@ -288,7 +288,7 @@ public class ConsultTeamService extends ConsultService {
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), "咨询问题:"+consult.getSymptoms(), consult.getImages());
        com.alibaba.fastjson.JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), agent);
        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
        com.alibaba.fastjson.JSONObject obj = ImUtill.createTopics(patient + "_" + ct.getDoctor() + "_" +specialDoctorCode+"_"+ ct.getType(), consult.getId(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
        com.alibaba.fastjson.JSONObject obj = ImUtill.createTopics(patient + "_" + ct.getDoctor() + "_" +specialDoctorCode+"_"+ ct.getType(), consult.getId(), tempPatient.getName(), users, messages, ImUtil.SESSION_TYPE_KANGFU);
        //specialDoctorCode
        if (obj == null) {
            throw new RuntimeException("IM消息发送异常!");

+ 46 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/common/CommonItemController.java

@ -0,0 +1,46 @@
package com.yihu.jw.hospital.module.common;
import com.yihu.jw.hospital.module.door.service.DoorOrderService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by yeshijie on 2023/11/3.
 */
@RestController
@RequestMapping(value = "/common/item", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "通用项目接口")
public class CommonItemController extends EnvelopRestEndpoint {
    @Autowired
    private DoorOrderService doorOrderService;
    @ApiOperation("查询字典-通用字典接口")
    @GetMapping(value= "getServiceItem")
    public Envelop getServiceItem(@ApiParam(name = "name", value = "name", required = false)
                               @RequestParam(value = "name", required = false)String name,
                                  @ApiParam(name = "signId", value = "signId", required = true)
                               @RequestParam(value = "signId", required = true)String signId,
                                  @ApiParam(name = "type", value = "type", required = true)
                               @RequestParam(value = "type", required = true)String type,
                                  @ApiParam(name = "page", value = "page", required = true)
                               @RequestParam(value = "page", required = true) Integer page,
                                  @ApiParam(name = "size", value = "pageSize", required = true)
                               @RequestParam(value = "size", required = true)Integer size){
        try {
            return doorOrderService.getServiceItem(signId,name,type,page,size);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询是吧",-1);
        }
    }
}

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

@ -0,0 +1,1998 @@
package com.yihu.jw.hospital.module.consult.controller;
import com.alibaba.fastjson.JSON;
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.entity.util.SystemConfEntity;
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.hospital.utils.HttpUtil;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
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.im.util.ImageCompress;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
 * 患者端:三师咨询控制类
 *
 * @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
    protected HttpServletRequest request;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private BaseDoctorInfoService doctorService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private com.yihu.jw.util.common.CommonUtil CommonUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private MessageService messageService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Value("${im.data_base_name}")
    private String im;
//    //    @Value("${doctorAssistant.api}")
//    private String doctorAssistant;
//
//    //    @Value("${doctorAssistant.target_url}")
//    private String targetUrl;
//    @Value("${spring.profiles}")
//    private String springProfile;
//    @Autowired
//    private RedisTemplate redisTemplate;
//    @Autowired
//    private PushMsgTask pushMsgTask;
//    @Autowired
//    private PrescriptionDao prescriptionDao;
//    @Autowired
//    private DoctorCommentService doctorCommentService;
//    @Autowired
//    private DoctorStatisticsService doctorStatisticsService;
//    @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) {
                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()).orElse(null);
            int i = 0;
            List<String> failed = new ArrayList<>();
            //这边还要看能不能获取到
            System.out.println("getUID():" + getUID());
            System.out.println("getRepUID():" + getRepUID());
            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).orElse(null);
//                                String doctorOpenID = doctor.getOpenid();
//                                if (StringUtils.isNotEmpty(doctorOpenID)) {
//                                    String title = "";
//                                    ConsultDo consultSingle = consultDao.findById(log.getConsult()).orElse(null);
//                                    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 String loginUser,
            @RequestParam int page, @RequestParam int pagesize) {
        try {
            System.out.println("查询聊天日志");
            System.out.println("参数==>consult:" + consult + "  loginUser:" + loginUser);
            ConsultTeamDo consultModel = consultTeamService.findByCode(consult);
            System.out.println("ConsultTeamDo==>" + JSON.toJSONString(consultModel));
            if (consultModel == null) {
                return error(-1, "咨询记录不存在!");
            }
            System.out.println("调用im查询");
            com.alibaba.fastjson.JSONObject messageObj = imUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, loginUser);
            System.out.println("查询完成");
            //过滤续签
//            consultTeamService.removeRenewPerson(messageObj, getRepUID());
            return write(200, "查询成功", "list", messageObj);
        } catch (Exception e) {
            error(e);
            return "查询失败!";
        }
    }
    /**
     * 网络咨询咨询日志查询
     *
     * @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, "查询失败!");
//        }
//    }
    /**
     * 三师咨询评论
     * consult 咨询标识
     * content 评价内容
     * star    星级
     * 操作结果
     */
//    @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 Envelop getTopic(String consult) {
        try {
            return success(imUtill.getTopic(consult).get("data").toString());
        } catch (Exception e) {
            return failed(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 {
            ConsultTeamDo 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();
        }
    }
    /**
     * 获取微信服务器图片
     *
     * @return
     */
    public String fetchWxImages() {
        String photos = "";
        try {
            String images = request.getParameter("mediaIds");
            if (StringUtils.isEmpty(images)) {
                return photos;
            }
            String[] mediaIds = images.split(",");
            for (String mediaId : mediaIds) {
                if (StringUtils.isEmpty(mediaId)) {
                    continue;
                }
                String temp = saveImageToDisk(mediaId);
                if (StringUtils.isNotEmpty(temp)) {
                    if (photos.length() == 0) {
                        photos = temp;
                    } else {
                        photos += "," + temp;
                    }
                }
            }
        } catch (Exception e) {
            error(e);
        }
        return photos;
    }
    /**
     * 获取下载图片信息(jpg)
     *
     * @param mediaId 文件的id
     * @throws Exception
     */
    public String saveImageToDisk(String mediaId) throws Exception {
        // 文件保存的临时路径
        String tempPath = SystemConfEntity.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        // 重命名文件
        String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
        // 保存路径
        File uploadFile = new File(tempPath + datePath + newFileName);
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            inputStream = getInputStream(mediaId);
            byte[] data = new byte[1024];
            int len = 0;
            fileOutputStream = new FileOutputStream(uploadFile);
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
            // 生成缩略图
            ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
            // 返回保存路径
            return datePath + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 下载多媒体文件(请注意,视频文件不支持下载,调用该接口需http协议)
     *
     * @return
     */
    public InputStream getInputStream(String mediaId) {
        String accessToken = getAccessToken();
        InputStream is = null;
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            // 获取文件转化为byte流
            is = http.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }
    /**
     * 获取微信的access_token
     *
     * @return
     */
    public String getAccessToken() {
        return weiXinAccessTokenUtils.getAccessToken();
    }
}

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

@ -0,0 +1,1667 @@
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.im.ConsultTeamDo;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.DoctorAssistantUtil;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.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;
/**
 * 医生端:三师咨询控制类
 *
 * @author George
 */
@RestController
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "三师咨询")
public class DoctorConsultController extends EnvelopRestEndpoint {
//    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
//    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private BasePatientService patientService;
    @Autowired
    private BaseDoctorInfoService doctorInfoService;
    @Autowired
    private com.yihu.jw.util.common.CommonUtil CommonUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private SystemMessageService messageService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAssistantUtil doctorAssistantUtil;
    //    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private HospitalInviteSpecialistDao inviteSpecialistDao;
//    @Autowired
//    private PrescriptionDiagnosisService prescriptionDiagnosisService;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private HttpClientUtil httpClientUtil;
    @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) {
            return e.getMessage();
        }
    }
    @ApiOperation("咨询是否结束")
    @RequestMapping(value = "/getConsultStatus", method = RequestMethod.GET)
    public String getConsultStatus(@RequestParam(required = true) String consult) {
        try {
            ConsultTeamDo consultTeam = consultTeamService.findByConsultCode(consult);
            return write(200, "查询成功", "data", consultTeam.getStatus());
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    @ApiOperation("咨询是否结束")
    @RequestMapping(value = "/getConsultStatusByPrescription", method = RequestMethod.GET)
    public String getConsultStatusByPrescription(@ApiParam(name = "prescriptionCode", value = "续方code")
                                                 @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            ConsultTeamDo consultTeam = consultTeamService.getConsultStatus(prescriptionCode);
            if (consultTeam != null) {
                return write(200, "查询成功", "data", consultTeam.getStatus());
            } else {
                return error(-1, "咨询不存在");
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
//
//    /**
//     * 设置消息已读
//     *
//     * @param consult
//     * @return
//     */
//    @ApiOperation("设置消息已读")
//    @RequestMapping(value = "/readed", method = RequestMethod.POST)
//    public String readMessage(String consult) {
//        try {
//            int result = consultTeamService.readMessage(consult);
//            return write(200, "设置成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    @ApiOperation("医生发送topic消息")
//    @RequestMapping(value = "sendTopicIM", method = RequestMethod.POST)
//    public String sendTopicIM(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "sender_id", value = "发送者id")
//                              @RequestParam(value = "sender_id", required = true) String sender_id,
//                              @ApiParam(name = "sender_name", value = "发送者姓名")
//                              @RequestParam(value = "sender_name", required = true) String sender_name,
//                              @ApiParam(name = "content_type", value = "消息类型")
//                              @RequestParam(value = "content_type", required = true) String content_type,
//                              @ApiParam(name = "content", value = "消息内容")
//                              @RequestParam(value = "content", required = true) String content,
//                              @ApiParam(name = "sessionId", value = "会话id")
//                              @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            imUtill.sendTopicIM(sender_id, sender_name, consult, content_type, content, null);
//            return success("发送成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "发送失败");
//    }
//
//    @ApiOperation("医生发送会话消息")
//    @RequestMapping(value = "sendImMsg", method = RequestMethod.POST)
//    public String sendImMsg(@ApiParam(name = "consult", value = "咨询code")
//                            @RequestParam(value = "consult", required = false) String consult,
//                            @ApiParam(name = "sender_id", value = "发送者id")
//                            @RequestParam(value = "sender_id", required = true) String sender_id,
//                            @ApiParam(name = "sender_name", value = "发送者姓名")
//                            @RequestParam(value = "sender_name", required = true) String sender_name,
//                            @ApiParam(name = "content_type", value = "消息类型")
//                            @RequestParam(value = "content_type", required = true) String content_type,
//                            @ApiParam(name = "business_type", value = "会话业务类型")
//                            @RequestParam(value = "business_type", required = true) String business_type,
//                            @ApiParam(name = "content", value = "消息内容")
//                            @RequestParam(value = "content", required = true) String content,
//                            @ApiParam(name = "sessionId", value = "会话id")
//                            @RequestParam(value = "sessionId", required = true) String sessionId) {
//        try {
//            imUtill.sendImMsg(sender_id, sender_name, sessionId, content_type, content_type, business_type);
//            return success("发送成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return error(-1, "发送失败");
//    }
//
//    @ApiOperation("医生主动发送im消息")
//    @RequestMapping(value = "doctorSendImMsg", method = RequestMethod.POST)
//    public String doctorSendImMsg(@ApiParam(name = "patient", value = "居民code")
//                                  @RequestParam(value = "patient", required = true) String patient,
//                                  @ApiParam(name = "doctor", value = "医生code")
//                                  @RequestParam(value = "doctor", required = true) String doctor,
//                                  @ApiParam(name = "doctorName", value = "医生姓名")
//                                  @RequestParam(value = "doctorName", required = true) String doctorName,
//                                  @ApiParam(name = "sessionId", value = "会话id")
//                                  @RequestParam(value = "sessionId", required = true) String sessionId,
//                                  @ApiParam(name = "content", value = "消息内容")
//                                  @RequestParam(value = "content", required = true) String content,
//                                  @ApiParam(name = "contentType", value = "消息类型")
//                                  @RequestParam(value = "contentType", required = true) String contentType) {
//        try {
//            consultTeamService.doctorSendImMsg(patient, doctor, doctorName, sessionId, content, contentType);
//            return success("发送成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return error(-1, "发送失败");
//        }
//    }
//
//    @ApiOperation("医生拒绝视频")
//    @RequestMapping(value = "refuseVideo", method = RequestMethod.POST)
//    public String refuseVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor) {
//        try {
//            Doctor d = doctorDao.findByCode(doctor);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            imUtill.sendTopicIM(doctor, d.getName(), consult, "43", "医生在忙,建议提现预约视频通讯", null);
//            return success("拒绝成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生接通视频")
//    @RequestMapping(value = "connectVideo", method = RequestMethod.POST)
//    public String connectVideo() {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(1);
//            doctorDao.save(doctor);
//            return success("接通成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生挂断视频")
//    @RequestMapping(value = "handUpVideo", method = RequestMethod.POST)
//    public String handUpVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "time", value = "视频接通时长")
//                              @RequestParam(value = "time", required = true) String time) {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(0);
//            doctorDao.save(doctor);
//            imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consult, "41", time, null);
//            return success("挂断成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    /**
//     * 三师咨询列表查询
//     *
//     * @param type     咨询类型:0、全部,1、咨询我的,2、公共的, 3、参与过的,4、已结束的  5 名医咨询 全部
//     *                 6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医   10查询我咨询的
//     * @param id
//     * @param pagesize 每页显示数,默认为10
//     * @return
//     */
//    @ApiOperation("三师咨询列表查询")
//    @RequestMapping(value = "list", method = RequestMethod.POST)
//    public String list(int type,
//                       int id,
//                       int pagesize,
//                       @RequestParam(required = false) String patient,
//                       @RequestParam(required = false) String title) {
//        try {
//            Page<ConsultTeamDo> list = consultTeamService.findByDoctor(getUID(), type, id, pagesize, patient, title);
//            JSONArray jsonArray = new JSONArray();
//            if (list != null) {
//                for (ConsultTeamDo consult : list) {
//                    if (consult == null) {
//                        continue;
//                    }
//
//                    if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
//                        continue;
//                    }
//
//                    JSONObject json = new JSONObject();
//                    json.put("id", consult.getId());
//                    // 设置咨询标识
//                    json.put("consult", consult.getConsult());
//                    // 设置患者标识
//                    json.put("patient", consult.getPatient());
//                    // 设置患者姓名
//                    json.put("name", consult.getName());
//                    // 设置醫生标识
//                    json.put("doctor", consult.getDoctor());
//                    Doctor doctor = doctorService.findDoctorByCode(consult.getDoctor());
//                    // 设置醫生标识
//                    json.put("doctorName", doctor.getName());
//                    // 设置医生photo
//                    json.put("doctorPhoto", doctor.getPhoto());
//                    // 设置医生sex
//                    json.put("doctorSex", doctor.getSex());
//                    if (consult.getType() == 7) {
//                        Doctor d = doctorInfoService.findDoctorByCode(consult.getPatient());
//                        // 设置患者头像
//                        json.put("photo", d.getPhoto());
//                        // 设置患者年龄
//                        json.put("age", IdCardUtil.getAgeForIdcard(d.getIdcard()));
//                        // 设置性别
//                        json.put("sex", d.getSex());
//                    } else {
//                        Patient p = patientService.findByCode(consult.getPatient());
//                        // 设置患者头像
//                        json.put("photo", p.getPhoto());
//                        // 设置患者年龄
//                        json.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(), p.getBirthday()));
//                        // 设置性别
//                        json.put("sex", p.getSex());
//                    }
//                    // 设置咨询标识
//                    json.put("title", consult.getSymptoms());
//                    // 设置评价内容
//                    json.put("comment", consult.getCommentContent());
//                    // 设置评价星级
//                    json.put("star", consult.getCommentStar());
//                    // 设置咨询类型:1三师咨询,2家庭医生咨询 6名医咨询
//                    json.put("type", consult.getType());
//                    // 设置咨询时间
//                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    // 咨询状态
//                    json.put("status", consult.getStatus());
//                    // 未读消息
//                    json.put("doctorRead", consult.getDoctorRead());
//                    // 设置关联指导
//                    json.put("guidance", consult.getGuidance());
//                    json.put("startId", consult.getStartMsgId());
//                    json.put("endId", consult.getEndMsgId());
//                    List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
//                    if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
//                        for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
//                            json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
//                            json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
//                        }
//                    }
//                    jsonArray.put(json);
//                }
//            }
//            return write(200, "查询成功", "list", list, jsonArray);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//
//    @RequestMapping(value = "list_by_team", method = RequestMethod.POST)
//    @ApiOperation(value = "居民咨询列表查询")
//    public String listByTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
//                             @RequestParam @ApiParam(value = "团队Code") Long teamCode,
//                             @RequestParam @ApiParam(value = "第几页") int page,
//                             @RequestParam @ApiParam(value = "页大小") int pagesize) {
//        try {
//            if (StringUtils.isEmpty(patient)) {
//                return error(-1, "请输入需查询的居民");
//            }
//            if (teamCode == null || teamCode < 1) {
//                return error(-1, "请输入需查询的居民的团队");
//            }
//            page = page > 0 ? page - 1 : 0;
//            JSONArray jsonArray = consultTeamService.findByPatientAndTeam(patient, teamCode, page, pagesize);
//            return write(200, "查询成功", "data", jsonArray);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 获取三师家庭咨询
//     *
//     * @param status   0未处理或未回复 1已回复 2已结束
//     * @param id
//     * @param pagesize
//     * @param patient
//     * @return
//     */
//    @ApiOperation("获取三师家庭咨询")
//    @RequestMapping(value = "/list_by_status", method = RequestMethod.POST)
//    public String listByStatus(int status, int id, int pagesize,
//                               @RequestParam(required = false) String patient) {
//        try {
//            Page<ConsultTeamDo> list = consultTeamService.findConsultByDoctor(getUID(), status, id, pagesize);
//            JSONArray jsonArray = new JSONArray();
//            for (ConsultTeamDo consult : list) {
//                if (consult == null) {
//                    continue;
//                }
//
//                if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
//                    continue;
//                }
//
//                Patient p = patientService.findByCode(consult.getPatient());
//
//                JSONObject json = new JSONObject();
//                json.put("id", consult.getId());
//                // 设置咨询标识
//                json.put("consult", consult.getConsult());
//                // 设置患者标识
//                json.put("patient", consult.getPatient());
//                // 设置患者头像
//                json.put("photo", p.getPhoto());
//                // 设置咨询标识
//                json.put("title", consult.getSymptoms());
//                // 设置患者姓名
//                json.put("name", consult.getName());
//                // 设置患者年龄
//                json.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(), p.getBirthday()));
//                // 设置评价内容
//                json.put("comment", consult.getCommentContent());
//                // 设置评价星级
//                json.put("star", consult.getCommentStar());
//                // 设置咨询类型:1三师咨询,2家庭医生咨询 6名医咨询
//                json.put("type", consult.getType());
//                // 设置咨询时间
//                json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                // 咨询状态
//                json.put("status", consult.getStatus());
//                json.put("doctor", consult.getDoctor());
//                json.put("doctorName", consult.getDoctorName());
//                // 设置性别
//                json.put("sex", p.getSex());
//                // 未读消息
//                json.put("doctorRead", consult.getDoctorRead());
//                // 设置关联指导
//                json.put("guidance", consult.getGuidance());
//                json.put("startId", consult.getStartMsgId());
//                json.put("endId", consult.getEndMsgId());
//                List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
//                if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
//                    for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
//                        json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
//                        json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
//                    }
//                }
//                jsonArray.put(json);
//            }
//            return write(200, "查询成功", "list", jsonArray);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    @RequestMapping(value = "/hasTnvite", method = RequestMethod.POST)
//    public String hasTnvite(String groupCode) {
//        try {
//            JSONObject jo = new JSONObject();
//            List<WlyyTalkGroupMember> wlyyTalkGroupMembers = talkGroupService.findTalkGroupMembers(groupCode);
//            if (wlyyTalkGroupMembers.size() > 2) {
//                jo.put("hasTnvite", 1);//有邀请
//            } else {
//                jo.put("hasTnvite", 0);//没邀请
//            }
//            return write(200, "查询成功", "list", jo);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 名医列表
//     *
//     * @return
//     */
//    @ApiOperation("名医列表")
//    @RequestMapping(value = "famousDoctorList", method = RequestMethod.POST)
//    public String famousDoctorList(
//            @RequestParam(required = false) String name) {
//        try {
//            JSONArray array = new JSONArray();
//            List<Doctor> list = doctorService.getDoctorFamousDoctorList(name);
//            if (list != null) {
//                for (Doctor doctor : list) {
//                    if (doctor == null) {
//                        continue;
//                    }
//                    // 过滤掉自己
//                    if (doctor.getCode().equals(getUID())) {
//                        continue;
//                    }
//
//                    // 判断名医是否在工作
//                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(doctor.getCode());
//
//                    if (isWorking == null || !isWorking.getString("status").equals("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("level", doctor.getLevel());
//                    // 所在医院名称
//                    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());
//                    array.put(json);
//                }
//            }
//            return write(200, "获取医院医生列表成功!", "list", array);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 获取咨询全科医生签约量
//     *
//     * @param consults
//     * @return
//     */
//    @ApiOperation("获取咨询全科医生签约量")
//    @RequestMapping(value = "/consult_sign", method = RequestMethod.POST)
//    public String consultSign(String consults) {
//        try {
//            List<Map<String, Object>> list = consultTeamService.getConsultSign(consults.split(","));
//            return write(200, "查询成功", "data", new JSONArray(list));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 结束三师咨询接口
//     *
//     * @param consult 三师咨询标识
//     * @return
//     */
//    @ApiOperation("结束三师咨询接口")
//    @RequestMapping(value = "finish", method = RequestMethod.POST)
//
//    public String finish(String consult) {
//        try {
//            int flag = consultTeamService.finish(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
//     * 医生咨询咨询日志查询
//     *
//     * @param consult  咨询标识
//     * @param patient  患者标识
//     * @param pagesize 每页显示数,默认为10
//     * @return
//     */
//    @ApiOperation("医生咨询咨询日志查询")
//    @RequestMapping(value = "record", method = RequestMethod.POST)
//    public String record(String consult, String patient, long id, int pagesize) {
//        try {
//            Patient patientTemp = null;
//            if (id <= 0) {
//                // 只有第一页才会查询患者信息
//                patientTemp = patientService.findByCode(patient);
//                // 更新医生未读数量为0
//                consultTeamService.clearDoctorRead(consult);
//            }
//            // 查询日志列表
//            JSONArray jsonArray = new JSONArray();
//            Page<ConsultTeamDoLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
//            if (list != null) {
//                for (ConsultTeamDoLog log : list) {
//                    if (consult == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", log.getId());
//                    // 设置回复内容
//                    json.put("content", log.getContent());
//                    // 设置回复医生姓名
//                    json.put("doctorName", log.getDoctorName());
//                    // 设置回复人头像
//                    json.put("photo", log.getPhoto());
//                    // 设置日志类型
//                    json.put("type", log.getType());
//                    // 设置记录类型
//                    json.put("chatType", log.getChatType());
//                    // 设置咨询或回复时间
//                    json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    jsonArray.put(json);
//                }
//            }
//            // 设置返回结果
//            JSONObject values = new JSONObject();
//            if (patientTemp != null) {
//                JSONObject patientJson = new JSONObject();
//                // 设置患者标识
//                patientJson.put("patient", patientTemp.getCode());
//                // 设置姓名
//                patientJson.put("name", patientTemp.getName());
//                // 设置头像
//                patientJson.put("photo", patientTemp.getPhoto());
//                values.put("patient", patientJson);
//            }
//            values.put("list", jsonArray);
//            // 返回结果
//            return write(200, "查询成功", "data", values);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 医生回复网络咨询
//     *
//     * @param patient 患者标识
//     * @param consult 咨询标识
//     * @param content 回复内容
//     * @param type    回复类型,1文字,2图片,3语音
//     * @return
//     */
//    @ApiOperation("医生回复网络咨询")
//    @RequestMapping(value = "reply", method = RequestMethod.POST)
//    public String reply(String patient, String consult, String content, int type) {
//        try {
//            // 查询医生基本信息
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "回复失败!");
//            } else {
//                ConsultTeamDoLog log = new ConsultTeamDoLog();
//                // 设置咨询标识
//                log.setConsult(consult);
//                // 拷贝图片
//                if (StringUtils.isNotEmpty(content)) {
//                    if (type == 3) {
//                        // 语音
//                        content = CommonUtil.copyTempVoice(content);
//                    } else if (type == 2) {
//                        // 图片
//                        content = CommonUtil.copyTempImage(content);
//                    }
//                }
//                // 设置回复内容
//                log.setContent(content);
//                log.setDel("1");
//                // 设置回复医生标识
//                log.setDoctor(doctor.getCode());
//                // 设置医生姓名
//                log.setDoctorName(doctor.getName());
//                // 设置医生头像
//                log.setPhoto(doctor.getPhoto());
//                // 设置咨询类型为医生回复
//                log.setType(1);
//                // 设置记录类型
//                log.setChatType(type);
//                // 保存医生回复内容
//                log = consultTeamService.reply(log, patient, getUID(), log.getType());
//                if (log == null) {
//                    return error(-1, "回复失败!");
//                } else {
//                    // 推送消息给患者
//                    // 推送消息给微信端
//                    ConsultTeamDo ct = consultTeamService.findByCode(consult);
//                    Patient p = patientService.findByCode(patient);
//                    if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
//                        JSONObject json = new JSONObject();
//                        json.put("first", p.getName() + ",您好!\n您的健康咨询有新的回复");
//                        json.put("toUser", p.getCode());
//                        String symp = ct.getSymptoms();
//                        json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...") : content);
//                        String replycontent = content.length() > 50 ? content.substring(0, 50) + "..." : content;
//                        if (type == 2) {
//                            replycontent = "[图片]";
//                        } else if (type == 3) {
//                            replycontent = "[语音]";
//                        }
//                        json.put("consult", consult);
//                        json.put("replycontent", replycontent);
//                        json.put("doctorName", doctor.getName());
//                        json.put("remark", "医生已为您提供问诊方案");
//                        // PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
//                    }
//                    if (type == 2) {
//                        return write(200, "回复成功!", "data", content);
//                    }
//                    return success("回复成功!");
//                }
//            }
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "回复失败!");
//        }
//    }
//
//    /**
//     * 查询医生的总咨询次数和今日咨询次数
//     *
//     * @param doctorCode
//     * @return
//     */
//    @ApiOperation("查询医生的总咨询次数和今日咨询次数")
//    @RequestMapping(value = "getConsultCount", method = RequestMethod.POST)
//    public String getAllCount(@RequestParam(required = true) String doctorCode) {
//        try {
//            JSONObject json = new JSONObject();
//            Map<String, Long> counts = consultTeamService.getAllCount(doctorCode);
//
//            json.put("all", counts.get("all"));
//            json.put("today", counts.get("today"));
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 查询患者的服务数目
//     *
//     * @return
//     */
//    @ApiOperation("查询患者的服务数目")
//    @RequestMapping(value = "getPatientServicNum", method = RequestMethod.POST)
//    public String getPatientServicNum(String patientCode) {
//        try {
//            JSONObject json = new JSONObject();
//            //统计咨询数目
//            Integer allSize1 = consultTeamService.findByDoctorSize(patientCode, getUID());
//            //查询健康指导
//            Integer allSize2 = patientHealthGuidanceService.findGuidanceByPatient(patientCode, getUID());
//            json.put("consult", allSize1);
//            json.put("guide", allSize2);
//            //json.put("today", counts.get("today"));
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据医生code和和患者code判断是否有存在进行中的咨询
//     *
//     * @param patientCode 多个患者 逗号分隔
//     * @param doctor
//     * @return 只返回存在咨询的患者的code
//     */
//    @ApiOperation("根据医生code和和患者code判断是否有存在进行中的咨询")
//    @RequestMapping(value = "getConsultByPatientAndDoctor", method = RequestMethod.POST)
//    public String getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        try {
//            JSONArray json = new JSONArray();
//            String[] patients = patientCode.split(",");
//            //查询医生未结束居民列表
//            List<String> list = consultTeamService.getConsultListByPatientAndDoctor(doctor);
//            for (int i = 0; i < patients.length; i++) {
//                if (list.contains(patients[i])) {
//                    json.put(patients[i]);
//                }
//            }
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 名医咨询添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("名医咨询添加接口")
//    @RequestMapping(value = "famousAdd", method = RequestMethod.POST)
//
//    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());
//            }
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//                // 将临时图片拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.copyTempImage(images);
//                }
//            }
//
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = fetchWxVoices();
//            }
//            if (StringUtils.isNotEmpty(voice)) {
//                voice = CommonUtil.copyTempVoice(voice);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询
//            consult.setType(7);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            JSONObject result = consultTeamService.famousConsult(consult, getUID(), "2", null);
//            // 推送消息给医生
//            pushMsgTask.put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
//            if (StringUtils.isNotEmpty(images)) {
//                String[] arr = images.split(",");
//                for (String img : arr) {
//                    pushMsgTask.put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
//                }
//            }
//            return write(200, "创建成功!", "data", result);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param doctor 医生
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/is_consult_unfinished", method = RequestMethod.POST)
//    public String isExistsUnfinishedConsult(@RequestParam(required = false) String patient,
//                                            @RequestParam(required = false) String type,
//                                            @RequestParam(required = true) String doctor) {
//        try {
//            if ("1".equals(type)) {
//                //专科
//                List<ConsultHelp> helps = consultTeamService.findUnfinishedByPatientAndSpecialist(patient, doctor);
//                if (helps.size() > 0) {
//                    return write(200, "查询成功", "data", helps.get(0).getConsult());
//                } else {
//                    return write(200, "查询成功", "data", "");
//                }
//            }
//            List<ConsultTeamDo> consults = consultTeamService.getUnfinishedConsult(StringUtils.isEmpty(patient) ? getUID() : patient, doctor);
//
//            if (consults != null && consults.size() > 0) {
//                return write(200, "查询成功", "data", consults.get(0).getConsult());
//            } else {
//                return write(200, "查询成功", "data", "");
//            }
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param consult 咨询code
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/consultTeam", method = RequestMethod.POST)
//    public String consult(@RequestParam(required = false) String consult) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamService.findByCode(consult);
//            return write(200, "查询成功", "data", consultTeam);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 三师咨询转接接口
//     *
//     * @param consult 图咨询标识
//     * @param doctor  转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
//     * @param type    转接对象类型,1三师团队,2指定医生,3工作组团队
//     * @return
//     */
//    @ApiOperation("三师咨询转接接口")
//    @RequestMapping(value = "transfer", method = RequestMethod.POST)
//
//    public String transfer(
//            String consult,
//            String doctor,
//            @RequestParam(required = false) int type) {
//        try {
//            consultTeamService.transfers(getUID(), doctor, consult);
//            return success("转接成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据咨询code获取咨询的log
//     *
//     * @param consultCode
//     * @return
//     */
//    @ApiOperation("根据咨询code获取咨询的log")
//    @RequestMapping(value = "getConsultLog", method = RequestMethod.POST)
//    public String getConsultLog(
//            String consultCode) {
//        try {
//            List<ConsultTeamDoLog> consultTeamLogs = consultTeamService.getConsultLog(consultCode);
//            JSONArray ja = new JSONArray();
//            for (ConsultTeamDoLog log : consultTeamLogs) {
//                JSONObject json = new JSONObject();
//                json.put("id", log.getId());
//                // 设置回复内容
//                json.put("content", log.getContent());
//                // 设置回复医生姓名
//                json.put("doctorName", log.getDoctorName());
//                // 设置回复人头像
//                json.put("photo", log.getPhoto());
//                // 设置日志类型
//                json.put("type", log.getType());
//                // 设置记录类型
//                json.put("chatType", log.getChatType());
//                // 设置咨询或回复时间
//                json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                ja.put(json);
//            }
//            return write(200, "查询成功", "data", ja);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 医生求助添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param groupCode  从哪个讨论组发起的求助
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("医生求助添加接口")
//    @RequestMapping(value = "forHelpAdd", method = RequestMethod.POST)
//
//    public String forHelpAdd(
//            @RequestParam(required = false) String when,
//            String symptoms,
//            @RequestParam(required = false) String oldConsultCode,
//            @RequestParam(required = false) String groupCode,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            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);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
//            consult.setType(10);
//            // 设置来源(从哪个讨论组发起的求助)
//            consult.setTeam(groupCode);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            if (consultTeamService.isCommonTeam(doctorCode, getUID())) {
//                consultTeamService.sendForHelpMsg(consult, getUID(), oldConsultCode);
//            } else {
//                consultTeamService.addForHelpTeamConsult(consult, getUID(), oldConsultCode);
//            }
//            return success("提交成功");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    @RequestMapping(value = "hasUnfinished", method = RequestMethod.POST)
//    public String hasUnfinished(String doctorCode) {
//        try {
//            String curDoc = getUID();
//            JSONObject json = new JSONObject();
//            if (consultTeamService.isCommonTeam(doctorCode, curDoc)) {
//                json.put("isCommonTeam", 1);
//                return write(200, "查询成功", "data", json);
//            }
//            List<ConsultTeamDo> ls = consultTeamService.hasUnfinished(doctorCode, curDoc);
//            if (ls != null && ls.size() > 0) {
//                ConsultTeamDo ct = ls.get(0);
//                json.put("consult", ct.getConsult());
//                //是否是医生求助医生
//                if (ct.getType() == 10) {
//                    //取出原有咨询求助返回原咨询的患者
//                    ConsultTeamDo consultTeam = consultTeamService.findByConsultCode(ct.getTeam());
//                    Patient patient = patientService.findByCode(consultTeam.getPatient());
//                    json.put("zxGroupCode", consultTeam.getPatient() + "_" + consultTeam.getTeam() + "_" + consultTeam.getType());
//                    json.put("from", ct.getPatient());
//                    json.put("patient_name", patient.getName());
//                }
//            }
//            return write(200, "查询成功", "data", json);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 该咨询求助过的医生列表
//     *
//     * @param consult 关联的上一个咨询
//     * @return
//     */
//    @ApiOperation("该咨询求助过的医生列表")
//    @RequestMapping(value = "forHelpDocs", method = RequestMethod.POST)
//    public String forHelpDocs(String consult) {
//        try {
//            List<String> ls = consultTeamService.findByTeam(consult);
//            JSONObject json = new JSONObject();
//            if (ls != null) {
//                for (String o : ls) {
//                    json.put(o, 1);
//                }
//            }
//            return write(200, "查询成功", "data", json);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    @RequestMapping(value = "getConsult")
//    public String getConsult(String consult) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamService.findByConsultCode(consult);
//            return write(200, "查询成功", "data", consultTeam);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "/isConsultFinished", method = RequestMethod.POST)
//    public String isConsultFinished(@RequestParam String consult) {
//        try {
//            ConsultTeamDo ct = consultTeamService.findByConsultCode(consult);
//            return write(200, "查询咨询状态成功", "data", ct.getStatus());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "seekHelp", method = RequestMethod.POST)
//
//    public String seekHelp(
//            @RequestParam(required = true) String symptoms,
//            @RequestParam(required = false) String oldConsultCode,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = true) Integer isSend) {
//        try {
//            if (StringUtils.isEmpty(images)) {
//                images = fetchWxImages();
//                // 将临时图片拷贝到正式存储路径下
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.copyTempImage(images);
//                }
//            }
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
//            consult.setType(10);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//
//            consult.setDoctor(doctorCode);//设置专科医生
//            // 保存到数据库
//            if (consultTeamService.isCommonTeam(doctorCode, getUID())) {
//                consultTeamService.addSeekHelpTeam(consult, getUID(), oldConsultCode, isSend);
//            } else {
//                consultTeamService.addSeekHelpOtherTeam(consult, getUID(), oldConsultCode, isSend);
//            }
//            return success("提交成功");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//
//    /**
//     * 结束咨询接口
//     *
//     * @param consult 咨询标识
//     * @return
//     */
//    @ApiOperation("结束咨询接口")
//    @RequestMapping(value = "finish_consult", method = {RequestMethod.GET, RequestMethod.POST})
//
//    public String finishConsult(@RequestParam(required = false) String consult) {
//        try {
//            int flag = consultTeamService.finishConsult(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -1) {
//                return error(-1, "该咨询已经关闭,不需重复关闭!");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
//     * 网络咨询咨询日志查询
//     *
//     * @param consult  咨询标识
//     * @param pagesize 每页显示数,默认为10
//     * @return
//     */
//    @ApiOperation("网络咨询咨询日志查询")
//    @RequestMapping(value = "loglist", method = RequestMethod.GET)
//    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, getUID());
//            return write(200, "查询成功", "list", messageObj);
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /*********************************************续方咨询**************************************************************/
//
//    @RequestMapping(value = "prescriptionDetail", method = RequestMethod.GET)
//    @ApiOperation("获取续方信息")
//    public String prescriptionDetail(@ApiParam(name = "consult", value = "咨询code", defaultValue = "1")
//                                     @RequestParam(value = "consult", 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("prescriptionDt", prescriptionDiagnosisService.getPrescriptionDiagnosis(prescriptionCode));//续方疾病类型
//            json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
//            json.put("followup", followUpService.getFollowupByPrescriptionCode(prescriptionCode));//续方关联的随访记录
//
//            //服务类型
//            List<SignFamilyServer> list = signFamilyServerDao.findBySignCodeAndType(consult1.getSignCode());
//            JSONArray jsonArray = new JSONArray();
//            if (list != null && list.size() > 0) {
//                for (SignFamilyServer server : list) {
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("serverType", server.getServerType());
//                    jsonObject.put("serverTypeName", server.getServerTypeName());
//                    jsonArray.put(jsonObject);
//                }
//            }
//            json.put("signFamilyServer", jsonArray);
//            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) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionBloodStatusConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送血糖血压快捷回复咨询")
//    public String addPrescriptionBloodStatusConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1血压,2血糖)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionBloodStatusConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionFollowupContentConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送问卷快捷回复咨询")
//    public String addPrescriptionFollowupContentConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1症状,2体征及生活方式)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionFollowupContentConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "getSessionId", method = RequestMethod.GET)
//    @ApiOperation("pcim-获取居民的sessionId")
//    public String getSessionId(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                               @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            com.alibaba.fastjson.JSONObject re = consultTeamService.getSessionId(patient);
//            return write(200, "获取成功!", "data", re);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "sendBusinessCard", method = RequestMethod.POST)
//    @ApiOperation("发送居民的名片")
//
//    public String sendBusinessCard(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                                   @RequestParam(value = "patient", required = true) String patient,
//                                   @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                   @RequestParam(value = "sessionId", required = true) String sessionId,
//                                   @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                   @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String doctorCode = getUID();
//            Doctor doctor = doctorService.findDoctorByCode(doctorCode);
//
//            Patient p = patientService.findByCode(patient);
//            com.alibaba.fastjson.JSONObject content = new com.alibaba.fastjson.JSONObject();
//            content.put("name", p.getName());
//            content.put("patient", patient);
//            content.put("photo", p.getPhoto());
//            content.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(), p.getBirthday()));
//            content.put("sex", IdCardUtil.getSexForIdcard_new(p.getIdcard()));
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily != null) {
//                content.put("hospitalName", signFamily.getHospitalName());
//            }
//            imUtill.sendImMsg(doctorCode, doctor.getName(), sessionId, ImUtill.ContentType.personalCard.getValue(), content.toString(), businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "messageForward", method = RequestMethod.POST)
//    @ApiOperation("请求转发消息")
//    public String messageForward(@ApiParam(name = "senderId", value = "发送者id", defaultValue = "")
//                                 @RequestParam(value = "senderId", required = true) String senderId,
//                                 @ApiParam(name = "senderName", value = "发送者姓名", defaultValue = "")
//                                 @RequestParam(value = "senderName", required = true) String senderName,
//                                 @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                 @RequestParam(value = "sessionId", required = true) String sessionId,
//                                 @ApiParam(name = "content", value = "会话内容", defaultValue = "")
//                                 @RequestParam(value = "content", required = true) String content,
//                                 @ApiParam(name = "title", value = "会话标题", defaultValue = "")
//                                 @RequestParam(value = "title", required = true) String title,
//                                 @ApiParam(name = "sessionType", value = "原会话的会话类型", defaultValue = "")
//                                 @RequestParam(value = "sessionType", required = true) String sessionType,
//                                 @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                 @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String message = consultTeamService.getMessageById(sessionType, content, title);
//            imUtill.sendImMsg(senderId, senderName, sessionId, ImUtill.ContentType.messageForward.getValue(), message, businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "examinationDetail", method = RequestMethod.GET)
//    @ApiOperation("获取在线复诊信息")
//    public String examinationDetail(@ApiParam(name = "consult", value = "咨询code", defaultValue = "1")
//                                    @RequestParam(value = "consult", 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("examinationDt", examination.getAdjustReason());//续方疾病类型
//
//            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) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "updateConsultParticipant", method = RequestMethod.POST)
//    @ApiOperation("更新会话成员(新增或删除)")
//
//    public String updateConsultParticipant(@ApiParam(name = "sessionid", value = "会话ID", defaultValue = "1")
//                                           @RequestParam(value = "sessionid", required = true) String sessionid,
//                                           @ApiParam(name = "userid", value = "新增成员ID,多个以英文逗号隔开", defaultValue = "1")
//                                           @RequestParam(value = "userid", required = true) String userid,
//                                           @ApiParam(name = "olduserid", value = "删除的成员id")
//                                           @RequestParam(value = "olduserid", required = false) String olduserid) {
//        try {
//            imUtill.updateParticipant(sessionid, userid, olduserid);
//            return write(200, "操作成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "inviteDoctor", method = RequestMethod.POST)
//    @ApiOperation("邀请医生回复居民问题")
//
//    public String inviteDoctor(@ApiParam(name = "sessionid", value = "会话ID")
//                               @RequestParam(value = "sessionid", required = true) String sessionid,
//                               @ApiParam(name = "doctor", value = "被邀请人")
//                               @RequestParam(value = "doctor", required = true) String doctor,
//                               @ApiParam(name = "topic", value = "咨询id")
//                               @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            String uid = getUID();
//            imUtill.updateParticipant(sessionid, doctor, null);
//            //设置邀请消息
//            Doctor from = doctorDao.findByCode(uid);
//            Doctor d = doctorDao.findByCode(doctor);
//            String content = "已邀请" + d.getName() + "医生为您服务,请耐心等待";
//            imUtill.sendTopicIM(from.getCode(), from.getName(), topic, "1", content, null);
//            //发送邀请医生提醒消息
////            if(StringUtils.isNotEmpty(d.getOpenid())){
////                String first = from.getName()+"医生邀请您,为";
////                doctorAssistantUtil.sendWXTemplate(1,d.getOpenid(),d.getCid(),"咨询邀请回复","","");
////            }
//            return write(200, "操作成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "askSpecialist", method = RequestMethod.POST)
//    @ApiOperation("邀请专科-回复居民咨询")
//
//    public String askSpecialist(@ApiParam(name = "sessionid", value = "会话ID")
//                                @RequestParam(value = "sessionid", required = true) String sessionid,
//                                @ApiParam(name = "doctor", value = "被邀请人")
//                                @RequestParam(value = "doctor", required = true) String doctor,
//                                @ApiParam(name = "topic", value = "咨询id")
//                                @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            consultTeamService.askSpecialist(topic, sessionid, getUID(), doctor);
//            return write(200, "操作成功!");
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 家庭医生发起康复咨询
//     *
//     * @param when              发病时间
//     * @param oldConsultCode    从哪个讨论组发起的求助
//     * @param specialDoctorCode 专科医生
//     * @param specialDoctorCode 全科医生
//     * @param images            图片URL地址,多图以逗号分隔
//     * @param voice             语音URL地址
//     * @param doctorCode        名医的code
//     * @return
//     */
//    @ApiOperation("医生求助添加接口")
//    @RequestMapping(value = "forSpecialAdd", method = RequestMethod.POST)
//
//    public String forSpecialAdd(
//            @RequestParam(required = false) String when,
//            @RequestParam(required = false) String oldConsultCode,
//            @RequestParam(required = false) String specialDoctorCode,
//            @RequestParam(required = false) String doctorCode,
//            @RequestParam(required = false) String patientCode,
//            @RequestParam(required = false) String images,
//            @RequestParam(required = false) String voice) {
//        try {
//            String symptoms = "";
//            if (StringUtils.isNoneBlank(oldConsultCode)) {
//                Consult consult = consultDao.findByCode(oldConsultCode);
//                symptoms = consult.getSymptoms();
//            }
//
//            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);
//            }
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型:1三师咨询,2家庭医生咨询  6.名医咨询   18.康复咨询
//            consult.setType(18);
//            // 设置发病时间
//            consult.setWhen(when);
//            // 设置主要症状
//            consult.setSymptoms(symptoms);
//            // 设置咨询图片URL
//            consult.setImages(images);
//            // 设置咨询语音URL
//            consult.setVoice(voice);
//
//            consult.setIsAuthentication(0);
//            consult.setIsRefinement(0);
//            // 保存到数据库
//            int res = 0;
//            JSONArray dts = null;
//            synchronized (getRepUID().intern()) {//新增同步方法。设备保存写在service层但是不生效,写在controller层才生效
//                JSONObject re = consultTeamService.addTeamSpecialConsult(consult, patientCode, getUID(), specialDoctorCode, doctorCode);
//                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, "还有咨询未结束,不允许再次提交咨询!");
//            }
//            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
//            if (flag) {
//                pushMsgTask.put(specialDoctorCode, 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());
//                Doctor doctor = doctorDao.findByCode(specialDoctorCode);
//                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");
//                }
//            }
////                }
////            }
//
//            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) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    @RequestMapping(value = "getKangFuConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getKangFuConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                       @ApiParam(name = "patient", value = "居民CODE") @RequestParam(required = false) String patient,
//                                       @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(patient, id, pagesize, 18, title);//18表示康复咨询
//            Patient patientobj = patientService.findByCode(patient);
//            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("patientName", patientobj.getName());
//                    json.put("patientPhoto", patientobj.getPhoto());
//                    // 设置主诉
//                    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) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "/getDoctorConsultSessions", method = RequestMethod.GET)
//    @ApiOperation("获取医生咨询列表,带专家咨询")
//    public String getDoctorConsultSessions(@ApiParam(name = "user_id", value = "会话医生code", required = true)
//                                           @RequestParam(value = "user_id", required = true) String user_id,
//                                           @ApiParam(name = "business_type", required = true)
//                                           @RequestParam(value = "business_type", required = true, defaultValue = "2") String business_type,
//                                           @ApiParam(name = "status", value = "0未结束,1已结束", required = true)
//                                           @RequestParam(value = "status", required = true) String status,
//                                           @ApiParam(name = "page", required = true)
//                                           @RequestParam(value = "page", required = true, defaultValue = "0") String page,
//                                           @ApiParam(name = "size", required = true)
//                                           @RequestParam(value = "size", required = true, defaultValue = "50") String size
//    ) {
//        try {
//            return write(200, "查询成功", "data", consultTeamService.getDoctorConsultSessions(user_id, business_type, status, page, size));
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    @RequestMapping(value = "/getIMkangFuConsultSessions", method = RequestMethod.GET)
//    @ApiOperation("获取医生康复咨询IM列表")
//    public String getIMkangFuConsultSessions(@ApiParam(name = "user_id", value = "会话医生code", required = true)
//                                             @RequestParam(value = "user_id", required = true) String user_id,
//                                             @ApiParam(name = "type", required = true)
//                                             @RequestParam(value = "type", required = true, defaultValue = "18") String type,
//                                             @ApiParam(name = "status", value = "0未结束,1已结束", required = false)
//                                             @RequestParam(value = "status", required = false) String status,
//                                             @ApiParam(name = "name", value = "居民姓名支持模糊", required = false)
//                                             @RequestParam(value = "name", required = false) String name,
//                                             @ApiParam(name = "page", required = true)
//                                             @RequestParam(value = "page", required = true, defaultValue = "0") String page,
//                                             @ApiParam(name = "size", required = true)
//                                             @RequestParam(value = "size", required = true, defaultValue = "50") String size
//    ) {
//        try {
//            return write(200, "查询成功", "data", consultTeamService.getIMkangFuConsultSessions(user_id, type, status, page, size, name));
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "/getSpecialAndKangFuConsultUnreadInfo", method = RequestMethod.GET)
//    @ApiOperation("获取专家咨询、康复咨询是否存在未处理")
//    public String getSpecialAndKangFuConsultUnreadInfo(@ApiParam(name = "user_id", value = "医生code")
//                                                       @RequestParam(value = "user_id", required = true) String user_id
//    ) {
//        try {
//            return write(200, "查询成功", "data", consultTeamService.getSpecialAndKangFuConsultUnreadInfo(user_id));
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
}

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

@ -13,17 +13,16 @@ 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 ConsultOrderDao consultDao;
//    @Autowired
    //    @Autowired
//    public BasePatientDao patientDao;
    @Autowired
    public BaseDoctorDao doctorDao;
@ -32,7 +31,7 @@ public class ConsultService {
    @Autowired
    private ImUtil imUtill;
//    @Value("${hlwyy.url}")
    //    @Value("${hlwyy.url}")
//    private String hlwyyUrl;
//    @Value("${im.data_base_name}")
////    private String ImDbName;
@ -67,10 +66,11 @@ public class ConsultService {
     * @param type    咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,5病友圈,9在线复诊,11上门服务
     * @return
     */
    public ConsultDo addConsult(String patient, String title, String symptoms, String images, int type) {
    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.setCode(UUID.randomUUID().toString().replaceAll("-", ""));//UUID
        consult.setCzrq(new Date());
        consult.setDel("1");
        consult.setPatient(patient);
@ -78,11 +78,6 @@ public class ConsultService {
        consult.setSymptoms(symptoms);
        consult.setImages(images);
        consult.setType(type);
        //这边是没有签约
//		SignFamily signFamily = signFamilyDao.findByPatient(patient);
//		if(signFamily!=null){
//			consult.setSignCode(signFamily.getCode());
//		}
        return consultDao.save(consult);
    }

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

@ -1,5 +1,6 @@
package com.yihu.jw.hospital.module.consult.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultDo;
@ -8,23 +9,15 @@ 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;
@ -68,53 +61,50 @@ public class ConsultTeamService extends ConsultService {
    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 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 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;
@ -122,10 +112,10 @@ public class ConsultTeamService extends ConsultService {
    private String imdb;
    @Autowired
    private PushMsgTask pushMsgTask;
    
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    
    @Autowired
    private ImUtil imUtill;
@ -178,7 +168,10 @@ public class ConsultTeamService extends ConsultService {
//    private PresModeAdapter presModeAdapter;
//    @Autowired
//    private ZyDictService zyDictService;
//    @Autowired
//    private WeiXinOpenIdUtils weiXinOpenIdUtils;
//    @Autowired
//    private MessageDao messageDao;
    /**
@ -194,32 +187,17 @@ public class ConsultTeamService extends ConsultService {
        String doctorName = doorServiceOrderDO.getDispatcherName();
        int orderStatus = doorServiceOrderDO.getStatus();
//        // 判断居民是否已经签约
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        if (signFamily == null) {
//            result.put(ResponseContant.resultFlag, ResponseContant.fail);
//            String failMsg = "当前居民未签约,无法进行上门服务咨询!";
//            result.put(ResponseContant.resultMsg, failMsg);
//            return result;
//        }
        // 添加咨询记录
        //添加咨询记录
        BasePatientDO patientDO = patientService.findPatientById(patient);
        if (null == patientDO) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前咨询的居民不存在!";
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
            throw new Exception("当前居民不存在");
        }
        //咨询记录
        String title = patientDO.getName() + "-发起了服务咨询";
        ConsultDo consult = super.addConsult(patient, title, doorServiceOrderDO.getServeDesc(), patientDO.getPhone(), 11);
        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);
@ -233,41 +211,47 @@ public class ConsultTeamService extends ConsultService {
        consultTeam.setEvaluate(0);
        consultTeam.setDoctorRead(1); // 医生未读数量为1
        consult.setRelationCode(doorServiceOrderDO.getId());//关联业务code
        consultTeam.setConsult(consult.getCode()); // 设置咨询标识
        consultTeam.setConsult(consult.getId()); // 设置咨询标识
        //(im创建咨询) 上门服务咨询的sessionid为居民code+咨询code+工单编号+咨询类型
        String sessionId = patient + "_" + consult.getCode() + "_" + doorServiceOrderDO.getNumber() + "_" + consultTeam.getType();
        //原本:(im创建咨询) 上门服务咨询的sessionid为居民code+咨询code+工单编号+咨询类型
        String sessionId = patient + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consultTeam.getType();
        //4、 上门服务咨询-参与者
        JSONObject participants = new JSONObject();
        participants.put(patient, 0);
        String content;
        if (StringUtils.isNotBlank(doorServiceOrderDO.getDoctorName())) {
            content = doorServiceOrderDO.getDoctorName() + "-为您服务";
        } else {
            content = "调度员即将分配人员为您服务";
        }
//        String content = patientDO.getName() + "-上门服务咨询";
//        String content = signFamily.getHospitalName() + "为您服务";
        String content = doorServiceOrderDO.getDoctorName() + "为您服务";
        //封装JSONObject的messages
        JSONObject messages = imUtill.getCreateTopicMessage(patient, patientDO.getName(), consult.getTitle(), content, consult.getImages(), "");
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getCode(), content, participants, messages, imUtill.SESSION_TYPE_ONDOOR_NURSING);
        /**
         * 创建议题
         */
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getId(), content, participants, messages, ImUtil.SESSION_TYPE_ONDOOR_NURSING);
        System.out.println("创建议题成功了!!!!!!!!!!!!!!!!");
        if (imResponseJson == null || imResponseJson.getString("status").equals("-1")) {
            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
            throw new Exception(failMsg);
        }
        consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        if (imResponseJson != null && imResponseJson.get("start_msg_id") != null) {
            consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        }
        System.out.println("准备保存consultTeam和consult");
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        System.out.println("保存的consultTeam==>"+ JSON.toJSONString(consultTeam));
        System.out.println("保存的consult==>"+ JSON.toJSONString(consult));
        System.out.println("保存consultTeam和consult成功");
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
    
//    @PostConstruct
//    public void init() {
@ -547,7 +531,7 @@ public class ConsultTeamService extends ConsultService {
     * 医生主动发送im消息
     */
    public void doctorSendImMsg(String patient, String doctor, String doctorName, String sessionId, String content, String contentType) {
        BasePatientDO  p = patientDao.findById(patient).orElse(null);
        BasePatientDO p = patientDao.findById(patient).orElse(null);
        if (StringUtils.isNotBlank(p.getOpenid())) {
            WechatTemplateConfig temp = templateConfigDao.findByScene("template_consult_notice", "yszdxx");
            org.json.JSONObject json = new org.json.JSONObject();
@ -1857,7 +1841,6 @@ public class ConsultTeamService extends ConsultService {
//
//        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'";
@ -2194,11 +2177,14 @@ public class ConsultTeamService extends ConsultService {
//    public int cancel(String consult) {
//        return consultTeamDao.cancel(consult);
//    }
    public ConsultTeamDo findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }
    public ConsultTeamDo findById(String id) {
        return consultTeamDao.findById(id).orElse(null);
    }
    /**
     * 三师咨询转接医生
     *
@ -2306,7 +2292,6 @@ public class ConsultTeamService extends ConsultService {
//
//        return consultDao.findByPatient(patientCode, doctorCode);
//    }
    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();
@ -2344,7 +2329,7 @@ public class ConsultTeamService extends ConsultService {
//        }
//
//        String content = "进入了咨询";
//        BasePatientDO  p = patientDao.findById(patient).orElse(null);
//        BasePatientDO  p = patientDao.findById(patient);
//        String intoUserName = p.getName();
//        if (patient.equals(agent)) {
//            content = intoUserName + content;
@ -2402,7 +2387,6 @@ public class ConsultTeamService extends ConsultService {
//        sf.append(sf1);
//        return sf.toString();
//    }
    public void save(ConsultTeamDo consult) {
        consultTeamDao.save(consult);
    }
@ -2418,7 +2402,7 @@ public class ConsultTeamService extends ConsultService {
//    public void addForHelpTeamConsult(ConsultTeamDo ct, String uid, String oldConsultCode) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        BaseDoctorDO doctorTemp = doctorDao.findById(uid).orElse(null);
//        BaseDoctorDO doctorTemp = doctorDao.findById(uid);
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
@ -2576,7 +2560,7 @@ public class ConsultTeamService extends ConsultService {
//                    }
//                }
//            }
//            BaseDoctorDO doctorTemp = doctorDao.findById(ct.getDoctor()).orElse(null);
//            BaseDoctorDO doctorTemp = doctorDao.findById(ct.getDoctor());
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
@ -3071,20 +3055,21 @@ public class ConsultTeamService extends ConsultService {
    /**
     * 根据续方code获取咨询
     */
//    public ConsultTeamDo getConsultStatus(String prescriptionCode) {
//        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
    public ConsultTeamDo getConsultStatus(String prescriptionCode) {
        //先注释掉
//        WlyyPrescriptionDO prescription = prescriptionDao.findByCode(prescriptionCode);
//        if (prescription != null) {
//            return consultTeamDao.findByConsult(prescription.getConsult());
//        }
//        return null;
//    }
        return null;
    }
    /**
     * pcim 使用
     */
    public com.alibaba.fastjson.JSONObject getSessionId(String patient) {
        com.alibaba.fastjson.JSONObject re = new com.alibaba.fastjson.JSONObject();
    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("' ");
@ -3129,7 +3114,7 @@ public class ConsultTeamService extends ConsultService {
     * 返回json
     */
    public String getMessageById(String sessionType, String content, String title) {
        com.alibaba.fastjson.JSONObject re = new com.alibaba.fastjson.JSONObject();
        JSONObject re = new JSONObject();
        re.put("title", title);
        content = "'" + content.replace(",", "','") + "'";
        String tableName = "";
@ -3152,7 +3137,7 @@ public class ConsultTeamService extends ConsultService {
        com.alibaba.fastjson.JSONArray ja = new com.alibaba.fastjson.JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            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"));
@ -3346,62 +3331,63 @@ public class ConsultTeamService extends ConsultService {
//    }
    /**
     * 根据关联业务code查询咨询记录 wlyyDoorServiceOrderService.queryOneDetail(consult.getRelationCode());
     */
//    public ConsultTeamDo queryByRelationCode(String relationCode) {
//        if (StringUtils.isEmpty(relationCode)) {
//            return null;
//        }
//        ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(relationCode);
//        return consultTeam;
//    }
    public ConsultTeamDo queryByRelationCode(String relationCode) {
        if (StringUtils.isEmpty(relationCode)) {
            return null;
        }
        ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(relationCode);
        return consultTeam;
    }
    /**
     * 根据咨询查关联业务记录
     */
//    public com.alibaba.fastjson.JSONObject queryByConsultCode(String code, Integer type) {
//        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
//        if (StringUtils.isEmpty(code) || null == type) {
//            return null;
//        }
//        Consult consult = consultDao.queryByCodeAndType(code, type);
//
//        if (null == consult) {
//            result.put("data", "");
//            return result;
//        }
//
//        if (type == 11) {
//            WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findOne(consult.getRelationCode());
//            com.alibaba.fastjson.JSONObject patientInfo = wlyyDoorServiceOrderService.queryOrderCardInfo(orderDO);
//            result.put("data", patientInfo);
//        }
//
//        result.putIfAbsent("data", consult);
//        return result;
//    }
    public JSONObject queryByConsultCode(String code, Integer type) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(code) || null == type) {
            return null;
        }
        //这是id
        ConsultDo consult = consultDao.queryByIdAndType(code, type);
//    public JSONObject updateIMMsg(String sessionId, String sessionType, String msgId, String content) {
//        JSONObject result = new JSONObject();
//        if (StringUtils.isEmpty(sessionId) || StringUtils.isEmpty(sessionType) || StringUtils.isEmpty(msgId) || StringUtils.isEmpty(content)) {
//            result.put("data", "参数【sessionId,sessionType,msgId,content】不可为空!");
//            result.put("status", -1);
//            return result;
//        }
//        JSONObject contentJsonObj = null;
//        try {
//            contentJsonObj = new JSONObject(content);
//        } catch (Exception e) {
//            result.put("status", -1);
//            result.put("data", "【content】必须是json格式:" + e.getMessage());
//            return result;
//        }
//        String response = ImUtill.updateMessage(sessionId, sessionType, msgId, content);
//        return new JSONObject(response);
//    }
//        ConsultDo consult = consultDao.findByRelationCode(code);
        if (null == consult) {
            result.put("data", "");
            return result;
        }
        if (type == 11) {
            WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findById(consult.getRelationCode()).orElse(null);
            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();
@ -3506,4 +3492,5 @@ public class ConsultTeamService extends ConsultService {
//        return result;
//    }
}

+ 100 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/district/controller/DistrictController.java

@ -0,0 +1,100 @@
package com.yihu.jw.hospital.module.district.controller;
import com.yihu.jw.hospital.module.district.service.DistrictService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
/**
 * 省市区三级地址控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DistrictController extends EnvelopRestEndpoint {
    @Autowired
    private DistrictService districtService;
    @Autowired
    HttpServletRequest request;
    /**
     * 获取人群分类
     */
    @RequestMapping(value = "getProfessionalDict", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("职业状态字典")
    public String getProfessionalDict() {
        try {
            // 获取医生下的患者
            return write(200, "获取成功!", "data", districtService.getProfessionalDict());
        } catch (Exception e) {
            return error(-1, "获取字典信息失败!");
        }
    }
    @RequestMapping(value = "getNationDict",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取民族信息列表")
    public String getNationDict(){
        try {
            // 获取医生下的患者
            return write(200, "获取成功!", "data",districtService.getNationDict());
        } catch (Exception e) {
            return error(-1, "获取字典信息失败!");
        }
    }
    /**
     * 省市一二三级查询接口
     *
     * @param type 1一级目录,2二级目录,3三级目录,4街道目录
     * @param code 省或市标识
     * @return
     */
    @RequestMapping(value = "district")
    @ResponseBody
    public String district(int type, String code) {
        try {
            List<?> list = districtService.findByType(type, code);
            return write(200, "查询成功!", "list", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 省市一二三级查询接口(包含权限控制)
     *
     * @param type 1一级目录,2二级目录,3三级目录,4街道目录
     * @param code 省或市标识
     * @return
     */
    @RequestMapping(value = "districtAuthority")
    @ResponseBody
    public String districtAuthority(int type, String code) {
        try {
            List<Map<String, String>> roleMap = (List<Map<String, String>>) request.getSession().getAttribute("roleMap");
            List<?> list = districtService.findByType(type, code, roleMap);
            return write(200, "查询成功!", "list", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
}

+ 249 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/district/service/DistrictService.java

@ -0,0 +1,249 @@
package com.yihu.jw.hospital.module.district.service;
import com.yihu.jw.area.dao.BaseCityDao;
import com.yihu.jw.area.dao.BaseProvinceDao;
import com.yihu.jw.area.dao.BaseStreetDao;
import com.yihu.jw.area.dao.BaseTownDao;
import com.yihu.jw.entity.base.area.BaseCityDO;
import com.yihu.jw.entity.base.area.BaseProvinceDO;
import com.yihu.jw.entity.base.area.BaseStreetDO;
import com.yihu.jw.entity.base.area.BaseTownDO;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * 省市区三级业务处理类
 *
 * @author George
 */
@Service
public class DistrictService extends EnvelopRestEndpoint {
    @Autowired
    private BaseProvinceDao provinceDao;
    @Autowired
    private BaseCityDao cityDao;
    @Autowired
    private BaseTownDao townDao;
    @Autowired
    private BaseStreetDao streetDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 查询省市区三级目录
     *
     * @param type 1一级目录,2二级目录,3三级目录,4街道目录
     * @param code 目录标识
     * @return
     */
    public List<?> findByType(int type, String code) {
        switch (type) {
            case 1:
                return findProvince();
            case 2:
                return findCity(code);
            case 3:
                return findTown(code);
            case 4:
                return findStreet(code);
        }
        return null;
    }
    /**
     * 查询省市区三级目录
     *
     * @param type 1一级目录,2二级目录,3三级目录,4街道目录
     * @param code 目录标识
     * @return
     */
    public List<?> findByType(int type, String code, List<Map<String, String>> roleMap) {
        switch (type) {
            case 1:
                return findProvince();
            case 2:
                return findCity(code);
            case 3:
                return findTown(code, roleMap);
            case 4:
                return findStreet(code);
        }
        return null;
    }
    /**
     * 查询所有的省份信息
     *
     * @return
     */
    public List<BaseProvinceDO> findProvince() {
        List<BaseProvinceDO> list = new ArrayList<BaseProvinceDO>();
        Iterable<BaseProvinceDO> iterable = provinceDao.findAll(Sort.by(Direction.ASC, "id"));
        if (iterable != null) {
            Iterator<BaseProvinceDO> it = iterable.iterator();
            while (it != null && it.hasNext()) {
                list.add(it.next());
            }
        }
        return list;
    }
    /**
     * 查询省份下的城市信息
     *
     * @param province 省编码
     * @return
     */
    public List<BaseCityDO> findCity(String province) {
        List<BaseCityDO> list = new ArrayList<BaseCityDO>();
        Iterable<BaseCityDO> iterable = cityDao.findByProvince(province);
        if (iterable != null) {
            Iterator<BaseCityDO> it = iterable.iterator();
            while (it != null && it.hasNext()) {
                list.add(it.next());
            }
        }
        return list;
    }
    /**
     * 查询城市下的区县信息
     *
     * @param city 城市编码
     * @return
     */
    public List<BaseTownDO> findTown(String city) {
        List<BaseTownDO> list = new ArrayList<BaseTownDO>();
        Iterable<BaseTownDO> iterable = townDao.findByCity(city);
        if (iterable != null) {
            Iterator<BaseTownDO> it = iterable.iterator();
            while (it != null && it.hasNext()) {
                list.add(it.next());
            }
        }
        return list;
    }
    /**
     * 查询城市下的区县信息(包含权限控制)
     *
     * @param city 城市编码
     * @return
     */
    public List<BaseTownDO> findTown(String city, List<Map<String, String>> roleMap) {
        List<BaseTownDO> list = new ArrayList<BaseTownDO>();
        Iterable<BaseTownDO> iterable = townDao.findByCity(city);
        if (iterable != null) {
            String areaString = "";
            Boolean cityFlag = false;
            for (Map<String, String> map : roleMap) {
                String code = map.get("code");
                if ("350200".equals(code)) {
                    cityFlag = true;
                    break;
                } else if (code.length() == 6) {
                    areaString += map.get("areas") + ",";
                }
            }
            Iterator<BaseTownDO> it = iterable.iterator();
            while (it != null && it.hasNext()) {
                BaseTownDO town = it.next();
                String townCode = town.getCode();
                if (cityFlag) {
                    list.add(town);
                } else {
                    if (areaString.indexOf(townCode) >= 0) {
                        list.add(town);
                    }
                }
            }
        }
        return list;
    }
    /**
     * 查询城市下的街道信息
     *
     * @param town 区县编码
     * @return
     */
    public List<BaseStreetDO> findStreet(String town) {
        List<BaseStreetDO> list = new ArrayList<BaseStreetDO>();
        Iterable<BaseStreetDO> iterable = streetDao.findByTown(town);
        if (iterable != null) {
            Iterator<BaseStreetDO> it = iterable.iterator();
            while (it != null && it.hasNext()) {
                list.add(it.next());
            }
        }
        return list;
    }
//    /**
//     * 查询城市下的街道信息
//     *
//     * @param street 街道编码
//     * @return
//     */
//    public List<Country> findCountry(String street) {
//        List<Country> list = new ArrayList<Country>();
//        Iterable<Country> iterable = countryDao.findByStreet(street);
//        if (iterable != null) {
//            Iterator<Country> it = iterable.iterator();
//            while (it != null && it.hasNext()) {
//                list.add(it.next());
//            }
//        }
//        return list;
//    }
    public BaseProvinceDO findProvinceByName(String name) {
        return provinceDao.findByName(name);
    }
    public BaseCityDO findCityByName(String name) {
        return cityDao.findByName(name);
    }
    public BaseTownDO finTownByName(String name) {
        return townDao.findByName(name);
    }
    public BaseTownDO finTownByNameAndCity(String name, String city) {
        return townDao.findByNameAndCity(name, city);
    }
    public BaseStreetDO findStreetByName(String name) {
        return streetDao.findByName(name);
    }
    public List<Map<String, Object>> getProfessionalDict() {
        String sql = "SELECT t.dict_code 'code',t.dict_value `value` FROM `base`.`wlyy_hospital_sys_dict`  t WHERE t.dict_name='PROFESSIONAL_STATE'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    public List<Map<String, Object>> getNationDict() {
        String sql = "SELECT t.NATION_CODE,t.NATION_NAME FROM zy_nation_dict t ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}

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

@ -20,6 +20,9 @@ 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;
import java.net.URLEncoder;
/**
 * Created by zdm on 2019/3/13.
 */
@ -34,6 +37,13 @@ public class DoctorDoorServiceAuditController extends EnvelopRestEndpoint {
    private BasePatientService patientService;
    /**
     * 参数:
     * auditorType: 2
     * status: 0
     * page: 1
     * pageSize: 15
     */
    @RequestMapping(value = "getPOnsiteServiceByDoctor", method = RequestMethod.GET)
    @ApiOperation(value = "获取待审核的居民上门服务资质申请")
    public Envelop getPOnsiteServiceByDoctor(
@ -60,8 +70,8 @@ public class DoctorDoorServiceAuditController extends EnvelopRestEndpoint {
    @RequestMapping(value = "getDoorSericeApplicationStatus", method = RequestMethod.GET)
    @ApiOperation(value = "获取资质审核状态")
    public Envelop getDoorSericeApplicationStatus(
            @ApiParam(name = "patient", value = "patient")
            @RequestParam(value = "patient", required = true) String patient) {
            @ApiParam(name = "patient", value = "patient") @RequestParam(value = "patient", required = true) String patient
    ) {
        try {
            return success("获取成功", doorServiceApplicationService.getDoorSericeApplicationStatus(patient));
        } catch (Exception ex) {
@ -94,6 +104,10 @@ public class DoctorDoorServiceAuditController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 参数:
     * id=9e1204850bf4437e8ebf2c182db34f0e
     */
    @RequestMapping(value = "getPOnsiteServiceById", method = RequestMethod.GET)
    @ApiOperation(value = "获取居民上门服务资质申请详情")
    public Envelop getPOnsiteServiceById(
@ -142,14 +156,25 @@ public class DoctorDoorServiceAuditController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 代审核
     * 参数:
     * {
     * "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) {
            @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();
            }

File diff suppressed because it is too large
+ 197 - 126
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());
        }
    }
}

+ 81 - 58
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.hospital.module.door.service.DoorOrderService;
import com.yihu.jw.hospital.module.door.service.WlyyDoorPrescriptionService;
import com.yihu.jw.hospital.module.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
@ -15,6 +16,7 @@ import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
@ -30,7 +32,8 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private DoorOrderService doorOrderService;
@ -56,19 +59,56 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "create")
    @ApiOperation(value = "创建上门服务咨询")
    public Envelop create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        JSONObject result = new JSONObject();
        try {
            result = wlyyDoorServiceOrderService.create(jsonData);
            jsonData = URLDecoder.decode(jsonData, "UTF-8");
            JSONObject result = wlyyDoorServiceOrderService.create(jsonData);
            return success(result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    /**
     * 居民端 上门服务预约工单的状态分组统计数量
     * 参数:patient: 0fab4dd67e074e16ac86db6b6c15233e
     */
    @GetMapping(value = "queryInfoStatusCountList")
    @ApiOperation(value = "统计上门服务工单各状态下的数量列表")
    public Envelop queryInfoStatusCountList(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patient
    ) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoStatusCountList(patient);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "查询预约咨询记录列表")
    public PageEnvelop page(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "status", value = "工单状态,状态为全部时不传") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size
    ) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoList(patient, status, page, size);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
        }
        int count = result.getIntValue(ResponseContant.count);
        return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "queryOne")
    @ApiOperation(value = "查询单个咨询工单详情")
    public ObjEnvelop queryOneDetail(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        return success(wlyyDoorServiceOrderService.queryOneDetail(id));
    }
    @PostMapping(value = "qucikSendIM")
    @ApiOperation(value = "通过IM向客户端推送消息")
@ -79,13 +119,13 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
            @ApiParam(name = "contentType", value = "消息内容类型:1-文本信息,19-服务工单格式化消息", required = true) @RequestParam String contentType,
            @ApiParam(name = "content", value = "消息内容json", required = true) @RequestParam String content
    ) {
        int result = wlyyDoorServiceOrderService.qucikSendIM(orderId, sendId, sendName, contentType, content);
        if (result == -1) {
            return failed("发送失败!");
        try {
            int result = wlyyDoorServiceOrderService.qucikSendIM(orderId, sendId, sendName, contentType, content);
            return success("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed("发送失败! " + e.getMessage());
        }
        return success("发送成功");
    }
@ -111,40 +151,17 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
    @GetMapping(value = "queryDispatcherInfoByPatient")
    @ApiOperation(value = "获取居民所签约的机构的调度员信息")
    public Envelop queryDispatcherInfoByPatient(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
        JSONObject result = wlyyDoorServiceOrderService.queryDispatcherInfoByPatient(patient);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
            @ApiParam(name = "hospitalCode", value = "机构code") @RequestParam(value = "hospitalCode", required = true) String hospitalCode) {
        try {
            List<Map<String, Object>> list = wlyyDoorServiceOrderService.queryDispatcherInfoByPatient(hospitalCode);
            return success("查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
        int count = result.getIntValue(ResponseContant.count);
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "infoList")
    @ApiOperation(value = "查询预约咨询记录")
    public PageEnvelop page(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "status", value = "工单状态,状态为全部时不传") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoList(patient, status, page, size);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
        }
        int count = result.getIntValue(ResponseContant.count);
        return success((List) result.get(ResponseContant.resultMsg), count, page, size);
    }
    @GetMapping(value = "queryInfoStatusCountList")
    @ApiOperation(value = "统计上门服务工单各状态下的数量列表")
    public Envelop queryInfoStatusCountList(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = false) String patient) {
        JSONObject result = wlyyDoorServiceOrderService.queryInfoStatusCountList(patient);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "list")
    @ApiOperation(value = "获取列表")
@ -162,12 +179,6 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
        return success(result);
    }
    @GetMapping(value = "queryOne")
    @ApiOperation(value = "查询单个咨询工单详情")
    public ObjEnvelop queryOneDetail(
            @ApiParam(name = "id", value = "工单id") @RequestParam(value = "id", required = true) String id) {
        return success(wlyyDoorServiceOrderService.queryOneDetail(id));
    }
    @GetMapping(value = "twoDimensionalCode")
    @ApiOperation(value = "生成二维码接口")
@ -178,10 +189,15 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
//        }else {
//            return failed("获取二维码失败,请确认工单",-1);
//        }
        if (wlyyDoorServiceOrderService.twoDimensionalCode(id, null) != null) {
            return success("获取二维码成功", 200, wlyyDoorServiceOrderService.twoDimensionalCode(id, null));
        } else {
            return failed("获取二维码失败,请确认工单", -1);
        try {
            if (wlyyDoorServiceOrderService.twoDimensionalCode(id, null) != null) {
                return success("获取二维码成功", 200, wlyyDoorServiceOrderService.twoDimensionalCode(id, null));
            } else {
                return failed("获取二维码失败,请确认工单", -1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
@ -228,11 +244,15 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
    @ApiOperation(value = "更新预约简要信息")
    public Envelop updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return failed(result.getString(ResponseContant.resultMsg));
        try {
            JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
            return success("更新成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryOneConclusion")
@ -249,6 +269,7 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
            @ApiParam(name = "reason", value = "取消理由") @RequestParam(value = "reason", required = true) String reason) {
        JSONObject result = new JSONObject();
        try {
            System.out.println("取消工单--参数orderId:" + orderId);
            result = wlyyDoorServiceOrderService.cancelOrder(orderId, 2, reason, null, null);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
@ -259,10 +280,9 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
        }
        return success(result.get(ResponseContant.resultMsg));
    }
    @GetMapping(value = "queryDoctorList")
    @ApiOperation(value = "服务人员列表(医生列表)")
    public PageEnvelop queryDoctorList(
@ -270,9 +290,12 @@ public class WlyyDoorServiceOrderController extends EnvelopRestEndpoint {
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName") String doctorName,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) {
        JSONObject result = wlyyDoorServiceOrderService.queryDoctorList(getUID(), hospital, doctorName, null, page, size);
        if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
            return PageEnvelop.getError(result.getString(ResponseContant.resultMsg), -1);
        JSONObject result = null;
        try {
            result = wlyyDoorServiceOrderService.queryDoctorList(getUID(), hospital, doctorName, null, page, size);
        } catch (Exception e) {
            e.printStackTrace();
            return PageEnvelop.getError(e.getMessage());
        }
        int count = result.getIntValue(ResponseContant.count);
        return success((List) result.get(ResponseContant.resultMsg), count, page, size);

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

@ -0,0 +1,27 @@
package com.yihu.jw.hospital.module.door.dao;
import com.yihu.jw.entity.base.servicePackage.ServiceItemPlanDO;
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 yeshijie on 2023/10/28.
 */
public interface ServiceItemPlanDao extends PagingAndSortingRepository<ServiceItemPlanDO, String>, JpaSpecificationExecutor<ServiceItemPlanDO> {
    @Query("from ServiceItemPlanDO w where w.signId =?1 ")
    List<ServiceItemPlanDO> findBySignId(String signId);
    @Query(value = "select * from base_service_item_plan w where w.sign_id =?1 and w.service_item_id=?2 order by w.plan_time desc", nativeQuery = true)
    List<ServiceItemPlanDO> findBySignIdAndServiceItemId(String signId, String serviceItemId);
    @Modifying
    @Query(value ="UPDATE  base_service_item_plan SET status='1' ,complete_time=?3 WHERE status='0' AND sign_id=?1 AND service_pack_id=?2 ORDER BY plan_time DESC LIMIT 1", nativeQuery = true)
    void updateState(String signId, String packageId, Date date);
}

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

@ -2,7 +2,9 @@ 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;
/**
@ -18,4 +20,6 @@ import org.springframework.data.repository.PagingAndSortingRepository;
 * @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);
}

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

@ -1,5 +1,6 @@
package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -8,22 +9,25 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSubItemDO;
import com.yihu.jw.entity.base.system.SystemDictDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.door.*;
import com.yihu.jw.entity.ehr.dict.SystemDict;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.door.dao.*;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
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.web.PageEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.collections.CollectionUtils;
@ -43,6 +47,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.lang.Boolean;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@ -62,9 +67,9 @@ public class DoorOrderService {
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Value("${sign.check_upload}")
    //    @Value("${sign.check_upload}")
    private String jwUrl;
    @Value("${server.server_url}")
    //    @Value("${server.server_url}")
    private String wxServerUrl;
    //图片服务地址
    @Value("${fastDFS.fastdfs_file_url}")
@ -117,8 +122,8 @@ public class DoorOrderService {
    private ConsultDao consultDao;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
//    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    //    @Autowired
//    private HttpUtil httpUtil;
    @Autowired
    private WlyyDoorCommentDao doorCommentDao;
@ -128,13 +133,53 @@ public class DoorOrderService {
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private ServerPackageItemPatientDao serverPackageItemPatientDao;
//    @Autowired
//    private DmJobService dmJobService;
    @Autowired
    BasePatientDao basePatientDao;
    @Autowired
    ServiceItemPlanDao serviceItemPlanDao;
    /**
     * 服务项查询
     *
     * @param signId 签约id
     * @param type   doorService 上门服务
     */
    public PageEnvelop getServiceItem(String signId, String name, String type, Integer page, Integer size) {
//        String sql = "SELECT si.* ";
//        String countSql = "select count(si.id) ";
//        String filter = " from base_service_package_sign_record r," +
//                "base_service_package_item i,base_service_package_sub_item si,base_service_package_item_relational ir " +
//                "WHERE r.id = '"+signId+"' and i.service_package_id=r.service_package_id and i.`code`='"+type+"' and si.status='1' " +
//                " and i.id = ir.item_id and ir.sub_item_id= si.id ";
//        if(StringUtils.isNotBlank(name)){
//            filter += " and si.name like '%"+name+"%' ";
//        }
//        String oderBy = " order by si.sort limit "+(page-1)*size+","+size;
        String sql = "SELECT e.* ";
        String countSql = "select count(e.id) ";
        String filter =
                "FROM\n" +
                        "	base_service_package_sign_record a \n" +
                        "	INNER JOIN base_service_package_item b ON a.service_package_id = b.service_package_id\n" +
                        "	INNER JOIN base_service_package_item c ON c.id=b.service_package_item_id\n" +
                        "	INNER JOIN base_service_package_item_relational d ON d.item_id=c.id \n" +
                        "	INNER JOIN base_service_package_sub_item e ON e.id=d.sub_item_id\n" +
                        "WHERE 1=1\n" +
                        "	AND b.`code` = '" + type + "' \n" +
                        "	AND e.`status` = '1' \n" +
                        "	AND a.id = '" + signId + "' ";
        if (StringUtils.isNotBlank(name)) {
            filter += " and e.name like '%" + name + "%' ";
        }
        String oderBy = " order by e.sort limit " + (page - 1) * size + "," + size;
        sql = sql + filter + oderBy;
        countSql = countSql + filter;
        List<ServicePackageSubItemDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ServicePackageSubItemDO.class));
        long count = jdbcTemplate.queryForObject(countSql, Long.class);
        return PageEnvelop.getSuccessListWithPage("", list, page, size, count);
    }
    public Map<String, String> getNumGroupByStatusTeam(String doctor, Integer type) {
        String sql = "SELECT a.status, COUNT(DISTINCT a.id) as num FROM wlyy_door_service_order a ";
@ -360,7 +405,8 @@ public class DoorOrderService {
     * @return
     */
    public List<Map<String, Object>> getDoorFeeDetailGroupByStatus(String orderId) {
        String sql = "SELECT d.id, d.status,d.name,d.code,sum(d.number) num,fee,sum(d.number)*fee sum from wlyy_door_fee_detail d where order_id=? and type=1 GROUP BY status,code";
        String sql = "SELECT d.id, d.status,d.name,d.code,sum(d.number) num,fee,sum(d.number)*fee sum " +
                " from wlyy_door_fee_detail d where order_id=? and type=1 GROUP BY status,code";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, orderId);
        return list;
    }
@ -372,7 +418,8 @@ public class DoorOrderService {
     * @return
     */
    public List<Map<String, Object>> getDoorServiceDoctor(String orderId) {
        String sql = "SELECT dd.id as id,CONCAT(d.`name`,' (',dd.doctor_job_name,')') as name, dd.doctor from wlyy_door_doctor dd join wlyy_doctor d on d.`code` = dd.doctor WHERE order_id=?";
        String sql = "SELECT dd.id as id,CONCAT(d.`name`,' (',dd.doctor_job_name,')') as name, " +
                "dd.doctor from wlyy_door_doctor dd join base_doctor d on d.`id` = dd.doctor WHERE order_id=?";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, orderId);
        return mapList;
    }
@ -384,7 +431,7 @@ public class DoorOrderService {
     * @return
     */
    public WlyyDoorServiceOrderDO getDoorServiceOrderById(String id, Integer level) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findById(null).orElse(null);
        WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findById(id).orElse(null);
        if (null == doorServiceOrder) {
            return null;
        }
@ -396,7 +443,7 @@ public class DoorOrderService {
            doorServiceOrder.setAge(age);
            doorServiceOrder.setPhoto(patient.getPhoto());
//            String typeValues = this.getTypeValueByPatientCode(patient.getCode());
           String typeValues = this.getTypeValueByPatientCode(patient.getId());
            String typeValues = this.getTypeValueByPatientCode(patient.getId());
            doorServiceOrder.setTypeValue(typeValues);
        }
        // 获取服务次数
@ -404,7 +451,7 @@ public class DoorOrderService {
        Integer times = wlyyDoorServiceOrderService.countPatientDoorTimes(doorServiceOrder.getPatient());
        //先注释-服务费用20231011
//        List<WlyyDoorDoctorDO> djDetailList = this.djDetailList(id, level, times);
//        doorServiceOrder.setDjDetailList(djDetailList);
//       doorServiceOrder.setDjDetailList(djDetailList);//出诊费
        List<Map<String, Object>> feeDetailDOS = this.getDoorFeeDetailGroupByStatus(id);
        String jsonData = this.serverPackagePriceByOrderId(id);
        if (null != feeDetailDOS && feeDetailDOS.size() > 0) {
@ -413,7 +460,7 @@ public class DoorOrderService {
            //计算扣服务包后应付的服务项费用
            /*Map<String, Object> map = this.countServerPackagePrice(jsonData, doorServiceOrder.getPatient());
            BigDecimal cashPrice = this.calculateCash(String.valueOf(map.get("cashPrice")), id, level, times);
            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = this.doorServiceOrderDao.findById(null).orElse(null);
            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = this.doorServiceOrderDao.findById(null);
            if(wlyyDoorServiceOrderDO.getTotalFee()!=cashPrice){
                wlyyDoorServiceOrderDO.setTotalFee(cashPrice);
                wlyyDoorServiceOrderService.save(wlyyDoorServiceOrderDO);
@ -427,12 +474,12 @@ public class DoorOrderService {
        if (null != doorServiceDoctors && doorServiceDoctors.size() > 0) {
            doorServiceOrder.setDoctors(doorServiceDoctors);
        }
        System.out.println("准备获取咨询==>参数:" + id);
        //获取咨询
        ConsultDo consult = consultDao.queryByRelationCode(id);
        System.out.println("consult==>" + JSON.toJSONString(consult));
        if (null != consult) {
            doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getCode() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
            doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getId() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
        }
        // 设置服务小结
@ -442,7 +489,7 @@ public class DoorOrderService {
        }
        doorConclusion.setServiceCount(count);
        doorServiceOrder.setDoorConclusion(doorConclusion);
        System.out.println("获取上门前后开方详情");
        //获取上门前后开方详情
        List<WlyyDoorPrescriptionDO> doorBeforePrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 1);
        List<WlyyDoorPrescriptionDO> doorAfterPrescriptionDOList = doorPrescriptionDao.findByOrderIdAndIsAfterDoor(id, 2);
@ -522,32 +569,37 @@ public class DoorOrderService {
     * @throws Exception
     */
    public WlyyDoorConclusionDO updateDoorConclusion(String model, Integer examPapeStatus) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        WlyyDoorConclusionDO doorConclusion = objectMapper.readValue(model, WlyyDoorConclusionDO.class);
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findById(doorConclusion.getOrderId()).orElse(null);
        BaseDoctorDO doctorVO = doctorDao.findById(one.getDoctor()).orElse(null);
        if (doorConclusion != null && StringUtils.isNotEmpty(doorConclusion.getId())) {
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setUpdateUser(one.getDoctor());
            doorConclusion.setUpdateUserName(null != doctorVO ? doctorVO.getName() : null);
        } else {
            doorConclusion.setCreateTime(new Date());
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setCreateUser(one.getDoctor());
            doorConclusion.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
            WlyyDoorConclusionDO doorConclusion = objectMapper.readValue(model, WlyyDoorConclusionDO.class);
            WlyyDoorServiceOrderDO one = doorServiceOrderDao.findById(doorConclusion.getOrderId()).orElse(null);
            BaseDoctorDO doctorVO = doctorDao.findById(one.getDoctor()).orElse(null);
            if (doorConclusion != null && StringUtils.isNotEmpty(doorConclusion.getId())) {
                doorConclusion.setUpdateTime(new Date());
                doorConclusion.setUpdateUser(one.getDoctor());
                doorConclusion.setUpdateUserName(null != doctorVO ? doctorVO.getName() : null);
            } else {
                doorConclusion.setCreateTime(new Date());
                doorConclusion.setUpdateTime(new Date());
                doorConclusion.setCreateUser(one.getDoctor());
                doorConclusion.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
            }
        //服务时间 为空的 默认使用医生签到时间 1.7.0.5修改
        if (null == doorConclusion.getServiceTime() || StringUtils.isBlank(doorConclusion.getServiceTime().toString())) {
            doorConclusion.setServiceTime(one.getDoctorSignTime());
            //服务时间 为空的 默认使用医生签到时间 1.7.0.5修改
            if (null == doorConclusion.getServiceTime() || StringUtils.isBlank(doorConclusion.getServiceTime().toString())) {
                doorConclusion.setServiceTime(one.getDoctorSignTime());
            }
            doorConclusionDao.save(doorConclusion);
            // 设置是否需要上传补录报告
            one.setExamPaperStatus(examPapeStatus);
            one.setConclusionStatus(2);
            doorServiceOrderDao.save(one);
            return doorConclusion;
        } catch (IOException e) {
            e.printStackTrace();
        }
        doorConclusionDao.save(doorConclusion);
        // 设置是否需要上传补录报告
        one.setExamPaperStatus(examPapeStatus);
        one.setConclusionStatus(2);
        doorServiceOrderDao.save(one);
        return doorConclusion;
        return null;
    }
    public WlyyDoorServiceOrderDO acceptOrder1(String orderId, String jobCode, String jobCodeName, int hospitalLevel) throws Exception {
@ -575,11 +627,9 @@ public class DoorOrderService {
        if (wlyyDoorServiceOrderService.orderWithDoctorAdd(new JSONObject(), jsonObjectParam, doorServiceOrder)) {
            return null;
        }
        doorServiceOrderDao.save(doorServiceOrder);
        this.systemMessageDao.orderMessageDel(doorServiceOrder.getDoctor(), orderId);
        //删除407的消息
        systemMessageDao.orderMessageDel(doorServiceOrder.getDoctor(), orderId);
        if (doorServiceOrder.getType() == null || doorServiceOrder.getType() != 3) {
            //获取咨询
@ -592,14 +642,13 @@ public class DoorOrderService {
            //成功创建服务工单后,居民所在机构调度员向居民发起一条通知服务消息
            // 发送IM消息通知患者医生已接单
            String noticeContent = "我已接受您的服务工单预约," + doorServiceOrder.getDoctorName() + "医生正在为您服务!";
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "1", noticeContent);
            String noticeContent = "已接受您的服务工单预约," + doorServiceOrder.getDoctorName() + "医生正在为您服务!";
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDoctor(), "智能助手", "1", noticeContent);
            // 发送居民上门服务简要信息
            JSONObject orderInfoContent = wlyyDoorServiceOrderService.queryOrderCardInfo(doorServiceOrder);
            orderInfoContent.put("re_msg_type", 0);
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDoctor(), "智能助手", "2101", orderInfoContent.toJSONString());
        }
        return doorServiceOrder;
    }
@ -609,18 +658,18 @@ public class DoorOrderService {
     * @param orderId
     */
    public void acceptOrder(String orderId, String jobCode, String jobCodeName, int hospitalLevel) throws Exception {
        //接单和发送消息
        WlyyDoorServiceOrderDO doorServiceOrder = acceptOrder1(orderId, jobCode, jobCodeName, hospitalLevel);
        if (doorServiceOrder == null) {
            return;
        }
        
        // 发送微信模板消息通知患者医生已接单
        BasePatientDO patient = patientService.findPatientById(doorServiceOrder.getPatient());
        // 获取微信模板
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "smyyyjjd");
            WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene("xm_test_ihealth_wx", "template_process_feedback", "smyyyjjd");
            String first = templateConfig.getFirst();
            first = first.replace("key1", (patient.getName() == null ? "" : patient.getName()));
            first = first.replace("key2", null != doorServiceOrder.getDoctorName() ? doorServiceOrder.getDoctorName() : "");
@ -632,7 +681,7 @@ public class DoorOrderService {
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            if (consult != null) {
                json.put("consult", consult.getCode());
                json.put("consult", consult.getId());
            }
            logger.info("上门服务已接单推送前");
            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
@ -641,7 +690,7 @@ public class DoorOrderService {
            logger.error(e.getMessage());
        }
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678 ----407在上门已经删除了,这快代码其实没啥用
        List<SystemMessageDO> messages = systemMessageDao.queryByRelationCodeAndTypeIn(orderId, new String[]{"403", "407"});
        if (CollectionUtils.isEmpty(messages)) {
            logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
@ -666,10 +715,6 @@ public class DoorOrderService {
    /**
     * 拒单
     *
     * @param orderId
     * @param reason
     * @throws Exception
     */
    public void refuseOrder(String receiver, String orderId, String reason) throws Exception {
        WlyyDoorServiceOrderDO doorServiceOrder = doorServiceOrderDao.findById(orderId).orElse(null);
@ -681,16 +726,18 @@ public class DoorOrderService {
//            this.createMessage(doorServiceOrder.getId(), "system", doorServiceOrder.getProxyPatient(), 403, "代预约服务工单重新派单", doorServiceOrder.getPatientName() + "的代预约服务工单需重新派单,请您前往处理");
            //2021-12-29 代预约医生拒单直接取消
            doorServiceOrder.setStatus(WlyyDoorServiceOrderDO.Status.cancel.getType());
            doorServiceOrder.setCancelReason(reason);   // 拒绝原因
            doorServiceOrder.setCancelReason(reason);// 拒绝原因
            doorServiceOrder.setCancelTime(new Date());
            doorServiceOrderDao.save(doorServiceOrder);
        } else {
            //删除消息
            this.systemMessageDao.orderMessageDel(doorServiceOrder.getDoctor(), orderId);
            //有调度员
            if (StringUtils.isNotBlank(doorServiceOrder.getDispatcher())) {
                // 派单消息
                this.createMessage(doorServiceOrder.getId(), "system", doorServiceOrder.getDispatcher(), 404, "服务工单拒单待重新派单", doorServiceOrder.getDoctorName() + "拒绝了" + doorServiceOrder.getProxyPatientName() + "的服务预约申请,请重新派单");
                //  调度员-派单-实时工单消息:435 医生拒单-- 王五拒绝了服务工单12345678
                // 调度员-派单-实时工单消息:435 医生拒单-- 王五拒绝了服务工单12345678
                List<SystemMessageDO> messages = systemMessageDao.queryByRelationCodeAndTypeIn(orderId, new String[]{"431", "433"});
                if (CollectionUtils.isEmpty(messages)) {
                    logger.error("当前工单没有医生待接单消息!orderId:" + orderId);
@ -710,19 +757,12 @@ public class DoorOrderService {
            doorServiceOrder.setStatus(WlyyDoorServiceOrderDO.Status.waitForSend.getType());  // 设置为1-待(调度员)派单
            doorServiceOrder.setCancelReason(reason);   // 拒绝原因
            doorServiceOrder.setCancelTime(new Date());
//        doorServiceOrder.setCancelType(WlyyDoorServiceOrderDO.CancelType.dispatcher.getType());
            doorServiceOrderDao.save(doorServiceOrder);
        }
    }
    /**
     * 添加【工单派单,转单】等系统消息
     *
     * @param orderId
     * @param sender
     * @param receiver
     * @param Content
     */
    public void createMessage(String orderId, String sender, String receiver, int type, String title, String Content) {
        SystemMessageDO message = new SystemMessageDO();
@ -855,7 +895,7 @@ public class DoorOrderService {
            object.put("feeDetailResultList", feeDetailResultList);
            // 获取或者基本信息
            
            BasePatientDO patient = patientService.findPatientById(String.valueOf(one.get("patientCode")));
            if (patient != null) {
                String sex = IdCardUtil.getSexForIdcard(patient.getIdcard());
@ -868,11 +908,11 @@ public class DoorOrderService {
                object.put("typeValue", typeValues);
            }
            String id = one.get("orderId").toString();
            WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findById(null).orElse(null);
            WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findById(id).orElse(null);
            //获取咨询
            ConsultDo consult = consultDao.queryByRelationCode(id);
            if (null != consult) {
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getCode() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getId() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
            }
            object.put("sessionId", doorServiceOrder.getSessionId());
@ -914,23 +954,26 @@ public class DoorOrderService {
    public JSONObject getDoorOrderList(String orderId, String patientName, String patientPhone, String hospitalCode,
                                       StringBuffer status, String createTimeStart, String createTimeEnd, String serverDoctorName,
                                       String doctorCode, Integer examPaperStatus, Integer page, Integer pageSize, Integer type, String name, String serverType) throws Exception {
        StringBuilder sqlList = new StringBuilder("select DISTINCT o.id as orderId,o.status,f.hospital,f.hospital_name as hospitalName1,o.is_trans_other_org,o.transed_org_code,h.name as hospitalName2,o.patient_name," +
                " o.patient_phone,o.remark,o.serve_desc,dc.service_time,o.patient as patientCode ,o.exam_paper_status as examPaperStatus,o.number as serverCode,o.total_fee,h.hos_level as hosLevel, " +
                "o.doctor, o.doctor_name as doctorName, o.doctor_type as doctorType ,(SELECT group_concat(DISTINCT dsv.type_value) FROM wlyy_door_service_voucher dsv WHERE dsv.patient_code = o.patient and dsv.status=1 ) AS serviceStatus ");
        StringBuilder sqlList = new StringBuilder(
                "select DISTINCT o.id as orderId,o.status," +
//                        "h.org_name AS hospitalName, " +//这个会重复
                        " h.org_code AS hospital," +
                        "o.is_trans_other_org,o.transed_org_code ,o.patient_name," +
                        " o.patient_phone,o.remark,o.serve_desc,dc.service_time,o.patient as patientCode ," +
                        "o.exam_paper_status as examPaperStatus,o.number as serverCode,o.total_fee, " +
                        " o.doctor, o.doctor_name as doctorName, o.doctor_type as doctorType ," +
                        "(SELECT group_concat(DISTINCT dsv.type_value) " +
                        " FROM wlyy_door_service_voucher dsv WHERE dsv.patient_code = o.patient and dsv.status=1 ) AS serviceStatus ");
        StringBuilder sqlCount = new StringBuilder(" select count(DISTINCT o.id) as total ");
        StringBuilder sql = new StringBuilder(" from wlyy_door_service_order o " +
                " LEFT JOIN wlyy_sign_family f ON f.patient = o.patient AND f.STATUS = 1 AND f.expenses_status = 1 " +
                " LEFT JOIN dm_hospital h on h.code=o.hospital and h.del=1 "
                " LEFT JOIN base_doctor_hospital h ON o.hospital=h.org_code "
                + " LEFT JOIN wlyy_door_doctor d on d.order_id = o.id " +
                " LEFT JOIN wlyy_patient p on p.code = o.patient " +
                " LEFT JOIN base_patient p on p.id = o.patient " +
                " LEFT JOIN wlyy_door_conclusion dc ON dc.order_id = o.id ");
        if (StringUtils.isNotBlank(serverType)) {
            sql.append(" INNER JOIN wlyy_door_service_voucher dsv on dsv.patient_code = o.patient and dsv.type='" + serverType + "' and dsv.status=1 ");
        }
//        if(!StringUtils.isEmpty(serverDoctorName)){
//            sql+=" RIGHT JOIN wlyy_door_doctor d on d.order_id = o.id";
//        }
        sql.append(" where 1=1 ");
        if (!StringUtils.isEmpty(orderId)) {
            sql.append(" and o.number = '" + orderId + "'");
@ -950,9 +993,7 @@ public class DoorOrderService {
        if (status != null) {
            sql.append(" and o.status in (" + status + ")");
        }
        /*else {
            sql += " and o.status != '-1' ";
        }*/
        if (!StringUtils.isEmpty(createTimeStart)) {
            sql.append(" and dc.service_time >='" + createTimeStart + "'");
        }
@ -971,8 +1012,12 @@ public class DoorOrderService {
        if (examPaperStatus != null) {
            sql.append(" and o.conclusion_status='" + examPaperStatus + "' ");
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlCount.append(sql).toString());
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlList.append(sql).append(" order by o.create_time desc LIMIT " + (page - 1) * pageSize + "," + pageSize).toString());
        String sql01 = sqlList.append(sql).append(" order by o.create_time desc LIMIT " + (page - 1) * pageSize + "," + pageSize).toString();
        String sql02 = sqlCount.append(sql).toString();
        System.out.println("getDoorOrderList----sql01==>" + sql01);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql01);
        System.out.println("工单的数量list==>" + list.size());
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql02);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
@ -1068,11 +1113,11 @@ public class DoorOrderService {
                object.put("typeValue", typeValues);
            }
            String id = one.get("orderId").toString();
            WlyyDoorServiceOrderDO doorServiceOrder = this.doorServiceOrderDao.findById(null).orElse(null);
            WlyyDoorServiceOrderDO doorServiceOrder = doorServiceOrderDao.findById(id).orElse(null);
            //获取咨询
            ConsultDo consult = consultDao.queryByRelationCode(id);
            if (null != consult) {
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getCode() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
                doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getId() + "_" + doorServiceOrder.getNumber() + "_" + consult.getType());
            }
            object.put("sessionId", doorServiceOrder.getSessionId());
@ -1351,6 +1396,14 @@ public class DoorOrderService {
//        BigDecimal cashPrice = this.calculateCash(String.valueOf(map.get("cashPrice")), orderId, level, times);
//        one.setTotalFee(cashPrice);
        doorServiceOrderDao.save(one);
        //
        String signId = one.getSignId();//签约id
        String packageId = one.getPackageId();//服务包id
        Date date = new Date();
        //更新计划状态为完成
        serviceItemPlanDao.updateState(signId, packageId, date);
        WlyyDoorServiceOrderDO doorServiceOrderDO = this.getDoorServiceOrderById(orderId, level);
        // 发送微信通知  待付款
@ -1358,41 +1411,29 @@ public class DoorOrderService {
        // 获取微信模板 smfwdwk-上门服务待付款
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        try {
            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "fwyspf");
            String first = templateConfig.getFirst();
            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
            first = first.replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "服务医生评分");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            json.put("id", orderId);
            //json.put("consult",consult.getCode());
            WlyyDoorCommentDO wlyyDoorCommentDO = this.doorCommentDao.selectCommentDoctor(patient.getId(), orderId);
            String finish = "";
            if (wlyyDoorCommentDO != null) {
                finish = "0";
                json.put("finish", finish);
            } else {
                finish = "1";
                json.put("finish", finish);
            }
            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 31, patient.getOpenid(), patient.getName(), json);
            /*WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","smfwdwk");
            String first = templateConfig.getFirst();
            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
            first = first .replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
           // String keyword1 = templateConfig.getKeyword1();
            org.json.JSONObject json = new org.json.JSONObject();
            json.put("first", first);
            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
            json.put("keyword2", "上门服务待付款");
            json.put("url", templateConfig.getUrl());
            json.put("remark", templateConfig.getRemark());
            json.put("consult",consult.getCode());*/
//            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
//            //暂时没有微信模板消息的功能
//            WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene("xm_test_ihealth_wx", "template_process_feedback", "fwyspf");
//            String first = templateConfig.getFirst();
//            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
//            first = first.replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
//            org.json.JSONObject json = new org.json.JSONObject();
//            json.put("first", first);
//            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
//            json.put("keyword2", "服务医生评分");
//            json.put("url", templateConfig.getUrl());
//            json.put("remark", templateConfig.getRemark());
//            json.put("id", orderId);
//            //json.put("consult",consult.getCode());
//            WlyyDoorCommentDO wlyyDoorCommentDO = this.doorCommentDao.selectCommentDoctor(patient.getId(), orderId);
//            String finish = "";
//            if (wlyyDoorCommentDO != null) {
//                finish = "0";
//                json.put("finish", finish);
//            } else {
//                finish = "1";
//                json.put("finish", finish);
//            }
//            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 31, patient.getOpenid(), patient.getName(), json);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
@ -1427,7 +1468,7 @@ public class DoorOrderService {
     * @param level
     */
//    public WlyyDoorServiceOrderDO confirmReceipt(String orderId, Integer level) throws Exception {
//        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findById(orderId).orElse(null);
//        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findById(orderId);
//        one.setPayWay(WlyyDoorServiceOrderDO.PayWay.offLine.getType());    // 1-微信支付,2-线下支付(居民自己向医院支付,具体怎么支付由医院来定)
//        one.setPayTime(new Date());
//        one.setStatus(WlyyDoorServiceOrderDO.Status.waitForCommnet.getType());   // 5-待评价
@ -1498,10 +1539,8 @@ public class DoorOrderService {
    /**
     * 修改预计到达时间
     *
     * @param orderId
     * @param arrivingTime
     * @return
     * orderId
     * arrivingTime
     */
    public WlyyDoorServiceOrderDO updateArrivingTime(String orderId, String arrivingTime) {
        WlyyDoorServiceOrderDO one = doorServiceOrderDao.findById(orderId).orElse(null);
@ -1619,56 +1658,59 @@ public class DoorOrderService {
    }
//    /**
//     * 根据服务项计算服务费用
//     *
//     * @param jsonData 格式[{"itemCode":"","fee":"","number":""}]
//     * @param patient  居民code
//     * @return
//     */
//    public Map<String, Object> countServerPackagePrice(String jsonData, String patient) {
//        Map<String, Object> map = new HashMap<>();
//        BigDecimal serverPackagePrice = new BigDecimal("0.00");
//        BigDecimal cashPrice = new BigDecimal("0.00");
//        //获取居民签约服务项及次数
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        String sql = "SELECT ip.service_item_code as itemCode, sum(ip.service_times) as times  FROM wlyy_server_package_patient pp , wlyy_server_package_item_patient ip " +
//                "where pp.`code` = ip.server_package_patient_code and  pp.patient = '" + patient + "' and pp.hospital = '" + signFamily.getHospital() + "' and pp.`status` = 1 " +
//                "GROUP BY ip.service_item_code ";
//        List<Map<String, Object>> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(String.class));
//
//        JSONArray jsonArray = JSONArray.parseArray(jsonData);
//        for (Object o : jsonArray) {
//            Boolean b = false;
//            BigDecimal times = null;
//            JSONObject jsonObject = (JSONObject) o;
//            String itemCode = jsonObject.getString("itemCode");
//            BigDecimal fee = jsonObject.getBigDecimal("fee");
//            BigDecimal number = jsonObject.getBigDecimal("number");
//            //遍历是否是居民签约的服务项,如果是,看还剩多少次数
//            for (Map<String, Object> m : list) {
//                if ((m.get(itemCode) + "").equals(itemCode)) {
//                    b = true;
//                    times = (BigDecimal) map.get("times");
//                }
//            }
//            //判断服务包里面的次数是否够抵扣,不够的仍需支付
//            if (b) {
//                if (times.compareTo(number) > -1) {
//                    serverPackagePrice = serverPackagePrice.add(fee.multiply(number));
//                } else {
//                    //还需另外支付次数
//                    BigDecimal t = number.subtract(times);
//                    cashPrice = cashPrice.add(fee.multiply(t));
//                }
//            } else {
//                cashPrice = cashPrice.add(fee.multiply(number));
//            }
//        }
//        map.put("serverPackagePrice", serverPackagePrice);
//        map.put("cashPrice", cashPrice);
//        return map;
//    }
    /**
     * 根据服务项计算服务费用
     *
     * @param jsonData 格式[{"itemCode":"","fee":"","number":""}]
     * @param patient  居民code
     * @return
     */
    public Map<String, Object> countServerPackagePrice(String jsonData, String patient) {
        Map<String, Object> map = new HashMap<>();
        BigDecimal serverPackagePrice = new BigDecimal("0.00");
        BigDecimal cashPrice = new BigDecimal("0.00");
        //获取居民签约服务项及次数
        String sql = "SELECT ip.service_item_code as itemCode, sum(ip.service_times) as times  " +
                "FROM wlyy_server_package_patient pp , wlyy_server_package_item_patient ip " +
                "where pp.`code` = ip.server_package_patient_code" +
                " and  pp.patient = '" + patient + "' " +
//                " and pp.hospital = '" + signFamily.getHospital() + "' " +
                " and pp.`status` = 1 " +
                "GROUP BY ip.service_item_code ";
        List<Map<String, Object>> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(String.class));
        JSONArray jsonArray = JSONArray.parseArray(jsonData);
        for (Object o : jsonArray) {
            Boolean b = false;
            BigDecimal times = null;
            JSONObject jsonObject = (JSONObject) o;
            String itemCode = jsonObject.getString("itemCode");
            BigDecimal fee = jsonObject.getBigDecimal("fee");
            BigDecimal number = jsonObject.getBigDecimal("number");
            //遍历是否是居民签约的服务项,如果是,看还剩多少次数
            for (Map<String, Object> m : list) {
                if ((m.get(itemCode) + "").equals(itemCode)) {
                    b = true;
                    times = (BigDecimal) map.get("times");
                }
            }
            //判断服务包里面的次数是否够抵扣,不够的仍需支付
            if (b) {
                if (times.compareTo(number) > -1) {
                    serverPackagePrice = serverPackagePrice.add(fee.multiply(number));
                } else {
                    //还需另外支付次数
                    BigDecimal t = number.subtract(times);
                    cashPrice = cashPrice.add(fee.multiply(t));
                }
            } else {
                cashPrice = cashPrice.add(fee.multiply(number));
            }
        }
        map.put("serverPackagePrice", serverPackagePrice);
        map.put("cashPrice", cashPrice);
        return map;
    }
//    /**
//     * 更新居民签约服务包服务项次数
@ -1715,7 +1757,8 @@ public class DoorOrderService {
     * @throws Exception
     */
    public String serverPackagePriceByOrderId(String orderId) throws Exception {
        String sql = "SELECT d.code itemCode,sum(d.number) number,fee from wlyy_door_fee_detail d where order_id=? and d.status in(1,2) and type=1 GROUP BY code";
        String sql = "SELECT d.code itemCode,sum(d.number) number,fee " +
                "from wlyy_door_fee_detail d where order_id=? and d.status in(1,2) and type=1 GROUP BY code";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql, orderId);
        return objectMapper.writeValueAsString(mapList);
    }
@ -1777,27 +1820,26 @@ public class DoorOrderService {
        return typeValues;
    }
//    /**
//     * 修改保存服务项
//     *
//     * @param jsonData
//     */
//    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
//    public void updatePackageItemInfo(String jsonData) {
//        JSONObject jsonObjectParam = JSONObject.parseObject(jsonData);
//        String orderId = String.valueOf(jsonObjectParam.get("orderId"));
//        WlyyDoorServiceOrderDO order = doorServiceOrderDao.findById(orderId);
//        // 删除出诊医生或服务项
//        wlyyDoorServiceOrderService.orderWithFeeDelete(jsonObjectParam, order);
//        // 更新服务包信息
//        wlyyDoorServiceOrderService.orderWithPackageItemFeeAdd(new JSONObject(), jsonObjectParam, order);
//
//        // 发送微信模板消息,通知居民服务项目已经变更(smyyyjjd-服务项目变更通知)
//        BasePatientDO patient = patientService.findByCode(order.getProxyPatient());
//        ConsultDo consult = consultDao.queryByRelationCode(orderId);
//        Integer status = 0;
//        try {
//
    /**
     * 修改保存服务项
     *
     * @param jsonData
     */
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public void updatePackageItemInfo(String jsonData) throws Exception {
        JSONObject jsonObjectParam = JSONObject.parseObject(jsonData);
        String orderId = String.valueOf(jsonObjectParam.get("orderId"));
        WlyyDoorServiceOrderDO order = doorServiceOrderDao.findById(orderId).orElse(null);
        // 删除出诊医生或服务项
        wlyyDoorServiceOrderService.orderWithFeeDelete(jsonObjectParam, order);
        // 更新服务包信息
        wlyyDoorServiceOrderService.orderWithPackageItemFeeAdd(new JSONObject(), jsonObjectParam, order);
        // 发送微信模板消息,通知居民服务项目已经变更(smyyyjjd-服务项目变更通知)
        BasePatientDO patient = basePatientDao.findById(order.getProxyPatient()).orElse(null);
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        Integer status = 0;
        try {
//            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "fwxmbgtz");
//            String first = templateConfig.getFirst();
//            first = first.replace("key1", (patient.getName() == null ? "" : patient.getName()));
@ -1809,14 +1851,14 @@ public class DoorOrderService {
//            json.put("keyword2", "服务项目变更确认");
//            json.put("url", templateConfig.getUrl());
//            json.put("remark", templateConfig.getRemark());
//            json.put("consult", consult.getCode());
//            json.put("consult", consult.getId());
//            json.put("status", status);
////            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 32, patient.getOpenid(), patient.getName(), json);
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//        }
//
//    }
//            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 32, patient.getOpenid(), patient.getName(), json);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
    /**
     * 获取管理员端上门服务菜单分类
@ -2019,9 +2061,9 @@ public class DoorOrderService {
        if (org.apache.commons.lang3.StringUtils.isBlank(sendId)) {
            wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
            response = imUtill.sendTopicIM(wlyyDoorServiceOrder.getDispatcher(), "智能助手", consult.getCode(), contentType, content, null);
            response = imUtill.sendTopicIM(wlyyDoorServiceOrder.getDispatcher(), "智能助手", consult.getId(), contentType, content, null);
        } else {
            response = imUtill.sendTopicIM(sendId, sendName, consult.getCode(), contentType, content, null);
            response = imUtill.sendTopicIM(sendId, sendName, consult.getId(), contentType, content, null);
        }
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getIntValue("status") == -1) {
@ -2418,9 +2460,9 @@ public class DoorOrderService {
    /**
     * 字典查询List
     */
    public List<SystemDict> getDictionaryList(String dictName) {
        String sql = "SELECT * FROM system_dict WHERE dict_name = '" + dictName + "' ";
        List<SystemDict> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SystemDict.class));
    public List<SystemDictDO> getDictionaryList(String dictName) {
        String sql = "SELECT * FROM base_system_dict WHERE dict_name = '" + dictName + "' ";
        List<SystemDictDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SystemDictDO.class));
        return list;
    }

+ 27 - 7
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorServiceApplicationService.java

@ -362,13 +362,33 @@ public class DoorServiceApplicationService {
     * @return
     */
    public List<Map<String, Object>> findDispatcherByPatient(String patient) throws Exception {
        String sql = "SELECT d.code,d.name FROM " +
                " manage_role_user ru LEFT JOIN " +
                " manage_roles r  ON ru.role_id=r.id " +
                " LEFT JOIN (select d.code,d.name from wlyy.wlyy_doctor d LEFT JOIN wlyy.wlyy_sign_family a ON d.hospital=a.hospital  " +
                "                 where a.patient = '" + patient + "' and a.status > 0  " +
                "                 AND d.status=1 and d.del=1) d ON ru.user_code=d.code " +
                " WHERE r.code='dispatcher' AND d.`code` IS NOT NULL";
//        String sql = "SELECT d.code,d.name FROM " +
//                " manage_role_user ru LEFT JOIN " +
//                " manage_roles r  ON ru.role_id=r.id " +
//                " LEFT JOIN (select d.code,d.name from wlyy.wlyy_doctor d LEFT JOIN wlyy.wlyy_sign_family a ON d.hospital=a.hospital  " +
//                "                 where a.patient = '" + patient + "' and a.status > 0  " +
//                "                 AND d.status=1 and d.del=1) d ON ru.user_code=d.code " +
//                " WHERE r.code='dispatcher' AND d.`code` IS NOT NULL";
//
//        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        //第三医院是没有签约的这个动作的
        String sql = "SELECT\n" +
                "	a.doctor_code 'code',\n" +
                "	b.`name` 'name',\n" +
                "	a.org_code,\n" +
                "	a.org_name 'hospitalName',\n" +
                "	t.CODE AS roleCode,\n" +
                "	t.NAME AS roleName \n" +
                "FROM\n" +
                "	base_doctor_role r\n" +
                "	INNER JOIN base_doctor_role_dict t ON t.CODE = r.role_code\n" +
                "	INNER JOIN base_doctor_hospital a ON r.doctor_code = a.doctor_code\n" +
                "	INNER JOIN base_doctor b ON a.doctor_code = b.id \n" +
                "WHERE\n" +
                "	1 = 1 \n" +
                "	AND t.`code` = 'dispatcher' \n";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

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

@ -1,8 +1,18 @@
package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorCommentDO;
import com.yihu.jw.entity.door.WlyyDoorCommentDoctorDO;
import com.yihu.jw.entity.door.WlyyDoorDoctorDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.entity.message.WlyyDynamicMessages;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorCommentDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorCommentDoctorDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorDoctorDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.message.dao.WlyyDynamicMessagesDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
@ -14,7 +24,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
@ -28,7 +41,19 @@ public class WlyyDoorCommentService extends BaseJpaService<WlyyDoorCommentDO, Wl
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    WlyyDoorCommentDao doorCommentDao;
    @Autowired
    WlyyDoorCommentDoctorDao doorCommentDoctorDao;
    @Autowired
    WlyyDoorDoctorDao wlyyDoorDoctorDao;
    @Autowired
    BasePatientDao patientDao;
    @Autowired
    WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    WlyyDynamicMessagesDao dynamicMessagesDao;
    //服务工单评价服务基本信息
    private WlyyDoorCommentDO jsonToWlyyDoorComment(JSONObject result, JSONObject jsonObjectParam,String jsonData) {
@ -160,4 +185,81 @@ public class WlyyDoorCommentService extends BaseJpaService<WlyyDoorCommentDO, Wl
    return result;
    }
    public String add(String patientCode,String orderId, Integer professionalSkill,Integer serveAttitude,Integer serveEfficiency,String description,Integer isAnonymous){
        BasePatientDO patient =patientDao.findById(patientCode).orElse(null);
        WlyyDoorCommentDO doorComment = new WlyyDoorCommentDO();
        BigDecimal evaluateSplit = BigDecimal.ZERO;
        BigDecimal num = new BigDecimal("3");
        //计算三项评分平均分
        evaluateSplit = evaluateSplit.add(
                (new BigDecimal(professionalSkill).add(new BigDecimal(serveAttitude)).add(new BigDecimal(serveEfficiency))).divide(num,2,BigDecimal.ROUND_HALF_UP)
        );
        doorComment.setOrderId(orderId);
        doorComment.setCode(getCode());
        doorComment.setProfessionalSkill(professionalSkill);
        doorComment.setServeAttitude(serveAttitude);
        doorComment.setServeEfficiency(serveEfficiency);
        doorComment.setEvaluateSplit(evaluateSplit);
        doorComment.setIsAnonymous(isAnonymous);
        doorComment.setDescription(description);
        doorComment.setPatient(patientCode);
        doorComment.setCreateUser(patientCode);
        doorComment.setCreateUserName(patient.getName());
        doorComment.setCreateTime(new Date());
        doorCommentDao.save(doorComment);
        //更新工单状态
        WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO =doorCommentDoctorDao.selectOrder(orderId);
        wlyyDoorServiceOrderDO.setStatus(6);
        wlyyDoorServiceOrderDO.setCompleteTime(new Date());
        wlyyDoorServiceOrderDO.setUpdateUser(patientCode);
        wlyyDoorServiceOrderDO.setUpdateUserName(patient.getName());
        wlyyDoorServiceOrderDO.setUpdateTime(new Date());
        wlyyDoorServiceOrderDao.save(wlyyDoorServiceOrderDO);
        //门户页实时动态展示,完成上门服务
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = simpleDateFormat.format(new Date());
            WlyyDynamicMessages dynamicMessages = new WlyyDynamicMessages();
            dynamicMessages.setCreateTime(str);//当前时间
            dynamicMessages.setName(patient.getName());//居民姓名
            String str1 = "居民完成上门服务工单评价";
            dynamicMessages.setCode(patient.getId());
            dynamicMessages.setCodeType("2");
            dynamicMessages.setResult(str1);
            dynamicMessages.setAddress(patient.getAddress());//居民地址
            dynamicMessagesDao.save(dynamicMessages);
        }catch (Exception e){
            e.printStackTrace();
        }
        List<WlyyDoorDoctorDO> wlyyDoorDoctorDOList =wlyyDoorDoctorDao.findByOrderId(orderId);
        for(WlyyDoorDoctorDO wlyyDoorDoctorDO:wlyyDoorDoctorDOList) {
            WlyyDoorCommentDoctorDO doorCommentDoctor = new WlyyDoorCommentDoctorDO();
            doorCommentDoctor.setOrderId(orderId);
            doorCommentDoctor.setCode(getCode());
            doorCommentDoctor.setDoctorCode(wlyyDoorDoctorDO.getDoctor());
            doorCommentDoctor.setProfessionalSkill(professionalSkill);
            doorCommentDoctor.setServeAttitude(serveAttitude);
            doorCommentDoctor.setServeEfficiency(serveEfficiency);
            doorCommentDoctor.setEvaluateSplit(evaluateSplit);
            doorCommentDoctor.setIsAnonymous(isAnonymous);
            doorCommentDoctor.setDescription(description);
            doorCommentDoctor.setPatient(patientCode);
            doorCommentDoctor.setCreateUser(patientCode);
            doorCommentDoctor.setCreateUserName(patient.getName());
            doorCommentDoctor.setCreateTime(new Date());
            doorCommentDoctorDao.save(doorCommentDoctor);
        }
        return"1";
    }
    public JSONObject commentDetail(String patient,String orderId)throws Exception{
        JSONObject result = new JSONObject();
        WlyyDoorCommentDO commentDetail = doorCommentDao.selectCommentDoctor(patient,orderId);
        result.put("commentDetail",commentDetail);
        return result;
    }
}

+ 634 - 484
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java

@ -1,35 +1,40 @@
package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.door.*;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.module.door.dao.*;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.order.BusinessOrderService;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.qvo.ParamQvo;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.fastdfs.FastDFSUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.EntityUtils;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
@ -52,7 +57,6 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
@ -67,17 +71,22 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    private Logger logger = LoggerFactory.getLogger(WlyyDoorServiceOrderService.class);
    @Value("${server.server_url}")
    private String wxServerUrl;
    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
//    @Value("${server.server_url}")
//    private String wxServerUrl;
//    @Value("${doctorAssistant.api}")
//    private String doctorAssistant;
//    @Value("${doctorAssistant.target_url}")
//    private String targetUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BusinessOrderDao businessOrderDao;
    @Autowired
    private BusinessOrderService businessOrderService;
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
@ -149,12 +158,23 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    @Autowired
    private WlyyDoorPrescriptionDrugDao doorPrescriptionDrugDao;
    @Value("${neiwang.enable}")
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    FileUploadService fileUploadService;
    //    @Value("${neiwang.enable}")
    private Boolean isneiwang;  //如果不是内网项目要转到到内网wlyy在上传
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Value("${neiwang.wlyy}")
    //    @Value("${neiwang.wlyy}")
    private String neiwangWlyy;  //内网的项目地址
    @Value("${wlyy.url}")
    private String wlyyUrl;
    @Autowired
    private WlyyDoorOrderItemDao doorOrderItemDao;
    @Autowired
@ -168,8 +188,11 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    @Autowired
    private WeiXinAccessTokenUtils tokenUtils;
//    @Autowired
//    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    private WxTemplateConfigDao wxTemplateConfigDao;
//    @Autowired
//    private DmJobService dmJobService;
@ -184,7 +207,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * 带预约-创建上门服务
     */
    @Transactional
    public JSONObject proxyCreate(String jsonData, String doctorCode) {
    public JSONObject proxyCreate(String jsonData, String doctorCode) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
@ -197,15 +220,14 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            return result;
        }
        //资质处理 .医生填写资质信息后,生成一个已通过审核的资质
        try {
            if (jsonObjectParam.get("doorServiceApplication") != null) {
                //创建审核
                doorServiceApplicationService.create("2", jsonObjectParam.get("doorServiceApplication").toString(), doctorCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 资质处理 .医生填写资质信息后,生成一个已通过审核的资质
         * 云照护没用资质审核模块
         */
//        if (jsonObjectParam.get("doorServiceApplication") != null) {
//            //创建审核
//            doorServiceApplicationService.create("2", jsonObjectParam.get("doorServiceApplication").toString(), doctorCode);
//        }
        WlyyDoorServiceOrderDO orderDO = null;
@ -276,8 +298,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            orderDO.setUpdateUser(orderDO.getProxyPatient());
            orderDO.setUpdateUserName(orderDO.getProxyPatientName());
        }
        orderDO.setStatus(2);
        orderDO.setType(3);
        orderDO.setStatus(2);//2-待(医生)接单
        orderDO.setType(3);//3医生代预约
        orderDO.setDispatcherResponseTime(new Date());
        this.save(orderDO);
        result.put("orderId", orderDO.getId());
@ -286,21 +308,24 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            return result;
        }
        if ("1".equals(orderDO.getShortcutType())) {
//            //快捷的当前医生直接接单
//            try {
//                Doctor doctor = doctorDao.findByCode(orderDO.getDoctor());
//                Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
//                doorOrderService.acceptOrder1(orderDO.getId(), doctor.getJob(), doctor.getJobName(), hospital.getLevel());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        } else {
            // 给服务医生发接单消息
            this.createMessage(orderDO.getId(), orderDO.getProxyPatient(), orderDO.getDoctor(), 407, "服务工单待接单", "您有新的服务工单,请前往处理");
            //发送智能助手消息
            sendWeixinMessage(4, orderDO.getDoctor(), orderDO.getPatient());
        }
//        if ("1".equals(orderDO.getShortcutType())) {
////            //快捷的当前医生直接接单
////            try {
////                Doctor doctor = doctorDao.findByCode(orderDO.getDoctor());
////                Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
////                doorOrderService.acceptOrder1(orderDO.getId(), doctor.getJob(), doctor.getJobName(), hospital.getLevel());
////            } catch (Exception e) {
////                e.printStackTrace();
////            }
//        } else {
//            // 给服务医生发接单消息
//            this.createMessage(orderDO.getId(), orderDO.getProxyPatient(), orderDO.getDoctor(), 407, "服务工单待接单", "您有新的服务工单,请前往处理");
//            //发送智能助手消息
//            sendWeixinMessage(4, orderDO.getDoctor(), orderDO.getPatient());
//        }
        //待预约走调度平台的模式
        result = submitDoorOrderAndSendMsg(orderDO, "5", jsonObjectParam);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        return result;
@ -355,7 +380,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithPackageItemFeeAdd(JSONObject result, JSONObject jsonObjectParam, WlyyDoorServiceOrderDO order) {
    public boolean orderWithPackageItemFeeAdd(
            JSONObject result, JSONObject jsonObjectParam, WlyyDoorServiceOrderDO order
    ) throws Exception {
        List<WlyyDoorFeeDetailDO> feeDetailDOList = new ArrayList<>();
        List<WlyyDoorOrderItemDO> orderItemDOList = new ArrayList<>();
        BigDecimal totalFee = order.getTotalFee();
@ -366,34 +393,17 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        JSONArray packageItemArray = jsonObjectParam.getJSONArray("packageItemArr");
        if (!CollectionUtils.isEmpty(packageItemArray)) {
            for (Object one : packageItemArray) {
                WlyyDoorFeeDetailDO feeDetailDO = null;
                JSONObject oneJson = (JSONObject) one;
                try {
                    feeDetailDO = EntityUtils.jsonToEntity(one.toString(), WlyyDoorFeeDetailDO.class);
                    WlyyDoorOrderItemDO orderItemDO = new WlyyDoorOrderItemDO();
                    orderItemDO.setDoctor(order.getDoctor());
                    orderItemDO.setCode(feeDetailDO.getCode());
                    orderItemDO.setCreateTime(new Date());
                    orderItemDO.setPatient(orderItemDO.getPatient());
                    orderItemDOList.add(orderItemDO);
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单与服务费用关联关系时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                try {
                    //工单主表中记录总费用
                    totalFee = totalFee.add(feeDetailDO.getFee().multiply(BigDecimal.valueOf(feeDetailDO.getNumber())));
                } catch (Exception e) {
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    String failMsg = "工单主表中记录总费用时," + e.getMessage();
                    result.put(ResponseContant.resultMsg, failMsg);
                    logger.error(failMsg);
                    return true;
                }
                WlyyDoorFeeDetailDO feeDetailDO = EntityUtils.jsonToEntity(one.toString(), WlyyDoorFeeDetailDO.class);
                WlyyDoorOrderItemDO orderItemDO = new WlyyDoorOrderItemDO();
                //工单主表中记录总费用
                totalFee = totalFee.add(feeDetailDO.getFee().multiply(BigDecimal.valueOf(feeDetailDO.getNumber())));
                //赋值
                orderItemDO.setDoctor(order.getDoctor());
                orderItemDO.setCode(feeDetailDO.getCode());
                orderItemDO.setCreateTime(new Date());
                orderItemDO.setPatient(order.getPatient());
                orderItemDO.setOrderId(order.getId());
                orderItemDOList.add(orderItemDO);
                // 服务项可能一开始由居民预约,后期由医生新增或医生删除
                Integer status = jsonObjectParam.getInteger("status");
                if (null == status || status == 1) {
@ -401,7 +411,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                } else {
                    feeDetailDO.setStatus(status);
                }
//                feeDetailDO.setNumber(1);
                feeDetailDO.setOrderId(order.getId());
                if (StringUtils.isBlank(feeDetailDO.getId())) {
                    feeDetailDO.setCreateTime(new Date());
@ -410,24 +419,14 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                }
                feeDetailDOList.add(feeDetailDO);
            }
//            order.setTotalFee(totalFee);
//            this.save(order);
            try {
                wlyyDoorFeeDetailDao.saveAll(feeDetailDOList);
                doorOrderItemDao.saveAll(orderItemDOList);
//                wlyyDoorFeeDetailService.batchInsert(feeDetailDOList);
            } catch (Exception e) {
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                String failMsg = "保存服务费用到数据库异常:," + e.getMessage();
                result.put(ResponseContant.resultMsg, failMsg);
                logger.error(failMsg);
                return true;
            }
        }/*else{
            // 未添加服务项时,费用默认为0
            order.setTotalFee(new BigDecimal(0));
            this.save(order);
        }*/
            wlyyDoorFeeDetailDao.saveAll(feeDetailDOList);
            doorOrderItemDao.saveAll(orderItemDOList);
            //更新总费用
            order.setTotalFee(totalFee);
            wlyyDoorServiceOrderDao.save(order);
        }
        return false;
    }
@ -505,7 +504,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                    }
                    wlyyDoorFeeDetailService.delete(idStrSet.toArray());
                    totalFee = orderDO.getTotalFee().subtract(totalSubFee);
//                    orderDO.setTotalFee(totalFee);
                    orderDO.setTotalFee(totalFee);
                    wlyyDoorServiceOrderDao.save(orderDO);//保存总费用
                }
            }
            wlyyDoorDoctorService.delete(idStrSet.toArray());
@ -560,7 +560,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            ConsultDo consult = consultDao.queryByRelationCode(orderDO.getId());
            String sessionId = null;
            if (consult != null) {
                sessionId = orderDO.getPatient() + "_" + consult.getCode() + "_" + orderDO.getNumber() + "_" + consult.getType();
                sessionId = orderDO.getPatient() + "_" + consult.getId() + "_" + orderDO.getNumber() + "_" + consult.getType();
            }
            for (Object one : doctorArray) {
                WlyyDoorDoctorDO doorDoctorDO = null;
@ -636,9 +636,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject queryDispatcherInfoByPatient(String hospitalCode) {
        JSONObject result = new JSONObject();
    public List<Map<String, Object>> queryDispatcherInfoByPatient(String hospitalCode) {
        String sql = "SELECT\n" +
                "	a.doctor_code 'code',\n" +
                "	b.`name` 'name',\n" +
@ -653,78 +651,66 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "	INNER JOIN base_doctor b ON a.doctor_code = b.id \n" +
                "WHERE\n" +
                "	1 = 1 \n" +
                "	AND t.`code` = 'dispatcher' \n" +
                "	AND a.org_code = '" + hospitalCode + "' \n";
//              "	AND r.doctor_code = '402803816babc778016babca8bdc003a'";
                "	AND t.`code` = 'dispatcher' \n";
        List<Map<String, Object>> dispatcherInfoList = jdbcTemplate.queryForList(sql);
//        List dispatcherInfoList = roleService.queryDispatcherInfoByHospital(hospitalCode);
        if (CollectionUtils.isEmpty(dispatcherInfoList)) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前居民所签约机构【" + hospitalCode + "】没有调度员,请联系管理员分配!";
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
//        if (StringUtils.isNotBlank(hospitalCode)) {
//            sql += " AND a.org_code = '" + hospitalCode + "' \n";
//        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, dispatcherInfoList);
        return result;
        List<Map<String, Object>> dispatcherInfoList = jdbcTemplate.queryForList(sql);
        return dispatcherInfoList;
    }
    /**
     * 创建上门服务工单
     *
     * @param jsonData
     * @return
     */
    public JSONObject create(String jsonData) {
//    @Transactional(rollbackFor = Exception.class)
    public JSONObject create(String jsonData) throws Exception {
        logger.info("创建上门服务jsonData参数:" + jsonData);
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        WlyyDoorServiceOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "上门服务工单服务基本信息:" + e.getMessage();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        JSONObject jsonObjectParam = JSONObject.parseObject(jsonData);
        WlyyDoorServiceOrderDO orderDO = EntityUtils.jsonToEntity(
                jsonObjectParam.get("order").toString(), WlyyDoorServiceOrderDO.class);
        orderDO.setNumber(getRandomIntStr());
        orderDO.setCreateTime(new Date());
        orderDO.setCreateUser(orderDO.getProxyPatient());
        orderDO.setCreateUserName(orderDO.getProxyPatientName());
        orderDO.setOrderInfo("0");
        orderDO.setOrderInfo("0");//工单详情 0-未推送 1-未确认 2-已确认
//        //服务后收费标识(1是0否)
//        if ("1".equals(orderDO.getFeeAfter())) {
//            //工单状态:-1-已取消,1-待(调度员)派单,2-待(医生)接单,3-待服务,4-待付款,5-待评价,6-已完成
//            if (StringUtils.isNotBlank(orderDO.getDoctor())) {
//                orderDO.setStatus(2);//待接单(医生)
//            } else {
//                orderDO.setStatus(1);//待派单(调度员)
//            }
//        } else {
//            orderDO.setStatus(4);//待付款
//        }
        if (StringUtils.isNotBlank(orderDO.getDoctor())) {
            orderDO.setStatus(2);//待接单(医生)
        } else {
            orderDO.setStatus(1);//待派单(调度员)
        }
        if (StringUtils.isEmpty(orderDO.getPatient())) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
            throw new Exception("当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient());
        }
        if (StringUtils.isEmpty(orderDO.getProxyPatient())) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前代理对象code为空,请联系管理员检查参数!proxyPatient = " + orderDO.getProxyPatient();
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
            throw new Exception(failMsg);
        }
        //已取消的订单也可以申请
        //判断师傅存在为完成的上门服务订单
        boolean bool = wlyyDoorServiceOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                new Integer[]{WlyyDoorServiceOrderDO.Status.waitForSend.getType(),
                        WlyyDoorServiceOrderDO.Status.waitForAccept.getType(),
@ -733,11 +719,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                });
        if (bool) {
            String failMsg = "当前服务对象存在未完成的上门服务,请先完成该服务!";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
            String failMsg = "当前服务对象存在未完成或未付款的上门服务,请先完成该服务!";
            throw new Exception(failMsg);
        }
        orderDO.setHospital(jsonObjectParam.getJSONObject("hospital").get("code").toString());
@ -748,86 +731,197 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        } else if (!orderDO.getProxyPatient().equals(orderDO.getPatient())) {
            orderDO.setType(2);
        }
        orderDO.setServiceStatus("1");
        this.save(orderDO);
        //创建咨询
        JSONObject successOrNot = null;
        try {
            successOrNot = consultTeamService.addDoorServiceConsult(orderDO.getId());
        } catch (Exception e) {
            String failMsg = "创建咨询时异常: " + e.getMessage();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if (Integer.parseInt(successOrNot.get(ResponseContant.resultFlag).toString()) == ResponseContant.fail) {
            return JSONObject.parseObject(successOrNot.toString());
        }
        ConsultTeamDo consultTeam = (ConsultTeamDo) successOrNot.get(ResponseContant.resultMsg);
        orderDO.setServiceStatus("1");//服务类型 1-预约项目 2-即时项目
        //保存服务订单
        wlyyDoorServiceOrderDao.save(orderDO);
        //新增工单与服务项费用关联关系
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO)) {
            return result;
        }
        //获取居民所签约的机构的调度员
        JSONObject dispatcherJson = queryDispatcherInfoByPatient(jsonObjectParam.getJSONObject("hospital").get("code").toString());
        //没有调度员的模式
        if ((dispatcherJson.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail)
                && StringUtils.isEmpty(orderDO.getDoctor()) && StringUtils.isEmpty(orderDO.getExpectedDoctorName())) {
            orderDO.setStatus(2);
            //应该是康复模板的康复下转,才有签约--先注释
//            orderDO.setDoctor(signFamily.getDoctor());
//            orderDO.setDoctorName(signFamily.getDoctorName());
            this.save(orderDO);
            WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findById(orderDO.getId()).orElse(null);
            //新增工单医生关联关系
            if (orderWithDoctorAdd(result, jsonObjectParam, wlyyDoorServiceOrder)) {
        /**
         * 1、发起支付订单
         * 2、发送咨询消息
         */
        result = submitDoorOrderAndSendMsg(orderDO, "5", jsonObjectParam);
        return result;
    }
    /**
     * 5表示上门服务
     * 情况
     * 1.直接付款走流程
     * 2.创建订单没付完款-待付款
     * 3.还要超时订单
     * -----
     * 这个上门服务是线下收费,不用在线支付
     */
    private JSONObject submitDoorOrderAndSendMsg(WlyyDoorServiceOrderDO orderDO, String type, JSONObject jsonObjectParam) throws Exception {
        boolean flag = true;
        JSONObject result = new JSONObject();
//        //创建订单信息
//        BasePatientDO pateint = patientDao.findById(orderDO.getPatient());
//        //查询是否存在订单信息
//        BusinessOrderDO businessOrderDO = businessOrderDao.findByOrderId(orderDO.getId());
//        if (businessOrderDO == null) {
//            businessOrderDO = new BusinessOrderDO();
//            businessOrderDO.setPatient(pateint.getId());
//            //支付账号
//            businessOrderDO.setYkOrderId(pateint.getMobile());
//            businessOrderDO.setPatientName(pateint.getName());
//            businessOrderDO.setOrderType(1);
//            businessOrderDO.setOrderCategory(type);
//            Date date = new Date();
//            Long lastPayTime = date.getTime() + 1000 * 60 * 30;//订单截至支付日期
//            businessOrderDO.setDescription("上门服务");
//            businessOrderDO.setRelationCode(orderDO.getId());//订单id
//            businessOrderDO.setRelationName("上门服务");
//            businessOrderDO.setCreateTime(date);
//            businessOrderDO.setUpdateTime(date);
//            businessOrderDO.setStatus(0);
//            businessOrderDO.setOrderNo(orderDO.getNumber());
//            businessOrderDO.setUploadStatus(0);
//            businessOrderDO.setPayType(1);
//            businessOrderDO.setPayPrice(Double.valueOf(orderDO.getTotalFee().doubleValue()));
//            businessOrderDO.setLastPayTime(lastPayTime);
//        } else {
//            /**
//             * 暂时没用,线下付款的
//             * 1、是否付款完成
//             * 2、判断付款时间是否超过时长了--还需要定时任务监听订单修改状态,把未付款改成已取消
//             */
////            if (businessOrderDO.getStatus() != 1) {
////                long nowTime = System.currentTimeMillis();
////                Long lastPayTime = businessOrderDO.getLastPayTime();
////                if (lastPayTime > nowTime) {
////                    //超时了 修改工单状态成已取消
////                    orderDO.setStatus(-1);//-已取消
////                    wlyyDoorServiceOrderDao.saveAll(orderDO);//更新上门工单
////                    businessOrderDO.setStatus(2);//已取消
////                    businessOrderDao.saveAll(businessOrderDO);//更新业务表
////                    flag = false;//不用创建咨询内容
////                }
////            }
//        }
        /**
         *  1、费用0时无需支付
         *  2、调用微信支付 再来更新flag标识
         */
//        if ("5".equals(type) && 0.0 == orderDO.getTotalFee().doubleValue()) {
//            businessOrderDO.setStatus(1);//1已支付
//            businessOrderDao.saveAll(businessOrderDO);
//        } else {
//            /**
//             * 保存订单信息-这边要判断付款回调修改状态值-付款失败取消订单
//             * businessOrderService
//             */
//            businessOrderDO.setStatus(0);//0待支付
//            businessOrderDao.saveAll(businessOrderDO);
//        }
        //保存业务表
//        businessOrderDao.saveAll(businessOrderDO);
        /**
         * 目前是线下付款的
         * 给出标识是否成功,往下面创建咨询信息发送内容
         */
        if (flag) {
            //获取机构的调度员
            List<Map<String, Object>> dispatcherList = queryDispatcherInfoByPatient(jsonObjectParam.getJSONObject("hospital").get("code").toString());
            //支付成功或者不用支付
            //创建咨询
            JSONObject successOrNot = consultTeamService.addDoorServiceConsult(orderDO.getId());
            ConsultTeamDo consultTeam = (ConsultTeamDo) successOrNot.get(ResponseContant.resultMsg);
            System.out.println("===调度员的信息开始======");
            for (Map<String, Object> map : dispatcherList) {
                System.out.println("调度员=>" + JSON.toJSONString(map));
            }
            System.out.println("===调度员的信息结束======");
            //判断其是否有分配执行人。如果有不用走调度平台
            if (StringUtils.isNotBlank(orderDO.getDoctor())) {
                orderDO.setStatus(2);//待接单
                orderDO.setDoctor(orderDO.getDoctor());
                orderDO.setDoctorName(orderDO.getDoctorName());
                this.save(orderDO);
                //新增工单医生关联关系
                if (orderWithDoctorAdd(result, jsonObjectParam, orderDO)) {
                    return result;
                }
                // 给服务医生发接单消息
                this.createMessage(orderDO.getId(), orderDO.getProxyPatient(), orderDO.getDoctor(), 407, "服务工单待接单", "您有新的服务工单,请前往处理");
                //发送智能助手消息-微信消息先注释
                sendWeixinMessage(4, orderDO.getDoctor(), orderDO.getPatient());
                result.put(ResponseContant.resultFlag, ResponseContant.success);
                result.put(ResponseContant.resultMsg, consultTeam);
                return result;
            }
            // 给服务医生发接单消息--先注释
//            this.createMessage(orderDO.getId(), orderDO.getProxyPatient(), signFamily.getDoctor(), 407, "服务工单待接单", "您有新的服务工单,请前往处理");
            //发送智能助手消息-微信消息先注释
//            sendWeixinMessage(4, signFamily.getDoctor(), orderDO.getPatient());
            //有调度员
            if (!dispatcherList.isEmpty()) {
                for (Map<String, Object> map : dispatcherList) {
                    String dispatcher = map.get("code").toString();
                    // 派单消息-首页
                    this.createMessage(orderDO.getId(), "system", dispatcher, 402, "新增居民预约服务申请", orderDO.getPatientName() + "提交了服务预约申请,请您前往处理");
                    // 派单-实时工单消息  430 居民提交工单申请-- 张三提交了服务工单12345678申请
                    this.createMessage(orderDO.getId(), "system", dispatcher, 430, "居民提交工单申请", orderDO.getPatientName() + "提交了服务工单" + orderDO.getNumber() + "申请");
                }
            }
            //给机构调度员发送医生助手消息
            for (Map<String, Object> map : dispatcherList) {
                //这边还没有微信消息的功能呢
                sendWeixinMessage(3, map.get("code") + "", orderDO.getPatient());
            }
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg, consultTeam);
            return result;
        }
        //todo 解决报错,resultMsg是字符串
        if (dispatcherJson.getIntValue(ResponseContant.resultFlag) != ResponseContant.fail) {
            List<Map<String, Object>> dispatcherInfoList = (List) dispatcherJson.get(ResponseContant.resultMsg);
            for (Map<String, Object> map : dispatcherInfoList) {
                String dispatcher = map.get("code").toString();
                // 派单消息-首页
                this.createMessage(orderDO.getId(), "system", dispatcher, 402, "新增居民预约服务申请", orderDO.getPatientName() + "提交了服务预约申请,请您前往处理");
                // 派单-实时工单消息  430 居民提交工单申请-- 张三提交了服务工单12345678申请
                this.createMessage(orderDO.getId(), "system", dispatcher, 430, "居民提交工单申请", orderDO.getPatientName() + "提交了服务工单" + orderDO.getNumber() + "申请");
            }
        }
        //给机构调度员发送医生助手消息
        String dispatcherSql = "SELECT u.user_code FROM `manage_role_user` u ,wlyy_doctor d where u.role_id = 22 and u.user_code = d.`code` and d.hospital = '" + orderDO.getHospital() + "'";
        List<Map<String, Object>> dispatcherList = jdbcTemplate.queryForList(dispatcherSql);
        for (Map<String, Object> map : dispatcherList) {
            sendWeixinMessage(3, map.get("user_code") + "", orderDO.getPatient());
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
            //发送 预约卡片信息(2101类型)
            JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
            orderInfoContent.put("re_msg_type", 0);//居民预约
            System.out.println("准备发送预约卡片信息");
            int flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
            System.out.println("flagCount==>" + flagCount);
            //模拟一,重试3次
//            int tryCount = 3;
//            int flagCount = 0;
//            for (int i = 0; i < tryCount; i++) {
//                //发送消息
//                flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
//                if (flagCount == 1) {
//                    break;
//                }
//            }
        //发送 预约卡片信息(2101类型)
        JSONObject orderInfoContent = this.queryOrderCardInfo(orderDO);
        orderInfoContent.put("re_msg_type", 0);//居民预约
        this.qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
//            //模式2,睡眠1秒钟
//            Thread.sleep(1000);
//            flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
        if (StringUtils.isNoneBlank(orderDO.getDoctor())) {
            //服务医生修改,直接转派
            BaseDoctorDO transDoctor = doctorDao.findById(orderDO.getDoctor()).orElse(null);
            sendOrderToDoctor(orderDO.getId(), null, "system", "系统", transDoctor.getId(), transDoctor.getName(), transDoctor.getJobTitleName());
            //后面这个要修改下,加个字段判断下是否转派
            if (StringUtils.isNoneBlank(orderDO.getDoctor())) {
                //服务医生修改,直接转派
                BaseDoctorDO transDoctor = doctorDao.findById(orderDO.getDoctor()).orElse(null);
                sendOrderToDoctor(orderDO.getId(), null, "system", "系统", transDoctor.getId(), transDoctor.getName(), transDoctor.getJobTitleName());
            }
        } else {
            //取消订单
            orderDO.setStatus(-1);//-已取消
            wlyyDoorServiceOrderDao.save(orderDO);//更新上门工单
        }
        return result;
    }
    /**
     * 发送微信消息
     * 三院暂时没这个功能--没有签约这个动作
@ -837,8 +931,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
//        if (type == 1) {
//            try {
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zztj");
//                BasePatientDO patient1 = patientDao.findById(patient).orElse(null);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//                BasePatientDO patient1 = patientDao.findById(patient);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode);
//                String doctorName = doctor.getName();
//                SignFamily signFamily = signFamilyDao.findByPatient(patient);//签约数据
//                String first = doctorName + "医生,您好!" + patient1.getName() + "提交了资质申请,请及时登录PC或APP处理";
@ -861,8 +955,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
//            //调度员转交给家庭医生
//            try {
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zztj");
//                BasePatientDO patient1 = patientDao.findById(patient).orElse(null);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//                BasePatientDO patient1 = patientDao.findById(patient);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode);
//                SignFamily signFamily = signFamilyDao.findByPatient(patient);
//                String doctorName = doctor.getName();
//                String first = doctorName + "医生,您好!" + patient1.getName() + "提交了资质申请,请及时登录PC或APP处理";
@ -885,8 +979,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
//            //上门预约申请
//            try {
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zztj");
//                BasePatientDO patient1 = patientDao.findById(patient).orElse(null);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//                BasePatientDO patient1 = patientDao.findById(patient);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode);
//                SignFamily signFamily = signFamilyDao.findByPatient(patient);
//                String doctorName = doctor.getName();
//                String first = doctorName + "医生,您好!" + patient1.getName() + "提交了上门出诊服务预约,请及时登录PC处理";
@ -909,7 +1003,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
//            try {
//                //社区调度员指派服务工单给家签医生
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zztj");
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//                BaseDoctorDO doctor = doctorDao.findById(doctorCode);
//                SignFamily signFamily = signFamilyDao.findByPatient(patient);
//                String doctorName = doctor.getName();
//                String first = doctorName + "医生,您好!您有新的服务工单,请及时登录APP或PC处理";
@ -937,7 +1031,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @param dispatcher
     * @param orderId
     */
    public JSONObject dispatcherIntoTopic(String orderId, String hospitalName, String dispatcher, String dispatcherName) {
    public JSONObject dispatcherIntoTopic(String orderId, String hospitalName, String dispatcher, String dispatcherName) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        if (null == orderDO) {
@ -948,14 +1042,16 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            return result;
        }
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = orderDO.getPatient() + "_" + consult.getCode() + "_" + orderDO.getNumber() + "_" + consult.getType();
        String sessionId = orderDO.getPatient() + "_" + consult.getId() + "_" + orderDO.getNumber() + "_" + consult.getType();
        // 把调度员拉入会话,作为其中一个成员,第一个进入会话的调度员,系统发送欢迎语和居民的预约卡片信息
        if (StringUtils.isEmpty(orderDO.getDispatcher())) {
            orderDO.setDispatcher(dispatcher);
            orderDO.setDispatcherName(dispatcherName);
            this.save(orderDO);
            // 先进入会话,再聊天
            imUtill.updateParticipant(sessionId, dispatcher, null);
//            String msg = imUtill.updateParticipant(sessionId, dispatcher, null);
            String msg = imUtill.updateParticipantNew(sessionId, dispatcher, null);
            System.out.println("进入会话,再聊天==>" + msg);
            String noticeContent = hospitalName + dispatcherName + "为您服务";
            this.qucikSendIM(orderId, dispatcher, "智能助手", "1", noticeContent);
//            imUtill.sendIntoTopicIM(dispatcher, sessionId, consult.getCode(), noticeContent, orderDO.getProxyPatient(), orderDO.getProxyPatientName());
@ -964,7 +1060,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        }
        // 把调度员拉入会话,作为其中一个成员
        imUtill.updateParticipant(sessionId, dispatcher, null);
//        String msg = imUtill.updateParticipant(sessionId, dispatcher, null);
        String msg = imUtill.updateParticipantNew(sessionId, dispatcher, null);
        System.out.println("把调度员拉入会话,作为其中一个成员==>" + msg);
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, "调度员[" + dispatcherName + "]进入会话成功");
        return result;
@ -972,9 +1070,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    /**
     * 回写最后一个回复内容的调度员到工单表
     *
     * @param dispatcher
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveLastDispatcher(String orderId, String dispatcher, String dispatcherName) {
@ -1104,7 +1199,10 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            e.printStackTrace();
        }
        if (!CollectionUtils.isEmpty(feeDetailDOS)) {
            //2023-10-11 先注释 计算服务费用
            /**
             *  2023-10-11 先注释 计算服务费用
             *  这边需要改写用表base_service_package_record
             */
//            Map<String, Object> map = doorOrderService.countServerPackagePrice(jsonData, orderDO.getPatient());
//            orderBriefInfo.put("packageFee", map.get("serverPackagePrice"));
        }
@ -1191,12 +1289,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    /**
     * 生成二維碼
     *
     * @param id
     * @param token
     * @return
     */
    public String twoDimensionalCode(String id, String token) {
    public UploadVO twoDimensionalCode(String id, String token) throws Exception {
        JSONObject orderJson = new JSONObject();
        List<WlyyDoorServiceOrderDO> orderList = this.findByField("id", id);
        if (orderList.size() > 0) {
@ -1206,35 +1300,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            //生成二维码图片
            String contentJsonStr = orderDO.getNumber();
            InputStream ipt = QrcodeUtil.createQrcode(contentJsonStr, 300, "png");
            if (isneiwang) {
                // 圖片列表
                List<String> tempPaths = new ArrayList<String>();
                try {
                    ObjectNode imgNode = FastDFSUtil.upload(ipt, "png", "plan_service_qrcode" + System.currentTimeMillis());
                    JSONObject json = JSONObject.parseObject(imgNode.toString());
                    tempPaths.add(json.getString("fid"));
                    String urls = "";
                    for (String image : tempPaths) {
                        if (urls.length() == 0) {
                            urls = image;
                        } else {
                            urls += "," + image;
                        }
                    }
                    fileUrl = fastdfs_file_url + urls;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    fileUrl = fastdfs_file_url + PrescriptionQRCodetoNeiWang(ipt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            param.put("number", orderDO.getNumber());
            param.put("imageUrl", fileUrl);
            return fileUrl;
            UploadVO uploadVO = PrescriptionQRCodetoNeiWang(ipt);
            return uploadVO;
        } else {
            return null;
        }
@ -1243,28 +1310,33 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    /**
     * 长处方生成取药码,生成取药二维码
     * 如果是外网那是发送到内网的服务器
     *
     * @param ipt
     * @return
     */
    public String PrescriptionQRCodetoNeiWang(InputStream ipt) throws FileNotFoundException {
        String filename = "QRCode_" + System.currentTimeMillis();
    public UploadVO PrescriptionQRCodetoNeiWang(InputStream ipt) throws Exception {
        String filename = "QRCode_" + System.currentTimeMillis() + ".jpg";
        String fileUrls = "";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String returnStr = request(request, ipt, filename);
        logger.info("returnStr :" + returnStr);
        logger.info("fileName :" + filename);
        logger.info("result :" + returnStr.toString());
        if (returnStr != null) {
            //1.3.7去掉前缀
            fileUrls += returnStr + ",";
        }
        return fileUrls.substring(0, fileUrls.length() - 1);
        UploadVO uploadVO = fileUploadService.uploadStream(ipt, filename, fastdfs_file_url);
//        System.out.println(uploadVO.getFullUri());
//        String returnStr = request(request, ipt, filename);
//        logger.info("returnStr :" + returnStr);
//        logger.info("fileName :" + filename);
//        logger.info("result :" + returnStr.toString());
//        if (returnStr != null) {
//            //1.3.7去掉前缀
//            fileUrls += returnStr + ",";
//        }
        return uploadVO;
    }
    public String request(HttpServletRequest request, InputStream in, String fileName) {
        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径
        //上传地址
        String url = wlyyUrl + "/upload/chat";
//        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
@ -1319,8 +1391,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        String sql = "SELECT " +
                "  d.photo AS doctorPhoto, " +
                "  d.`name` AS doctorName, " +
                "  d.`job_name` AS doctorJobName, " +
                "  d.hospital_name AS hospitalName, " +
                "  d.`job_title_name` AS doctorJobName, " +
                "  d.visit_hospital_name AS hospitalName, " +
                "  d.mobile AS doctorPhone, " +
                "  o.id, " +
                "  o.number, " +
@ -1330,17 +1402,16 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "  o.`status` AS status, " +
                "  o.`pay_way` AS payWay, o.type," +
                "  ifnull(de.order_id,concat(rand(),'_notExist')) AS feeOrderId, " +
                "  dm.phone AS hospitalPhone, " +
                "  count(de.number) as itemCount " +
                "  a.mobile AS hospitalPhone, " +
                "  count(de.number) as itemCount ," +
                "  o.sign_id 'signId' , o.package_id 'packageId' " +
                " FROM " +
                "  ( wlyy_door_service_order o " +
                " LEFT JOIN wlyy_doctor d ON o.doctor = d.`code`) " +
                " LEFT JOIN wlyy_door_fee_detail de on o.id = de.order_id " +
                " LEFT JOIN dm_hospital dm on o.hospital = dm.code " +
                " LEFT JOIN base_doctor d ON o.doctor = d.`id`) " +
                " LEFT JOIN wlyy_door_fee_detail de on o.id = de.order_id  and de.type='1' " +
                " LEFT JOIN base_org a on o.hospital = a.code " +
                " WHERE " +
                "  (o.patient = '{patient}' " +
//                "or o.proxy_patient = '{patient}'" +
                ") " +
                "  (o.patient = '{patient}') " +
                " AND (o.`status` = {status} or -100 = {status})" +
                "  group by o.id " +
                " ORDER BY o.create_time desc" +
@ -1355,9 +1426,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "   count(DISTINCT o.id)  " +
                " FROM  " +
                "  ( wlyy_door_service_order o " +
                " LEFT JOIN wlyy_doctor d ON o.doctor = d.`code`) " +
                " LEFT JOIN base_doctor d ON o.doctor = d.`id`) " +
                " LEFT JOIN wlyy_door_fee_detail de on o.id = de.order_id " +
                " LEFT JOIN dm_hospital dm on o.hospital = dm.code " +
                " LEFT JOIN base_org a on o.hospital = a.code " +
                " WHERE  " +
                "  (o.patient = '{patient}' or o.proxy_patient = '{patient}') " +
                " AND (o.`status` = {status} or -100 = {status})";
@ -1366,8 +1437,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                .replace("{status}", String.valueOf(status));
        List sqlResultlist = new ArrayList<>();
        logger.info("infoList-info: " + finalSql);
        logger.info("infoList-count: " + finqlCountSql);
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
        } catch (Exception e) {
@ -1447,10 +1516,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderInfo(String orderId) {
        String sql = "UPDATE `wlyy_door_service_order` SET order_info =2 WHERE id = ?";
        Object[] params = new Object[]{orderId};
        int a = jdbcTemplate.update(sql, params);
        return a;
        String sql = "UPDATE `wlyy_door_service_order` SET order_info =2 WHERE id = '" + orderId + "'";
        int i = jdbcTemplate.update(sql);
        return i;
    }
@ -1600,7 +1668,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
        BasePatientDO patient = patientService.findPatientById(orderDO.getPatient());
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "smyyyqx");
        WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene("xm_test_ihealth_wx", "template_process_feedback", "smyyyqx");
        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", first);
@ -1609,7 +1677,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        json.put("url", templateConfig.getUrl());
        json.put("remark", templateConfig.getRemark());
        if (consult != null) {
            json.put("consult", consult.getCode());
            json.put("consult", consult.getId());
        } else {
            json.put("id", orderDO.getId());
        }
@ -1628,30 +1696,30 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        return result;
    }
    public JSONObject orderMsgTask(String orderId) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
        BasePatientDO patient = patientService.findPatientById(orderDO.getPatient());
        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback", "smyyyqx");
        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
        org.json.JSONObject json = new org.json.JSONObject();
        json.put("first", orderDO.getPatientName() + ",您好!您的上门服务知情同意书已送达");
        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
        json.put("keyword2", "知情同意书已推送");
//        json.put("url", templateConfig.getUrl());
        json.put("url", "appoint_service/html/appoint-serviceDetail.html?id=" + orderId);
//        appoint_service/html/appoint-serviceDetail.html?openid=ojsU-1XJVftkfdbP1F5bi8JVPtOo&consult=e0d17c67ab07477f8e96534bc610e51b
        json.put("remark", templateConfig.getRemark());
        if (consult != null) {
            json.put("consult", consult.getCode());
        } else {
            json.put("id", orderDO.getId());
        }
        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
        return result;
    }
//    public JSONObject orderMsgTask(String orderId) throws Exception {
//        JSONObject result = new JSONObject();
//        WlyyDoorServiceOrderDO orderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);;
//        ConsultDo consult = consultDao.queryByRelationCode(orderId);
//        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
//        BasePatientDO patient = patientService.findPatientById(orderDO.getPatient());
//        WxTemplateConfigDO templateConfig = wxTemplateConfigDao.findByScene("template_process_feedback", "smyyyqx");
//        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
//        org.json.JSONObject json = new org.json.JSONObject();
//        json.put("first", orderDO.getPatientName() + ",您好!您的上门服务知情同意书已送达");
//        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
//        json.put("keyword2", "知情同意书已推送");
////        json.put("url", templateConfig.getUrl());
//        json.put("url", "appoint_service/html/appoint-serviceDetail.html?id=" + orderId);
////        appoint_service/html/appoint-serviceDetail.html?openid=ojsU-1XJVftkfdbP1F5bi8JVPtOo&consult=e0d17c67ab07477f8e96534bc610e51b
//        json.put("remark", templateConfig.getRemark());
//        if (consult != null) {
//            json.put("consult", consult.getId());
//        } else {
//            json.put("id", orderDO.getId());
//        }
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
//        return result;
//    }
    /**
     * 统计居民一个月内工单取消次数
@ -1742,7 +1810,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateOrderCardInfo(String jsonData) {
    public JSONObject updateOrderCardInfo(String jsonData) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
@ -1759,7 +1827,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        wlyyDoorServiceOrder.setPatientName(jsonObjectParam.getString("patientName"));
//        wlyyDoorServiceOrder.setProxyPatientPhone(jsonObjectParam.getString("phone"));
        // 居民电话
        if (!StringUtils.isEmpty(jsonObjectParam.getString("phone"))) {
            wlyyDoorServiceOrder.setPatientPhone(jsonObjectParam.getString("phone"));
@ -1913,7 +1980,10 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     *
     * @return
     */
    public JSONObject queryBriefList(String dispatcher, String hospital, String orderNumber, String patientName, String phone, Integer status, String patientType, int page, int size) {
    public JSONObject queryBriefList(
            String dispatcher, String hospital, String orderNumber,
            String patientName, String phone, Integer status, String patientType, int page, int size
    ) throws Exception {
        JSONObject result = new JSONObject();
        orderNumber = null == orderNumber ? "" : orderNumber;
@ -1949,11 +2019,12 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "  o.serve_lat as lat, " +
                "  o.`status` as status, " +
                "  o.`dispatcher_name` as dispatcherName, " +
                "  concat( o.patient,'_' ,c.`code`, '_',o.`number`,'_11' ) as sessionId, " +
                "  concat( o.patient,'_' ,c.`id`, '_',o.`number`,'_11' ) as sessionId, " +
                "   t1.`type` as patientType " +
                " FROM " +
                " ( wlyy_door_service_order o " +
                "LEFT JOIN wlyy_patient p ON o.patient = p.`code` ) LEFT JOIN wlyy_consult c on o.id = c.relation_code" +
                " LEFT JOIN base_patient p ON o.patient = p.`id` ) " +
                " LEFT JOIN wlyy_consult c on o.id = c.relation_code " +
                " left JOIN ( " +
                "         select a.patient, group_concat(v.type) as type " +
                "         from wlyy_door_service_voucher v " +
@ -1981,7 +2052,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "   count(o.id)  " +
                " FROM  " +
                "   wlyy_door_service_order o  " +
                " LEFT JOIN wlyy_patient p ON o.patient = p.`code` " +
                " LEFT JOIN base_patient p ON o.patient = p.`id` " +
                " left JOIN  ( " +
                "         select a.patient, group_concat(v.type) as type " +
                "         from wlyy_door_service_voucher v " +
@ -2003,7 +2074,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        List<Map<String, Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            logger.info(finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询【调度员】上门服务工单列表信息失败:" + e.getMessage());
@ -2028,6 +2098,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        }
        String serviceSql = "SELECT count(d.id) times FROM wlyy_door_doctor d where d.order_id in(SELECT id from wlyy_door_service_order WHERE DATE_FORMAT(doctor_sign_time, '%Y') = DATE_FORMAT(NOW(), '%Y') AND patient=?)";
//        final Set<String>  patientSet = doorServiceVoucherDao.queryByTypeIn(types);
        sqlResultlist.forEach(
                oneMap -> {
                    // 获取服务次数
@ -2035,22 +2107,23 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                    oneMap.put("serviceCount", serviceCount);
                    oneMap.put("isInSession", false);
                    String sessionId = String.valueOf(oneMap.get("sessionId"));
                    JSONArray parArray = imUtill.getParticipants(sessionId);
                    parArray.forEach(
                            oneParObj -> {
                                org.json.JSONObject oneParJson = (org.json.JSONObject) oneParObj;
                                if (StringUtils.equalsIgnoreCase(oneParJson.getString("id"), dispatcher)) {
                                    oneMap.put("isInSession", true);
                    JSONArray parArray = null;
                    try {
                        parArray = imUtill.getParticipants(sessionId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (parArray != null) {
                        parArray.forEach(
                                oneParObj -> {
                                    com.alibaba.fastjson.JSONObject oneParJson = (com.alibaba.fastjson.JSONObject) oneParObj;
                                    if (StringUtils.equalsIgnoreCase(oneParJson.getString("id"), dispatcher)) {
                                        oneMap.put("isInSession", true);
                                    }
                                }
                            }
                    );
                    /*// 筛选居民类型 半失能/失能老人 肺结核患者 计生特殊家庭 残疾人 重性精神病 其他 等
                    if(patientSet.contains(oneMap.get("patient"))){
                        filteredResult.add(oneMap);
                    }*/
                        );
                    }
                });
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
        JSONObject countItem = new JSONObject();
@ -2065,7 +2138,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     *
     * @return
     */
    public JSONObject queryDoctorList(String patient, String hospital, String doctorName, String status, int page, int size) {
    public JSONObject queryDoctorList(
            String patient, String hospital, String doctorName, String status, int page, int size
    ) throws Exception {
        JSONObject result = new JSONObject();
        doctorName = null == doctorName ? "" : doctorName;
@ -2075,9 +2150,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        int start = 0 == page ? page++ : (page - 1) * size;
        int end = 0 == size ? 15 : size;
        //
        String sql = "SELECT " +
                "  d.code as doctor, " +
                "  a.dept_code 'deptCode',\ta.dept_name 'deptName',a.org_code 'orgCode',\ta.org_name 'orgName', " +
                "  d.id as doctor, " +
                "  d.photo as photo, " +
                "  d.name as name," +
                "  case d.sex  " +
@ -2085,20 +2160,29 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "  when 1 then '男' " +
                "  when 2 then '女' " +
                "  end as sex, " +
                "  d.`job_name` AS jobName, " +
                "  d.mobile as phone, " +
                "  d.job_title_code 'jobCode', d.`job_title_name` AS jobName, " +
                "  d.mobile as phone," +
                "  CONCAT(d.doctor_lat ,',',d.doctor_lon) 'position', " +
                "  IFNULL(ds.`status`,5) as status," +
                "  1 as sortFlag ,count(o.id) as count" +
                " FROM " +
                " wlyy_doctor d " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor LEFT JOIN wlyy_door_service_order o on o.doctor = d.code and o.`status` in (2,3,4) " +
                " WHERE d.status = 1" +
                " AND d.level <> 11" +
                " AND d.hospital = '{hospital}' " +
                " AND d.`name` like '%{doctorName}%' " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')" +
                " base_doctor d " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`id` = ds.doctor " +
                " LEFT JOIN wlyy_door_service_order o on o.doctor = d.id  and o.`status` in (2,3,4)  " +
                " LEFT JOIN base_doctor_hospital a ON d.id=a.doctor_code " +
                " WHERE 1=1 " +
                " and d.enabled = 1 " +
//                " AND d.level <> 11" +
                " AND a.org_code = '{hospital}' ";
        if (StringUtils.isNotBlank(doctorName)) {
            sql += " AND d.`name` like '%{doctorName}%' ";
        }
        sql += " AND (ds.`status` in ({status}) or '-100' = '{status}')" +
                " AND d.del=1  " +
                " GROUP BY d.`code` ORDER BY ds.create_time DESC " +
                " GROUP BY d.`id` " +
                " ORDER BY ds.create_time DESC " +
                " LIMIT {start},{end}";
        String finalSql = sql.replace("{hospital}", hospital)
@ -2110,50 +2194,26 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        String countSql = "SELECT  " +
                "   count(d.id)  " +
                " FROM  " +
                "   wlyy_doctor d  " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor " +
                " WHERE d.status = 1" +
                " AND d.level <> 4" +
                " AND d.hospital = '{hospital}' " +
                " AND d.`name` like '%{doctorName}%' " +
                " AND d.del=1 and d.status=1 " +
                "   base_doctor d  " +
                " LEFT JOIN wlyy_door_doctor_status ds ON d.`id` = ds.doctor " +
                " LEFT JOIN base_doctor_hospital a ON d.id=a.doctor_code " +
                " WHERE d.enabled = 1" +
//                " AND d.level <> 4" +
                " AND a.org_code = '{hospital}' ";
        if (StringUtils.isNotBlank(doctorName)) {
            countSql += " AND d.`name` like '%{doctorName}%' ";
        }
        countSql += " AND d.del=1 and d.enabled=1 " +
                " AND (ds.`status` in ({status}) or '-100' = '{status}')";
        String finalCountSql = countSql.replace("{hospital}", hospital)
                .replace("{doctorName}", doctorName)
                .replace("{status}", String.valueOf(status));
        List<Map<String, Object>> sqlResultlist = new ArrayList<>();
        try {
            sqlResultlist = jdbcTemplate.queryForList(finalSql);
            if (sqlResultlist != null && sqlResultlist.size() != 0) {
                for (Map<String, Object> map : sqlResultlist) {
                    BaseDoctorDO doctor = doctorDao.findById(map.get("doctor").toString()).orElse(null);
                    //先注释需要在加字段20231011
//                    Hospital hospital1 = hospitalDao.findByCode(doctor.getHospital());
//                    if (doctor.getPosition() == null || doctor.getPosition() == "") {
//                        map.put("position", hospital1.getPosition());
//                    } else {
//                        map.put("position", doctor.getPosition());
//                    }
                }
            }
            logger.info("服务医生人员sql:" + finalSql);
        } catch (Exception e) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库查询 服务医生人员 列表信息失败:" + e.getMessage());
            return result;
        }
        List<Map<String, Object>> sqlResultlist = jdbcTemplate.queryForList(finalSql);
        Integer count = jdbcTemplate.queryForObject(finalCountSql, Integer.class);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(finalCountSql, Integer.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg, "从数据库统计  服务医生人员 数量失败:" + e.getMessage());
            return result;
        }
        //添加未完成服务工单列表
        for (Map<String, Object> map : sqlResultlist) {
            String doctor = map.get("doctor") + "";
@ -2161,66 +2221,12 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            if (notFinish > 0 && StringUtils.isNotBlank(doctor)) {
                String notFinishSql = "select o.id,o.number,o.patient,o.patient_name,o.patient_phone,o.patient_expected_serve_time,o.`status`, CASE p.sex when 1 then '男' when 2 THEN '女' END as sex,p.idcard, " +
                        "year(now()) - ((CASE LENGTH(p.idcard) WHEN 18 THEN substring(p.idcard, 7, 4) WHEN 15 THEN CONCAT('19',substring(p.idcard, 7, 2)) END )) as age , p.photo,o.serve_lat AS lat,o.serve_lon AS lon,o.id AS orderId " +
                        "from wlyy_door_service_order o LEFT JOIN wlyy_patient p on o.patient = p.`code` and p.`status`=1 " +
                        "from wlyy_door_service_order o LEFT JOIN base_patient p on o.patient = p.`id` and p.`del`=1 " +
                        "where o.doctor ='" + doctor + "' and o.status in (2,3,4)";
                List<Map<String, Object>> notFinishList = jdbcTemplate.queryForList(notFinishSql);
                map.put("notFinishList", notFinishList);
            }
        }
        // 居民端第一页置顶家庭医生 -- 先注释掉-20231011
//        if (!StringUtils.isEmpty(patient) && page == 1) {
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (null != signFamily) {
//                String signDoctor = signFamily.getDoctor();
//                String signDoctorName = signFamily.getDoctorName();
//                //判断当前居民是否有家庭医生
//                boolean doctorExist = wlyyDoorDoctorStatusDao.existsByDoctorAndStatusIn(signDoctor, new Integer[]{1, 2, 3, 4});
//                if (doctorExist) {
//                    boolean bool = false;
//                    Map<String, Object> signDoctorMap = new HashMap<>();
//                    for (Map<String, Object> oneDoctorMap : sqlResultlist) {
//                        bool = oneDoctorMap.containsValue(signDoctor);
//                        if (bool) {
//                            oneDoctorMap.put("sortFlag", 0L);
//                            oneDoctorMap.put("isSignDoctor", true);
//                            break;
//                        }
//                    }
//                    if (!bool) {
//                        //查出家签医生置顶
//                        String signDocSql = "SELECT " +
//                                " d. CODE AS doctor, " +
//                                " d.photo AS photo, " +
//                                " d. NAME AS name, " +
//                                " CASE d.sex " +
//                                "WHEN 0 THEN " +
//                                " '无' " +
//                                "WHEN 1 THEN " +
//                                " '男' " +
//                                "WHEN 2 THEN " +
//                                " '女' " +
//                                "END AS sex, " +
//                                " d.`job_name` AS jobName, " +
//                                " d.mobile AS phone, " +
//                                " IFNULL(ds.`status`, 5) AS STATUS, " +
//                                " 0 AS sortFlag, " +
//                                " count(o.id) AS count " +
//                                "FROM " +
//                                " wlyy_doctor d " +
//                                "LEFT JOIN wlyy_door_doctor_status ds ON d.`code` = ds.doctor " +
//                                "LEFT JOIN wlyy_door_service_order o ON o.doctor = d. CODE " +
//                                "AND o.`status` IN (2, 3, 4) " +
//                                "WHERE " +
//                                " d. STATUS = 1 AND d.hospital = '" + hospital + "'" +
//                                " and d.name like '%" + doctorName + "%'" +
//                                "AND d.`code` = '" + signDoctor + "'";
//                        sqlResultlist.addAll(jdbcTemplate.queryForList(signDocSql));
////                        count += 1;
//                    }
//                    sqlResultlist.sort(comparing((doctor) -> Integer.parseInt(doctor.get("sortFlag").toString())));
//                }
//            }
//        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, sqlResultlist);
@ -2331,16 +2337,15 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject sendOrderToDoctor(String orderId, String remark, String dispatcher, String dispathcherName, String doctor, String doctorName, String doctorJobName) {
    public JSONObject sendOrderToDoctor(
            String orderId, String remark, String dispatcher, String dispathcherName, String doctor, String doctorName, String doctorJobName
    ) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        if (null == doorServiceOrderDO) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单不存在,id:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
            throw new Exception(failMsg);
        }
        WlyyDoorDoctorStatusDO doorDoctorStatusDO = wlyyDoorDoctorStatusDao.queryByDoctorAndStatusIn(doctor, new Integer[]{WlyyDoorDoctorStatusDO.Status.waitForSend.getType(),
@ -2349,11 +2354,8 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                WlyyDoorDoctorStatusDO.Status.serving.getType(),
        });
        if (null == doorDoctorStatusDO) {
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前派单的医生不存在或禁止接单,doctor:" + doctor;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
            throw new Exception(failMsg);
        }
        doorServiceOrderDO.setRemark(remark);
@ -2377,8 +2379,9 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getCode() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipant(sessionId, doctor, null);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        String response = imUtill.updateParticipant(sessionId, doctor, null);
        System.out.println("给医生加入群聊==>" + response);
        // 调度员处理完该单(新增预约的,或者是拒单重新派单的)
        List<SystemMessageDO> messages = systemMessageDao.queryByRelationCodeAndTypeIn(orderId, new String[]{"402", "404", "430", "435"});
@ -2433,7 +2436,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject transferOrder(String orderId, String remark, String dispatcher, String dispathcherName, String doctor, String doctorName, String doctorJobName) {
    public JSONObject transferOrder(String orderId, String remark, String dispatcher, String dispathcherName, String doctor, String doctorName, String doctorJobName) throws Exception {
        JSONObject result = new JSONObject();
        WlyyDoorServiceOrderDO doorServiceOrderDO = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        if (null == doorServiceOrderDO) {
@ -2478,7 +2481,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getCode() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
        imUtill.updateParticipant(sessionId, doctor, null);
        // 调度员处理完该单(新增预约的,或者是拒单重新派单的)
@ -2628,36 +2631,72 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @param content
     * @return
     */
    public int qucikSendIM(String orderId, String sendId, String sendName, String contentType, String content) {
        int result = -1;
        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        if (null == consult) {
            logger.error("当前工单未关联咨询,工单id:" + orderId);
            return result;
    public int qucikSendIM(String orderId, String sendId, String sendName, String contentType, String content) throws Exception {
        int tryAgain = 3;
        int flag = 0;
        for (int i = 0; i < tryAgain; i++) {
            flag = sendMsg(orderId, sendId, sendName, contentType, content);
            if (flag == 1) {
                break;
            } else {
                System.out.println("开始重试发送");
            }
        }
        return flag;
    }
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = null;
        String response = null;
        if (StringUtils.isBlank(sendId)) {
            wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
            String sender = "system";
            if (StringUtils.isNoneBlank(wlyyDoorServiceOrder.getDispatcher())) {
                sender = wlyyDoorServiceOrder.getDispatcher();
            }
            response = imUtill.sendTopicIM(sender, "智能助手", consult.getCode(), contentType, content, null);
    public int sendMsg(String orderId, String sendId, String sendName, String contentType, String content) throws Exception {
        System.out.println("发送消息的方法【sendMsg】");
        int result = -1;
        System.out.println("查询ConsultDo==>参数:" + orderId);
        String sql = "SELECT * FROM wlyy_consult WHERE relation_code='" + orderId + "'";
        ConsultDo consult = null;
        List<ConsultDo> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ConsultDo.class));
        if (list != null && list.size() > 0) {
            consult = list.get(0);
            System.out.println("ConsultDo的list数量==>" + list.size());
        } else {
            response = imUtill.sendTopicIM(sendId, sendName, consult.getCode(), contentType, content, null);
            throw new Exception("ConsultDo为空,参数RelationCode:" + orderId);
        }
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getIntValue("status") == -1) {
            logger.error("上门服务工单消息发送失败:" + resObj.getString("message"));
//        ConsultDo consult = consultDao.queryByRelationCode(orderId);
        System.out.println("方法:【sendMsg】 内容:consult==>" + JSON.toJSONString(consult));
        if (null == consult) {
            System.out.println("当前工单未关联咨询,工单id:" + orderId);
            return result;
        }
        try {
            String response = null;
            if (StringUtils.isBlank(sendId)) {
                WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
                System.out.println("方法:【wlyyDoorServiceOrder】 内容:consult==>" + JSON.toJSONString(consult));
                String sender = "system";
                if (StringUtils.isNoneBlank(wlyyDoorServiceOrder.getDispatcher())) {
                    sender = wlyyDoorServiceOrder.getDispatcher();
                }
                response = imUtill.sendTopicIM(sender, "智能助手", consult.getId(), contentType, content, null);
            } else {
                response = imUtill.sendTopicIM(sendId, sendName, consult.getId(), contentType, content, null);
            }
            System.out.println("sendTopicIM结果==>" + response);
            JSONObject resObj = JSONObject.parseObject(response);
            if (resObj.getIntValue("status") == -1) {
                String msg = "上门服务工单消息发送失败:" + resObj.getString("message");
                System.out.println(msg);
                return -1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上门服务工单消息发送失败:" + e.getMessage());
            return -1;
        }
        result = 1;
        return result;
    }
    /**
     * 判断消息订单是否已被取消
     *
@ -2666,7 +2705,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     */
    public JSONObject orderIsCancel(String messageId) {
        JSONObject result = new JSONObject();
        String sql = "SELECT m.* FROM `wlyy_message` m LEFT JOIN wlyy_door_service_order o on m.relation_code=o.id " +
        String sql = "SELECT m.* FROM `base_system_message` m LEFT JOIN wlyy_door_service_order o on m.relation_code=o.id " +
                "where  o.status = -1 and m.id='" + messageId + "'";
        List<Map<String, Object>> messageList = jdbcTemplate.queryForList(sql);
        if (messageList.size() == 0) {
@ -2685,6 +2724,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     *
     * @param orderId
     */
    @Transactional
    public void cancelConclusion(String orderId) {
        wlyyDoorServiceOrderDao.updateConclusionStatus(orderId);
    }
@ -2695,6 +2735,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @param orderId
     * @param isPatientConfirm
     */
    @Transactional
    public void updateIsPatientConfirm(String orderId, Integer isPatientConfirm) {
        WlyyDoorServiceOrderDO wlyyDoorServiceOrder = wlyyDoorServiceOrderDao.findById(orderId).orElse(null);
        wlyyDoorServiceOrder.setIsPatientConfirm(isPatientConfirm);
@ -2710,7 +2751,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @param commitPrescriptionCode
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject createPrescription(String orderId, String prescriptionCode, String commitPrescriptionCode) {
    public JSONObject createPrescription(String orderId, String prescriptionCode, String commitPrescriptionCode) throws Exception {
        JSONObject res = new JSONObject();
        //上门后在线开方,手动关联处方号的话更新处方单号跟状态
        if (StringUtils.isNotBlank(commitPrescriptionCode)) {
@ -2755,6 +2796,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
     * @param positionStatus
     * @param position
     */
    @Transactional
    public void updateDoctorStatus(String doctor, Integer positionStatus, String position) {
        BaseDoctorDO doctor1 = doctorDao.findById(doctor).orElse(null);
        //先注释-需要在补字段
@ -2817,7 +2859,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    @Transactional
    public JSONObject proxyUpdate(String jsonData, String doctorCode) {
    public JSONObject proxyUpdate(String jsonData, String doctorCode) throws Exception {
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
@ -2892,7 +2934,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        if (orderWithPackageItemFeeAdd(result, jsonObjectParam, orderDO)) {
            return result;
        }
        if (!orderDO.getDoctor().equals(serviceOrderDO.getDoctor())) {
            //服务医生修改,直接转派
            BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
@ -2997,4 +3038,113 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        result.put(ResponseContant.resultMsg, wlyyDoorServiceOrder);
        return result;
    }
    public Map<String, Object> getDoctorInfo(ParamQvo qvo) {
        Map<String, Object> map = new HashMap<>();
        String sql = "SELECT\n" +
                "	a.*,\n" +
                "	b.dept_name 'deptName',\n" +
                "	b.org_code 'orgCode',\n" +
                "	b.org_name 'orgName',\n" +
                "	c.mapping_code 'jobNumber',\n" +
                "	h.dept_type_code 'deptTypeCode' \n" +
                "FROM\n" +
                "	base_doctor a\n" +
                "	LEFT JOIN base_doctor_hospital b ON a.id = b.doctor_code\n" +
                "	LEFT JOIN base_doctor_mapping c ON a.id = c.doctor\n" +
                "	LEFT JOIN dict_hospital_dept h ON b.dept_code = h.CODE \n" +
                "WHERE\n" +
                "	1 = 1 \n" +
                "	AND a.id='" + qvo.getLoginUserCode() + "' ";
//                "	AND b.org_code = '922b9636-5aff-11e6-8344-fa163e8aee56'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (!list.isEmpty()) {
            map = list.get(0);
            //查询角色
            String roleSql = "SELECT " +
                    " t.CODE AS \"roleCode\", " +
                    " t.NAME AS \"roleName\"" +
                    " FROM " +
                    " base_doctor_role r " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " WHERE " +
                    " r.doctor_code = '" + qvo.getLoginUserCode() + "'";
            List<Map<String, Object>> roleList = jdbcTemplate.queryForList(roleSql);
            if (roleList != null && roleList.size() > 0) {
                map.put("roles", roleList);
            } else {
                map.put("roles", null);
            }
        }
        return map;
    }
    /**
     * 初始化社区医生
     */
    public void initDoorStatus(String hospital) {
        String sql = "SELECT * from base_doctor doc WHERE doctor_level=1 and id not in ( " +
                "SELECT doctor from wlyy_door_doctor_status " +
                ")";
        //机构就不要了
//        if (org.apache.commons.lang.StringUtils.isNotBlank(hospital)) {
//            sql += "and EXISTS (select id from base_doctor_hospital dh where doc.id = dh.doctor_code and dh.org_code='" + hospital + "' and dh.del=1 ) ";
//        }
        List<BaseDoctorDO> doctorDOs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(BaseDoctorDO.class));
        List<WlyyDoorDoctorStatusDO> doctorList = new ArrayList<>(doctorDOs.size());
        for (BaseDoctorDO baseDoctorDO : doctorDOs) {
            WlyyDoorDoctorStatusDO doctorDoor = new WlyyDoorDoctorStatusDO();
            doctorDoor.setDoctor(baseDoctorDO.getId());
            doctorDoor.setStatus(1);
            doctorDoor.setCreateTime(new Date());
            doctorDoor.setCreateUser("System");
            doctorDoor.setCreateUserName("System");
            doctorList.add(doctorDoor);
        }
        wlyyDoorDoctorStatusDao.saveAll(doctorList);
    }
    public List<Map<String, Object>> getDotorOrgList() {
        String sql = "SELECT a.org_code 'hospitalCode',a.org_name 'hospitalName' \n" +
                "FROM base_doctor_hospital a INNER JOIN base_doctor b\n" +
                "WHERE b.doctor_level='1'\n";
        sql += " GROUP BY a.org_code,a.org_name ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    public void updateOrderStatusAndTime(String orderId, String status, String doctorArrivingTime) {
        String sql = " update wlyy_door_service_order o set o.prescription_status = 0,o.status ='" + status + "' ,o.doctor_arriving_time='" + doctorArrivingTime + "'  where o.id = '" + orderId + "' ";
        jdbcTemplate.execute(sql);
    }
    public List<Map<String, Object>> getOgrById(String signId, String orderId) {
        String sql = "";
        if (StringUtils.isNotBlank(signId)) {
            sql = "SELECT\n" +
                    "	b.* \n" +
                    "FROM\n" +
                    "	base_service_package_sign_record a\n" +
                    "	INNER JOIN base_service_package_item b ON a.service_package_id = b.service_package_id\n" +
                    "	AND a.id='" + signId + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        }
        if (StringUtils.isNotBlank(orderId)) {
            sql = "SELECT\n" +
                    "	DISTINCT b.* \n" +
                    "FROM\n" +
                    "	base_service_package_sign_record a\n" +
                    "	INNER JOIN wlyy_door_service_order b ON a.service_package_id=b.package_id\n" +
                    "	INNER JOIN base_service_package_item c ON b.package_id = c.service_package_id\n" +
                    "	AND b.id='" + orderId + "'\n";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        }
        return null;
    }
}

+ 1 - 3
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java

@ -16,13 +16,12 @@ import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.module.followup.dao.*;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.hospital.module.system.service.SystemDictService;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.idcard.IdCardUtil;
@ -40,7 +39,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

+ 2 - 2
business/base-service/src/main/java/com/yihu/jw/jw/service/JwArchivesService.java

@ -1,6 +1,6 @@
package com.yihu.jw.jw.service;
package com.yihu.jw.hospital.module.jw.service;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.hospital.module.system.service.SystemDictService;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;

+ 2 - 2
business/base-service/src/main/java/com/yihu/jw/jw/service/JwSmjkService.java

@ -1,9 +1,9 @@
package com.yihu.jw.jw.service;
package com.yihu.jw.hospital.module.jw.service;
import com.yihu.jw.entity.base.system.SystemDictDO;
import com.yihu.jw.entity.hospital.booking.ReservationHospitalDept;
import com.yihu.jw.hospital.module.system.service.SystemDictService;
import com.yihu.jw.hospital.prescription.vo.GuahaoDoctor;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.util.common.XMLUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;

+ 891 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/message/DoctorMessageController.java

@ -0,0 +1,891 @@
package com.yihu.jw.hospital.module.message;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping(value = "/doctor/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = {RequestMethod.GET, RequestMethod.POST})
@Api(description = "医生端-消息")
public class DoctorMessageController extends EnvelopRestEndpoint {
    @Autowired
    private SystemMessageService messageService;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private SystemMessageDao messageDao;
//    @Autowired
//    private ThirdJkEduArticleService thirdJkEduArticleService;
//    @Autowired
//    private SpecialistEvaluateSevice specialistEvaluateSevice;
//    @Autowired
//    ElasticsearchUtil elasticsearchUtil;
    //    @Value("${demo.flag}")
    private Boolean demoFlag;
    @RequestMapping(value = "getWaitingMessages", method = RequestMethod.GET)
    @ApiOperation("获取服务工单待接单列表")
    @ResponseBody
    public Envelop getWaitingMessages(
            @ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
            @ApiParam(name = "types", value = "消息类型") @RequestParam(value = "types", required = true) String types,
            @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
            @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize
    ) {
        if (StringUtils.isBlank(pageSize)) {
            pageSize = "10";
        }
        if (page.equals("0")) {
            page = "1";
        }
        String[] split = StringUtils.split(types, ",");
        List<Integer> typeList = new ArrayList<>();
        for (String s : split) {
            typeList.add(Integer.valueOf(s));
        }
        SystemMessageDO message1 = new SystemMessageDO();
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
        message1.setOver(object.getString("over"));
        message1.setIsRead(object.getInteger("read").toString());
        System.out.println("getUID()=>" + getUID());
        message1.setReceiver(getUID());
        try {
            JSONObject waitingMessages = messageService.getWaitingMessages(message1, types, Integer.valueOf(page), Integer.valueOf(pageSize));
            return success("查询成功", waitingMessages);
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
//    @ResponseBody
//    @RequestMapping(value = "messages")
//    @ApiOperation("查询医生未读消息和最后消息")
//    public Envelop messages(
//            @ApiParam(name = "type", value = "文章审核的时候必传,消息类型,14:提交文章审核,15:审核结果") @RequestParam(value = "type", required = false) Integer type,
//            @ApiParam(name = "flag", value = "标识家医/专科") @RequestParam(value = "flag", required = false) Integer flag
//    ) {
//        try {
//            JSONObject json = messageService.findDoctorAllMessage(getUID(), type, flag);
//            return success("获取消息总数成功!", json);
//        } catch (Exception e) {
//            return failed(e.getMessage());
//        }
//    }
    /**
     * 医生消息总数统计接口
     *
     * @return
     */
//    @RequestMapping(value = "amount")
//    @ResponseBody
//    @ApiOperation("医生消息总数统计接口")
//    public String amount() {
//        try {
//            JSONObject json = messageService.findDoctorAllMessageAmount(getUID());
//            if (json == null) {
//                return error(-1, "获取消息总数失败!");
//            } else {
//                return write(200, "获取消息总数成功!", "data", json);
//            }
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 健康咨询消息列表查询接口
     *
     * @param id
     * @param pagesize 分页大小
     * @return
     */
//    @RequestMapping(value = "consults")
//    @ResponseBody
//    @ApiOperation("健康咨询消息列表查询接口")
//    public String consultList(long id, int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<ConsultTeamDo> list = messageService.findConsultListByDoctor(getUID(), id, pagesize);
//            for (ConsultTeamDo consult : list) {
//                if (consult == null) {
//                    continue;
//                }
//                JSONObject json = new JSONObject();
//                json.put("id", consult.getId());
//                // 设置咨询标识
//                json.put("consult", consult.getConsult());
//                // 设置患者标识
//                json.put("patient", consult.getPatient());
//                // 设置患者头像
//                json.put("photo", consult.getPhoto());
//                // 设置主要症状
//                json.put("symptoms", consult.getSymptoms());
//                // 设置患者姓名
//                json.put("name", consult.getName());
//                // 设置状态(0进行中,1已完成,-1患者取消)
//                json.put("status", consult.getStatus());
//                // 设置消息未读数量
//                json.put("unread", consult.getDoctorRead());
//                // 设置咨询时间
//                json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
//                array.put(json);
//            }
//            return write(200, "获取健康咨询列表成功!", "list", array);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    /**
//     * 更新体征消息为已读
//     *
//     * @param msgid
//     * @return
//     */
//    @RequestMapping(value = "read_health")
//    @ResponseBody
//    @ApiOperation("消息设置成已读")
//    public String readHealth(long msgid) {
//        try {
//            messageService.readHealth(msgid);
//            return success("操作成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 根据参数查询发送给我的消息
     */
//    @RequestMapping(value = "find")
//    @ResponseBody
//    @ApiOperation("查询发送给我的消息")
//    public String findMyMessage(String sender, String signStatus) {
//        try {
//            SystemMessageDO msg = messageService.findUnreadSign(sender, getUID(), signStatus);
//            JSONObject json = null;
//            if (msg != null) {
//                json = new JSONObject();
//                json.put("id", msg.getId());
//                json.put("sender", msg.getSender());
//                json.put("senderName", msg.getSenderName());
//                json.put("type", msg.getType());
//                json.put("read", msg.getIsRead()); // 是否已读:1未读,0已读
////                json.put("signStatus", msg.getSignStatus());
//                json.put("status", msg.getOver());
//                json.put("reason", msg.getReason());
//            }
//            return write(200, "获取消息成功!", "data", json);
//        } catch (Exception e) {
//            return "获取失败=>"+e.getMessage();
//        }
//    }
    /**
     * 系统消息(分配健管师 + 随访计划消息 )
     */
//    @RequestMapping(value = "getSystemMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取系统消息")
//    public String getSystemMessage(@ApiParam(value = "第几页", defaultValue = "1")
//                                   @RequestParam Integer page,
//                                   @ApiParam(value = "每页几行", defaultValue = "10")
//                                   @RequestParam Integer pagesize) {
//        try {
//            List<SystemMessageDO> list = messageService.getSystemMessage(getUID(), page, pagesize);
//            return write(200, "获取消息成功!", "list", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 续方
     */
//    @RequestMapping(value = "getPrescriptionMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取续方消息")
//    public String getPrescriptionMessage(@ApiParam(value = "第几页", defaultValue = "1")
//                                         @RequestParam Integer page,
//                                         @ApiParam(value = "每页几行", defaultValue = "10")
//                                         @RequestParam Integer pagesize,
//                                         @ApiParam(value = "类型(6团队长待审核,7健管师待取药)", defaultValue = "6")
//                                         @RequestParam Integer type) {
//        try {
//            List<SystemMessageDO> list = messageService.getPrescriptionMessage(getUID(), type, page, pagesize);
//            return write(200, "获取消息成功!", "list", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 文章审核
     *
     * @param page
     * @param pagesize
     * @return
     */
//    @RequestMapping(value = "getEduArticleMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取文章审核消息")
//    public String getEduArticleMessage(@ApiParam(name = "type", value = "文章审核的时候必传,消息类型,14:提交文章审核,15:审核结果")
//                                       @RequestParam(value = "type", required = false) Integer type,
//                                       @ApiParam(value = "第几页", defaultValue = "1")
//                                       @RequestParam Integer page,
//                                       @ApiParam(value = "每页几行", defaultValue = "10")
//                                       @RequestParam Integer pagesize) {
//        try {
//            List<SystemMessageDO> list = messageService.getEduArticleMessage(getUID(), type, page, pagesize);
//            return write(200, "获取消息成功!", "list", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getHealthIndexMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取超标指标消息--根据患者分组")
//    public String getHealthIndexMessage() throws Exception {
//        try {
//            Map<String, List<Map<String, Object>>> list = messageService.getHealthIndexMessage(getUID());     //"D20161008003"
//
//            return write(200, "获取超标指标消息成功", "data", list);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, ex.getMessage());
//        }
//    }
//    @RequestMapping(value = "getHealthIndexMessageByPatient", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取患者超标指标消息")
//    public String getHealthIndexMessageByPatient(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20161008001")
//                                                 @RequestParam(value = "patient", required = true) String patient,
//                                                 @ApiParam(name = "type", value = "健康指标类型1血糖,2血压,3体重", defaultValue = "1")
//                                                 @RequestParam(value = "type", required = true) String type,
//                                                 @ApiParam(name = "page", value = "第几页", defaultValue = "1")
//                                                 @RequestParam(value = "page", required = true) Integer page,
//                                                 @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
//                                                 @RequestParam(value = "pagesize", required = true) Integer pagesize) throws Exception {
//        try {
//
//            List<Map<String, String>> list = messageService.getHealthIndexMessageByPatient(getUID(), patient, type, page, pagesize, getObserverStatus());
//            Map<Object, Object> map = new HashMap<Object, Object>();
//            ObjectMapper mapper = new ObjectMapper();
//            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//            map.put("status", 200);
//            map.put("msg", "获取超标指标消息成功");
//            map.put("data", list);
//            String tzCode = "";
//            for (Map<String, String> one : list) {
//                tzCode += "," + one.get("tzCode");
//            }
//            map.put("tzCode", StringUtils.isNotEmpty(tzCode) ? tzCode.substring(1) : "");
//            return mapper.writeValueAsString(map);
//        } catch (Exception ex) {
//            return ex.getMessage();
//        }
//    }
    /**
     * 设置某类消息已读
     *
     * @param type 消息类型
     * @return
     */
//    @RequestMapping(value = "setMessageReaded")
//    @ResponseBody
//    @ApiOperation("设置某类消息已读")
//    public Envelop setMessageReaded(@RequestParam @ApiParam(value = "消息类型") Integer type) {
//        try {
//            messageService.setMessageReaded(getUID(), type);
//            return success("设置成功");
//        } catch (Exception e) {
//            return failed(e.getMessage());
//        }
//    }
    /**
     * 设置某条消息已读
     */
//    @RequestMapping(value = "setMessageReadedById")
//    @ResponseBody
//    @ApiOperation("设置某条消息已读")
//    public String setMessageReadedById(@RequestParam @ApiParam(value = "消息id") Long id) {
//        try {
//            messageService.setMessageReadedById(getUID(), id);
//            return write(200, "设置成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    @RequestMapping(value = "getMessageNoticeSetting", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取消息设置")
    public String getMessageNoticeSetting() {
        try {
            com.alibaba.fastjson.JSONObject messageNoticeSetting = messageService.getMessageNoticSetting(getUID(), "1");
            return write(200, "查询成功", "data", messageNoticeSetting);
        } catch (Exception e) {
            return e.getMessage();
        }
    }
//    @RequestMapping(value = "saveMessageNoticeSetting", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("保存消息提醒设置")
//    public Envelop saveMessageNoticeSetting(@ApiParam(name = "json", value = "数据json")
//                                            @RequestParam(value = "json", required = true) String json) {
//        try {
//            MessageNoticeSetting messageNoticeSetting = objectMapper.readValue(json, MessageNoticeSetting.class);
//            if (messageNoticeSetting.getId() == null) {
//                return failed( "参数错误");
//            }
//            messageService.saveMessageNoticeSetting(messageNoticeSetting);
//            return success("设置成功");
//        } catch (Exception e) {
//            return failed(  e.getMessage());;
//        }
//    }
//    /**
//     * 待处理
//     */
//    @RequestMapping(value = "unTreated", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("专科医生待处理消息")
//    public String selectUntreated() {
//        try {
//            JSONObject json = messageService.selectUntreated(getUID());
//            return write(200, "获取消息总数成功!", "data", json);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    /**
//     * @param message
//     * @param page
//     * @param pageSize
//     * @return
//     */
//    @RequestMapping(value = "getSpecialist", method = RequestMethod.GET)
//    @ApiOperation("专科医生待处理列表")
//    @ResponseBody
//    public String getSpecialist(@ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
//                                @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
//                                @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize) {
//        if (StringUtils.isBlank(pageSize)) {
//            pageSize = "10";
//        }
//        if (page.equals("0")) {
//            page = "1";
//        }
//        SystemMessageDO  message1 = new SystemMessageDO();
//        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
//        message1.setOver(object.getString("over"));
////        message1.setRead(object.getInteger("read"));
//        message1.setReceiver(getUID());
//        try {
//            return write(200, "查询成功!", "data", messageService.getSpecialistUnTreated(message1, Integer.valueOf(page), Integer.valueOf(pageSize)));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getSpecialistMessages", method = RequestMethod.GET)
//    @ApiOperation("专科医生待处理列表")
//    @ResponseBody
//    public String getSpecialistMessage(@ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
//                                       @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
//                                       @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize) {
//        if (StringUtils.isBlank(pageSize)) {
//            pageSize = "10";
//        }
//        if (page.equals("0")) {
//            page = "1";
//        }
//        SystemMessageDO  message1 = new SystemMessageDO();
//        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
//        message1.setOver(object.getString("over"));
//        message1.setRead(object.getInteger("read"));
//        message1.setReceiver(getUID());
//        try {
//            return write(200, "查询成功!", "data", messageService.getSpecialistMessages(message1, Integer.valueOf(page), Integer.valueOf(pageSize)));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 转诊消息
     *
     * @param message
     * @param page
     * @param pageSize
     * @return
     */
//    @RequestMapping(value = "getTransferMessage", method = RequestMethod.GET)
//    @ApiOperation("转诊消息")
//    @ResponseBody
//    public String getTransferMessage(@ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
//                                     @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
//                                     @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize) {
//        if (StringUtils.isBlank(pageSize)) {
//            pageSize = "10";
//        }
//        if (page.equals("0")) {
//            page = "1";
//        }
//        SystemMessageDO  message1 = new SystemMessageDO();
//        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
//        message1.setOver(object.getString("over"));
//        message1.setRead(object.getInteger("read"));
//        message1.setReceiver(getUID());
//        try {
//            return write(200, "查询成功!", "data", messageService.getTransferMessage(message1, Integer.valueOf(page), Integer.valueOf(pageSize)));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 发送消息 type:19 受理提醒,20 待办工作提醒 21 服务进展提醒-已完成 22 服务进展提醒-未完成
     * message{sender:"",receiver:"",relationCode:""}
     *
     * @param message
     * @param hospital
     * @param patient
     * @param time
     * @return
     */
//    @RequestMapping(value = "sendMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("发送消息")
//    public String sendMessage(@ApiParam(name = "message", value = "消息对象(如:{'sender':'','receiver':'','relationCode':'','type':19})", required = true)
//                              @RequestParam(value = "message", required = true) String message,
//                              @ApiParam(name = "hospital", value = "医院code", required = false)
//                              @RequestParam(value = "hospital", required = false) String hospital,
//                              @ApiParam(name = "patient", value = "居民code", required = true)
//                              @RequestParam(value = "patient", required = true) String patient,
//                              @ApiParam(name = "time", value = "时间", required = false)
//                              @RequestParam(value = "time", required = false) Integer time,
//                              @ApiParam(name = "jsonObject", value = "参数", required = false)
//                              @RequestParam(value = "jsonObject", required = false) String jsonObject) {
//        try {
//            com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(message);
//            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(object.getString("sender"));
//            message1.setType(object.getInteger("type").toString());
//            message1.setReceiver(object.getString("receiver"));
//            message1.setRelationCode(object.getString("relationCode"));
//            com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(jsonObject);
//            return write(200, "获取消息成功!", "data", specialistEvaluateSevice.sendMessage(message1, hospital, patient, time, jsonObject1));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 一键已读
     *
     * @param types
     * @return
     */
//    @RequestMapping(value = "setMessageReads", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("一键已读")
//    public String setMessageRead(
//            @ApiParam(name = "types", value = "消息集合") @RequestParam(value = "types") String types,
//            @ApiParam(name = "flag", value = "标识家医/专科") @RequestParam(value = "flag") Integer flag
//    ) {
//        try {
//            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(types);
//            List<Integer> typeList = new ArrayList<>();
//            for (int i = 0; i < array.size(); i++) {
//                typeList.add(array.getInteger(i));
//            }
//            return write(200, "获取消息总数成功!", "data", messageService.setMessageReaded(getUID(), typeList, flag));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 设置待办消息已处理
     *
     * @param id
     * @param type
     * @return
     */
//    @RequestMapping(value = "setSpecialistOver", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("设置待办消息已处理")
//    public String setSpecialistOver(
//            @ApiParam(name = "id", value = "消息id") @RequestParam(value = "id") Long id,
//            @ApiParam(name = "type", value = "消息类型") @RequestParam(value = "type") Integer type
//    ) {
//        try {
//
//            return write(200, "获取消息总数成功!", "data", messageService.setSpecialistOver(id, type));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 获取协同服务消息列表
     */
//    @RequestMapping(value = "getSynergyMessages", method = RequestMethod.GET)
//    @ApiOperation("协同服务消息列表")
//    @ResponseBody
//    public String getSynergyMessage(@ApiParam(name = "message", value = "消息对象") @RequestParam(value = "message") String message,
//                                    @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
//                                    @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize) {
//        if (StringUtils.isBlank(pageSize)) {
//            pageSize = "10";
//        }
//        if (page.equals("0")) {
//            page = "1";
//        }
//        SystemMessageDO  message1 = new SystemMessageDO();
//        com.alibaba.fastjson.JSONObject object = JSON.parseObject(message);
//        message1.setReceiver(getUID());
//        try {
//            List<SystemMessageDO> messageList = messageService.getSynergyMessages(message1, Integer.valueOf(page), Integer.valueOf(pageSize));
//            return write(200, "查询成功!", "data", messageList);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 设置协同消息已读
     */
//    @RequestMapping(value = "setSynergyMessagesByRead", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("设置协同消息已读")
//    public String setSynergyMessagesByRead() {
//        try {
//            return write(200, "获取消息总数成功!", "data", messageService.setSynergyMessagesByRead(getUID()));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM专科服务
     */
//    @RequestMapping(value = "getSpeciaistByType")
//    @ApiOperation("PCIM专科服务列表")
//    @ResponseBody
//    public String getSpeciaistByType(String types,
//                                     Integer page,
//                                     Integer pageSize) {
//        List<Integer> typeList = new ArrayList<>();
//        String str[] = types.split(",");
//        for (int i = 0; i < str.length; i++) {
//            typeList.add(Integer.parseInt(str[i]));
//        }
//        try {
//            return write(200, "查询成功!", "data", messageService.getSpeciaistByType(typeList, getUID(), page, pageSize));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM专科医生总条数
     *
     * @return
     */
//    @RequestMapping(value = "getDoctorBySpecialistAllMessage", method = RequestMethod.GET)
//    @ApiOperation("PCIM专科医生总条数")
//    @ResponseBody
//    public String getDoctorBySpecialistAllMessage() {
//        try {
//            return write(200, "查询成功!", "data", messageService.getDoctorBySpecialistAllMessage(getUID()));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM-转诊消息
     *
     * @param page
     * @param pageSize
     * @return
     */
//    @RequestMapping(value = "getTransferMessageByPCIM", method = RequestMethod.GET)
//    @ApiOperation("PCIM-转诊消息")
//    @ResponseBody
//    public String getTransferMessageByPCIM(@ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) String page,
//                                           @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) String pageSize) {
//        if (StringUtils.isBlank(pageSize)) {
//            pageSize = "10";
//        }
//        if (page.equals("0")) {
//            page = "1";
//        }
//        try {
//            return write(200, "查询成功!", "data", messageService.getTransferMessageByPCIM(getUID(), Integer.valueOf(page), Integer.valueOf(pageSize)));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM-签约服务列表
     *
     * @param types
     * @param page
     * @param pageSize
     * @return
     */
//    @RequestMapping(value = "getFamilyByType", method = RequestMethod.GET)
//    @ApiOperation("PCIM-签约服务列表")
//    @ResponseBody
//    public String getFamilyByType(@ApiParam(name = "types", value = "消息对象") @RequestParam(value = "types") String types,
//                                  @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) Integer page,
//                                  @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) Integer pageSize) {
//        List<Integer> typeList = new ArrayList<>();
//        String str[] = types.split(",");
//        for (int i = 0; i < str.length; i++) {
//            typeList.add(Integer.parseInt(str[i]));
//        }
//        try {
//            return write(200, "查询成功!", "data", messageService.getFamilySignByType(typeList, getUID(), page, pageSize));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * 获取pcim家医服务
     *
     * @param page
     * @param pageSize
     * @return
     */
//    @RequestMapping(value = "getPCIMFamilyServer", method = RequestMethod.GET)
//    @ApiOperation("PCIM-家医服务")
//    @ResponseBody
//    public String getPCIMFamilyServer(@ApiParam(name = "types", value = "消息对象") @RequestParam(value = "types") String types,
//                                      @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) Integer page,
//                                      @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) Integer pageSize) {
//        try {
//            List<Integer> typeList = new ArrayList<>();
//            String str[] = types.split(",");
//            for (int i = 0; i < str.length; i++) {
//                typeList.add(Integer.parseInt(str[i]));
//            }
//            return write(200, "查询成功!", "data", messageService.getPCIMFamilyServer(getUID(), typeList, page, pageSize));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM-其他业务
     */
//    @RequestMapping(value = "getOtherService", method = RequestMethod.GET)
//    @ApiOperation("PCIM-其他业务")
//    @ResponseBody
//    public String getOtherService(@ApiParam(name = "types", value = "消息对象") @RequestParam(value = "types") String types,
//                                  @ApiParam(name = "page", value = "第几页", defaultValue = "1") @RequestParam(value = "page", required = true) Integer page,
//                                  @ApiParam(name = "pageSize", value = "", defaultValue = "10") @RequestParam(value = "pageSize", required = true) Integer pageSize) {
//        try {
//            List<Integer> typeList = new ArrayList<>();
//            String str[] = types.split(",");
//            for (int i = 0; i < str.length; i++) {
//                typeList.add(Integer.parseInt(str[i]));
//            }
//            return write(200, "查询成功!", "data", messageService.getOtherService(getUID(), typeList, page, pageSize));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM--家庭医生消息总条数
     *
     * @return
     */
//    @RequestMapping(value = "getDoctorByFamilyAllMessage", method = RequestMethod.GET)
//    @ApiOperation("PCIM--家庭医生消息总条数")
//    @ResponseBody
//    public String getDoctorByFamilyAllMessage() {
//        try {
//            return write(200, "查询成功!", "data", messageService.getDoctorByFamilyAllMessage(getUID()));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
    /**
     * PCIM-分析总览
     *day         天数(3,7,30)
     *area        父code
     *level       等级  1 团队,2 机构,3 区,4 市
     *level2_type 指标代码 例如性别 1 男 2 女  不传就返回男和女的总和
     */
//    @RequestMapping(value = "AnalysisOverview", method = RequestMethod.GET)
//    @ApiOperation("PCIM-分析总览")
//    @ResponseBody
//    public String AnalysisOverview(@ApiParam(name = "day", value = "天数") @RequestParam(value = "day") int day,
//                                   @RequestParam(required = false) String area,
//                                   @RequestParam(required = false) Integer level,
//                                   @RequestParam(required = false) String level2_type) {
//        try {
//            if (demoFlag) {
//                return "{\n" +
//                        "    \"msg\": \"查询成功!\",\n" +
//                        "    \"data\": {\n" +
//                        "        \"weixinBindCount\": 1,\n" +
//                        "        \"weixinBindCountChange\": 7,\n" +
//                        "        \"articleCountChange\": \"0.01%\",\n" +
//                        "        \"consultCount\": 12,\n" +
//                        "        \"articleCount\": \"0.05%\",\n" +
//                        "        \"consultCount1\": 24,\n" +
//                        "        \"reservationCount1\": 24,\n" +
//                        "        \"articleCount1\": \"0.03%\",\n" +
//                        "        \"weixinBindCount1\": 8,\n" +
//                        "        \"reservationCount\": 34,\n" +
//                        "        \"consultCountChange\": 12,\n" +
//                        "        \"reservationCountChange\": 10\n" +
//                        "    },\n" +
//                        "    \"status\": 200\n" +
//                        "}";
//            }
//            if (level == null) {
//                level = 5;
//            }
//            return write(200, "查询成功!", "data", messageService.AnalysisOverview(getUID(), day, area, level, level2_type));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getAllNotOverMessage", method = RequestMethod.GET)
//    @ApiOperation("PCIM--专科/家医不同type的消息的总数")
//    @ResponseBody
//    public String getAllNotOverMessage() {
//        try {
//            return write(200, "查询成功!", "data", messageService.getAllNotOverMessage(getUID()));
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getExaminationMessage", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("获取在线复诊消息")
//    public String getPrescriptionMessage(@ApiParam(value = "第几页", defaultValue = "1")
//                                         @RequestParam Integer page,
//                                         @ApiParam(value = "每页几行", defaultValue = "10")
//                                         @RequestParam Integer pagesize
//    ) {
//        try {
//            //31 在线复诊咨询待审核提醒
//            List<SystemMessageDO> list = messageService.getPrescriptionMessage(getUID(), 31, page, pagesize);
//            return write(200, "获取消息成功!", "list", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getMessageByType")
//    @ResponseBody
//    @ApiOperation("根据类型获取消息")
//    public String getFollowupMessage(@ApiParam(name = "type", value = "消息类型,4:待随访消息")
//                                     @RequestParam(value = "type", required = false) Integer type,
//                                     @ApiParam(value = "第几页", defaultValue = "1")
//                                     @RequestParam Integer page,
//                                     @ApiParam(value = "每页几行", defaultValue = "10")
//                                     @RequestParam Integer pagesize) {
//        try {
//            List<SystemMessageDO> list = messageService.getMessageByType(getUID(), type, page, pagesize);
//            return write(200, "获取消息总数成功!", "data", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "getBingQingMessage")
//    @ResponseBody
//    @ApiOperation("获取病情跟踪消息")
//    public String getBingQingMessage(
//            @ApiParam(value = "第几页", defaultValue = "1")
//            @RequestParam Integer page,
//            @ApiParam(value = "每页几行", defaultValue = "10")
//            @RequestParam Integer pagesize) {
//        try {
//            List<SystemMessageDO> list = messageService.getBingQingMessage(getUID(), page, pagesize);
//            return write(200, "获取消息总数成功!", "data", list);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//    @RequestMapping(value = "setMessageOverBySender", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("根据接收者和类型设消息为已处理")
//    public String setMessageOverBySender(@ApiParam(name = "sender", value = "发送者")
//                                         @RequestParam(value = "sender") String sender,
//                                         @ApiParam(name = "type", value = "消息类型")
//                                         @RequestParam(value = "type") Integer type) {
//        try {
//            messageService.setMessageOverBySender(sender, type);
//            return write(200, "更新成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
}

+ 0 - 23
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPlanTemplateDao.java

@ -1,23 +0,0 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPlanTemplateDO;
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 RehabilitationPlanTemplateDao extends PagingAndSortingRepository<RehabilitationPlanTemplateDO, String>, JpaSpecificationExecutor<RehabilitationPlanTemplateDO> {
    @Query("select t from RehabilitationPlanTemplateDO t where (t.adminTeamCode = ?1 or t.adminTeamCode is null) and t.del = 1 ORDER BY t.adminTeamCode,t.createTime DESC ")
    List<RehabilitationPlanTemplateDO> findByAdminTeamCode(Long adminTeamCode);
    @Modifying
    @Query("update RehabilitationPlanTemplateDO t set t.del = 0 where t.id = ?1")
    void updateDelById(String id);
    @Modifying
    @Query("delete RehabilitationPlanTemplateDO t  where t.id = ?1")
    void delete(String id);
}

+ 0 - 18
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationTemplateDetailDao.java

@ -1,18 +0,0 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationTemplateDetailDO;
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 RehabilitationTemplateDetailDao extends PagingAndSortingRepository<RehabilitationTemplateDetailDO, Long>, JpaSpecificationExecutor<RehabilitationTemplateDetailDO> {
    List<RehabilitationTemplateDetailDO> findTemplateDetailByTemplateId(String templateId);
    void deleteByTemplateId(String templateId);
    @Query("SELECT r.hospitalServiceItemId FROM RehabilitationTemplateDetailDO r where r.templateId = ?1")
    List<String> findHospitalServiceItemIdByTemplateId(String templateId);
}

+ 28 - 32
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/PatientRecordService.java

@ -1,13 +1,11 @@
package com.yihu.jw.hospital.module.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.DmHospitalDO;
import com.yihu.jw.entity.patient.PatientEvent;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.jw.service.JwArchivesService;
import com.yihu.jw.jw.service.JwSmjkService;
import com.yihu.jw.hospital.module.jw.service.JwArchivesService;
import com.yihu.jw.hospital.module.jw.service.JwSmjkService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.PatientEventDao;
import com.yihu.jw.patient.service.BasePatientService;
@ -20,7 +18,6 @@ import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@ -33,7 +30,6 @@ import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
@ -602,32 +598,32 @@ public class PatientRecordService {
        return re;
    }
    /**
     * 根据身份证号换取居民请求秘钥
     *
     * @param idcard
     * @return
     */
    public com.alibaba.fastjson.JSONObject getPatientAccetokenByIdcard(String idcard) throws Exception {
        BasePatientDO patient = patientService.findInfoByIdCard(idcard);
        if (patient == null) {
            if (patientService.addPaitentByIdcard(idcard) == null) {
                throw new Exception("该身份证查询不到居民");
            }
            List<BasePatientDO>  patientList = patientDao.getPatientByIdcardOrSsc(idcard);//重新获取该患者信息
            patient = patientList.get(0);
        }
        if (null != patient) {
            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("patient_" + uuid, idcard, 3600, TimeUnit.SECONDS);
            com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
            result.put("patientCode", uuid);
            result.put("create_time", DateUtil.dateToStrLong(new Date()));
            result.put("expires_in", 3600);
            return result;
        }
        return null;
    }
//    /**
//     * 根据身份证号换取居民请求秘钥
//     *
//     * @param idcard
//     * @return
//     */
//    public com.alibaba.fastjson.JSONObject getPatientAccetokenByIdcard(String idcard) throws Exception {
//        BasePatientDO patient = patientService.findInfoByIdCard(idcard);
//        if (patient == null) {
//            if (patientService.addPaitentByIdcard(idcard) == null) {
//                throw new Exception("该身份证查询不到居民");
//            }
//            List<BasePatientDO>  patientList = patientDao.getPatientByIdcardOrSsc(idcard);//重新获取该患者信息
//            patient = patientList.get(0);
//        }
//        if (null != patient) {
//            String uuid = UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set("patient_" + uuid, idcard, 3600, TimeUnit.SECONDS);
//            com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
//            result.put("patientCode", uuid);
//            result.put("create_time", DateUtil.dateToStrLong(new Date()));
//            result.put("expires_in", 3600);
//            return result;
//        }
//        return null;
//    }
    /**
     * 根据居民缓存TOKEN换取居民CODE

+ 72 - 73
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java

@ -10,20 +10,19 @@ import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.DmHospitalDO;
import com.yihu.jw.entity.rehabilitation.PatientDischargeDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.PatientDischargeDao;
import com.yihu.jw.hospital.module.specialist.dao.PatientMedicalRecordsRehabilitationDao;
import com.yihu.jw.hospital.module.system.dao.SystemDictDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.system.dao.SystemDictDao;
import com.yihu.jw.util.DoctorAssistantUtil;
import com.yihu.jw.hospital.utils.DoctorAssistantUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
@ -808,77 +807,77 @@ public class RehabilitationInfoService  {
     * @param doctorCode
     * @return
     */
    public JSONObject getPatientByIdcardOrSsc(String patientInfo, Integer type, String doctorCode) {
        //加签列表查询wlyy_patient_discharge表,与type无关。当家签处添加时(即type=1),统一保存type=2的记录
        JSONObject data = new JSONObject();
        List<BasePatientDO> patientList = patientDao.getPatientByIdcardOrSsc(patientInfo);
        BasePatientDO patient = null;
        if(patientList.size() == 0){
            //未找到居民,从健康档案添加居民
            if(type==2){
                patient = patientService.addPaitentByIdcard(patientInfo);
            }
        }else{
            patient = patientList.get(0);
        }
        if(patient==null){
            data.put("status", -1);
            data.put("msg", "未查询到患者");
            return data;
        }
        BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
        //判断是否添加过该居民
        Integer patientDischargeDOS =0;
        if (type==2){//查询下转是否存在该患者:sign_status=1(包括type==null,type==2) 1.6.8后新增未家签的也能添加患者 判断条件(d.type=2 and sign_status=0)
            String sql = "select count(1) from wlyy_patient_discharge d where d.create_user='"+doctorCode+"' and d.idcard='"+patient.getIdcard()+"'and (sign_status=1 and ( ISNULL(d.type) or d.type=2) or (d.type=2 and sign_status=0))";
            patientDischargeDOS = jdbcTemplate.queryForObject(sql,Integer.class);
        }
        else{//查询加签列表是否存在该患者
            String sql = "select count(1) from wlyy_patient_discharge d where d.create_user='"+doctorCode+"' and d.idcard='"+patient.getIdcard()+"'";
            patientDischargeDOS = jdbcTemplate.queryForObject(sql,Integer.class);
        }
        if(patientDischargeDOS > 0){
            data.put("status", -1);
            data.put("msg", "该患者已添加过,请勿重复添加");
            return data;
        }
        PatientDischargeDO patientDischargeDO = new PatientDischargeDO();
        patientDischargeDO.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
        patientDischargeDO.setType(2);//统一保存为2
        patientDischargeDO.setPatient(patient.getId());
        patientDischargeDO.setName(patient.getName());
        patientDischargeDO.setIdcard(patient.getIdcard());
        patientDischargeDO.setSsc(patient.getSsc());
        patientDischargeDO.setAddress(patient.getAddress());
        patientDischargeDO.setCreateUser(doctorCode);
        patientDischargeDO.setCreateUserName(doctor.getName());
        patientDischargeDO.setCreateTime(new Date());
        //判断是否家签  修改
        SignFamily signFamily = signFamilyDao.getExpensesSignByIdcard(patient.getIdcard());
        if(signFamily != null ) {
            patientDischargeDO.setSignStatus(1);
            patientDischargeDO.setHospital(signFamily.getHospital());
            patientDischargeDO.setHospitalName(signFamily.getHospitalName());
            patientDischargeDao.save(patientDischargeDO);
        }else {
            patientDischargeDO.setSignStatus(0);
//            if (type == 1){//添加签约患者加签列表
            patientDischargeDao.save(patientDischargeDO);
//            }else if(type == 2) {
//                patientDischargeDao.save(patientDischargeDO);
//                data.put("status", -1);
//                data.put("msg", "该患者未家签,请家签后重试");
//                return data;
//    public JSONObject getPatientByIdcardOrSsc(String patientInfo, Integer type, String doctorCode) {
//        //加签列表查询wlyy_patient_discharge表,与type无关。当家签处添加时(即type=1),统一保存type=2的记录
//        JSONObject data = new JSONObject();
//        List<BasePatientDO> patientList = patientDao.getPatientByIdcardOrSsc(patientInfo);
//        BasePatientDO patient = null;
//        if(patientList.size() == 0){
//            //未找到居民,从健康档案添加居民
//            if(type==2){
//                patient = patientService.addPaitentByIdcard(patientInfo);
//            }
        }
        data.put("status", 200);
        data.put("data", patientDischargeDO);
        return data;
    }
//        }else{
//            patient = patientList.get(0);
//        }
//
//        if(patient==null){
//            data.put("status", -1);
//            data.put("msg", "未查询到患者");
//            return data;
//        }
//
//        BaseDoctorDO doctor = doctorDao.findById(doctorCode).orElse(null);
//        //判断是否添加过该居民
//        Integer patientDischargeDOS =0;
//        if (type==2){//查询下转是否存在该患者:sign_status=1(包括type==null,type==2) 1.6.8后新增未家签的也能添加患者 判断条件(d.type=2 and sign_status=0)
//            String sql = "select count(1) from wlyy_patient_discharge d where d.create_user='"+doctorCode+"' and d.idcard='"+patient.getIdcard()+"'and (sign_status=1 and ( ISNULL(d.type) or d.type=2) or (d.type=2 and sign_status=0))";
//            patientDischargeDOS = jdbcTemplate.queryForObject(sql,Integer.class);
//        }
//        else{//查询加签列表是否存在该患者
//            String sql = "select count(1) from wlyy_patient_discharge d where d.create_user='"+doctorCode+"' and d.idcard='"+patient.getIdcard()+"'";
//            patientDischargeDOS = jdbcTemplate.queryForObject(sql,Integer.class);
//        }
//        if(patientDischargeDOS > 0){
//            data.put("status", -1);
//            data.put("msg", "该患者已添加过,请勿重复添加");
//            return data;
//        }
//
//        PatientDischargeDO patientDischargeDO = new PatientDischargeDO();
//        patientDischargeDO.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
//        patientDischargeDO.setType(2);//统一保存为2
//        patientDischargeDO.setPatient(patient.getId());
//        patientDischargeDO.setName(patient.getName());
//        patientDischargeDO.setIdcard(patient.getIdcard());
//        patientDischargeDO.setSsc(patient.getSsc());
//        patientDischargeDO.setAddress(patient.getAddress());
//        patientDischargeDO.setCreateUser(doctorCode);
//        patientDischargeDO.setCreateUserName(doctor.getName());
//        patientDischargeDO.setCreateTime(new Date());
//        //判断是否家签  修改
//        SignFamily signFamily = signFamilyDao.getExpensesSignByIdcard(patient.getIdcard());
//        if(signFamily != null ) {
//            patientDischargeDO.setSignStatus(1);
//            patientDischargeDO.setHospital(signFamily.getHospital());
//            patientDischargeDO.setHospitalName(signFamily.getHospitalName());
//            patientDischargeDao.save(patientDischargeDO);
//        }else {
//            patientDischargeDO.setSignStatus(0);
////            if (type == 1){//添加签约患者加签列表
//            patientDischargeDao.save(patientDischargeDO);
////            }else if(type == 2) {
////                patientDischargeDao.save(patientDischargeDO);
////                data.put("status", -1);
////                data.put("msg", "该患者未家签,请家签后重试");
////                return data;
////            }
//        }
//        data.put("status", 200);
//        data.put("data", patientDischargeDO);
//
//        return data;
//    }
    public JSONObject getUnm(String doctor,String patient){
        String sqlMe = "select d.id,d.plan_id as planId,i.code,i.name,p.patient,d.frequency_code from wlyy_specialist.wlyy_rehabilitation_plan_detail d \n" +

+ 2 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java

@ -9,6 +9,8 @@ import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.disease.dao.RehabilitationPlanTemplateDao;
import com.yihu.jw.hospital.disease.dao.RehabilitationTemplateDetailDao;
import com.yihu.jw.hospital.module.rehabilitation.dao.*;
import com.yihu.jw.hospital.module.rehabilitation.vo.TemplateDetailVo;
import com.yihu.jw.hospital.module.specialist.service.SpecialistHospitalServiceItemService;

+ 88 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/controller/DoorCommentController.java

@ -0,0 +1,88 @@
package com.yihu.jw.hospital.module.score.controller;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.hospital.module.door.service.WlyyDoorCommentService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by wangpeiqiang on 2019/3/16.
 * 居民端-评分接口.
 */
@RestController
@RequestMapping(value = "/patient/door_comment")
@Api(description = "居民端-评分")
public class DoorCommentController extends EnvelopRestEndpoint {
    @Autowired
    WlyyDoorCommentService doorCommentService;
    /**
     * 参数:
     * orderId: 4028f8f68b216198018b22bcfcbb018f
     * professionalSkill: 100
     * serveAttitude: 100
     * serveEfficiency: 100
     * description: 1
     * isAnonymous: 0
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加居民评分")
    public String add(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "professionalSkill", value = "专业能力", required = false) @RequestParam(value = "professionalSkill", required = false) Integer professionalSkill,
            @ApiParam(name = "serveAttitude", value = "服务态度", required = false) @RequestParam(value = "serveAttitude", required = false) Integer serveAttitude,
            @ApiParam(name = "serveEfficiency", value = "服务效率", required = false) @RequestParam(value = "serveEfficiency", required = false) Integer serveEfficiency,
            @ApiParam(name = "description", value = "服务描述或建议", required = false) @RequestParam(value = "description", required = false) String description,
            @ApiParam(name = "isAnonymous", value = "是否匿名", required = false) @RequestParam(value = "isAnonymous", required = false) Integer isAnonymous
    ){
        try {
            if(orderId==null){
                return "工单id不能为空";
            }
            String dc = doorCommentService.add(getUID(), orderId, professionalSkill,serveAttitude,serveEfficiency,description,isAnonymous);
            if("-1".equals(dc)){
                return error(-2,"评分失败");
            }
            return write(200,"评分成功","data",dc);
        } catch (Exception e) {
            error(e);
            return error(-1,"评分失败");
        }
    }
    /**
     * 根据医生code查询居民评价详情
     *
     * @return
     */
    @RequestMapping(value = "/commentDetail", method = RequestMethod.GET)
    @ApiOperation("查询居民评价详情")
    public String commentDetail(
            @ApiParam(name = "patient", value = "居民code", required = false)
            @RequestParam(value = "patient", required = false)String patient,
            @ApiParam(name = "orderId", value = "工单id", required = true)
            @RequestParam(value = "orderId", required = true) String orderId
    ){
        try {
            if(StringUtils.isEmpty(patient)){
                patient = getUID();
            }
            JSONObject result = doorCommentService.commentDetail(patient,orderId);
            return write(200, "请求成功!","data",result);
        }catch (Exception e){
            error(e);
            return error(-1, "请求失败");
        }
    }
}

+ 124 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/service/DoorCommentService.java

@ -0,0 +1,124 @@
package com.yihu.jw.hospital.module.score.service;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorCommentDO;
import com.yihu.jw.entity.door.WlyyDoorCommentDoctorDO;
import com.yihu.jw.entity.door.WlyyDoorDoctorDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.entity.message.WlyyDynamicMessages;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorCommentDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorCommentDoctorDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorDoctorDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.message.dao.WlyyDynamicMessagesDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * Created by wangpeiqiang on 2019/3/16.
 * 居民端-评分
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DoorCommentService extends EnvelopRestEndpoint {
    @Autowired
    BasePatientDao patientDao;
    @Autowired
    WlyyDoorCommentDao doorCommentDao;
    @Autowired
    WlyyDoorCommentDoctorDao doorCommentDoctorDao;
    @Autowired
    WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    WlyyDoorDoctorDao wlyyDoorDoctorDao;
    @Autowired
    WlyyDynamicMessagesDao dynamicMessagesDao;
    public String add(String patientCode,String orderId, Integer professionalSkill,Integer serveAttitude,Integer serveEfficiency,String description,Integer isAnonymous){
        BasePatientDO patient =patientDao.findById(patientCode).orElse(null);
        WlyyDoorCommentDO doorComment = new WlyyDoorCommentDO();
        BigDecimal evaluateSplit = BigDecimal.ZERO;
        BigDecimal num = new BigDecimal("3");
        //计算三项评分平均分
        evaluateSplit = evaluateSplit.add(
                (new BigDecimal(professionalSkill).add(new BigDecimal(serveAttitude)).add(new BigDecimal(serveEfficiency))).divide(num,2,BigDecimal.ROUND_HALF_UP)
        );
        doorComment.setOrderId(orderId);
        doorComment.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
        doorComment.setProfessionalSkill(professionalSkill);
        doorComment.setServeAttitude(serveAttitude);
        doorComment.setServeEfficiency(serveEfficiency);
        doorComment.setEvaluateSplit(evaluateSplit);
        doorComment.setIsAnonymous(isAnonymous);
        doorComment.setDescription(description);
        doorComment.setPatient(patientCode);
        doorComment.setCreateUser(patientCode);
        doorComment.setCreateUserName(patient.getName());
        doorComment.setCreateTime(new Date());
        doorCommentDao.save(doorComment);
        //更新工单状态
        WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO =this.doorCommentDoctorDao.selectOrder(orderId);
        wlyyDoorServiceOrderDO.setStatus(6);
        wlyyDoorServiceOrderDO.setCompleteTime(new Date());
        wlyyDoorServiceOrderDO.setUpdateUser(patientCode);
        wlyyDoorServiceOrderDO.setUpdateUserName(patient.getName());
        wlyyDoorServiceOrderDO.setUpdateTime(new Date());
        wlyyDoorServiceOrderDao.save(wlyyDoorServiceOrderDO);
        //门户页实时动态展示,完成上门服务
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = simpleDateFormat.format(new Date());
            WlyyDynamicMessages dynamicMessages = new WlyyDynamicMessages();
            dynamicMessages.setCreateTime(str);//当前时间
            dynamicMessages.setName(patient.getName());//居民姓名
            String str1 = "居民完成上门服务工单评价";
            dynamicMessages.setCode(patient.getId());
            dynamicMessages.setCodeType("2");
            dynamicMessages.setResult(str1);
            dynamicMessages.setAddress(patient.getAddress());//居民地址
            dynamicMessagesDao.save(dynamicMessages);
        }catch (Exception e){
            e.printStackTrace();
        }
        List<WlyyDoorDoctorDO> wlyyDoorDoctorDOList =this.wlyyDoorDoctorDao.findByOrderId(orderId);
        for(WlyyDoorDoctorDO wlyyDoorDoctorDO:wlyyDoorDoctorDOList) {
            WlyyDoorCommentDoctorDO doorCommentDoctor = new WlyyDoorCommentDoctorDO();
            doorCommentDoctor.setOrderId(orderId);
            doorCommentDoctor.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
            doorCommentDoctor.setDoctorCode(wlyyDoorDoctorDO.getDoctor());
            doorCommentDoctor.setProfessionalSkill(professionalSkill);
            doorCommentDoctor.setServeAttitude(serveAttitude);
            doorCommentDoctor.setServeEfficiency(serveEfficiency);
            doorCommentDoctor.setEvaluateSplit(evaluateSplit);
            doorCommentDoctor.setIsAnonymous(isAnonymous);
            doorCommentDoctor.setDescription(description);
            doorCommentDoctor.setPatient(patientCode);
            doorCommentDoctor.setCreateUser(patientCode);
            doorCommentDoctor.setCreateUserName(patient.getName());
            doorCommentDoctor.setCreateTime(new Date());
            doorCommentDoctorDao.save(doorCommentDoctor);
        }
        return"1";
    }
    public JSONObject commentDetail(String patient,String orderId)throws Exception{
        JSONObject result = new JSONObject();
        WlyyDoorCommentDO commentDetail = doorCommentDao.selectCommentDoctor(patient,orderId);
        result.put("commentDetail",commentDetail);
        return result;
    }
}

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

@ -1,4 +1,4 @@
package com.yihu.jw.system.dao;
package com.yihu.jw.hospital.module.system.dao;
import com.yihu.jw.entity.base.system.SystemDictDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

+ 2 - 39
business/base-service/src/main/java/com/yihu/jw/system/service/SystemDictService.java

@ -1,17 +1,13 @@
package com.yihu.jw.system.service;
package com.yihu.jw.hospital.module.system.service;
import com.yihu.jw.entity.base.system.SystemDictDO;
import com.yihu.jw.system.dao.SystemDictDao;
import com.yihu.jw.hospital.module.system.dao.SystemDictDao;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ -112,37 +108,4 @@ public class SystemDictService {
        return systemDictDao.delete(dictName);
    }
    /**
     * 保存健康教育设置字典
     * @param dictName
     * @param isComment
     */
//    public void save(String dictName, String isComment) {
//        SystemDict systemDict = new SystemDict();
//        systemDict.setDictName(dictName);
//        systemDict.setCode(isComment);
//        if (isComment.equals("0")) {
//            systemDict.setValue("不允许");
//        } else if (isComment.equals("1")) {
//            systemDict.setValue("允许");
//        }
//        systemDict.setSort(1);
//        systemDictDao.save(systemDict);
//    }
//    public void saveJkeduNotDisturb(String dictName, String json) {
//        JSONArray jsonArray = new JSONArray(json);
//        List<SystemDict> list = new ArrayList<>();
//        int code = 1;
//        for (Object object : jsonArray){
//            SystemDict systemDict = new SystemDict();
//            systemDict.setDictName(dictName);
//            systemDict.setCode(code + "");
//            systemDict.setValue(((JSONObject)object).toString());
//            systemDict.setSort(code);
//            list.add(systemDict);
//            code ++;
//        }
//        systemDictDao.save(list);
//    }
}

+ 223 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/utils/CommonUtil.java

@ -0,0 +1,223 @@
//package com.yihu.jw.hospital.utils;
//
//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.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.util.EntityUtils;
//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.stereotype.Component;
//import org.springframework.web.multipart.MultipartFile;
//
//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("${fastDFS.fastdfs_file_url}")
//    private String fastdfs_file_url;
//
//    @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 {
//        // 文件保存的临时路径
//        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;
//    }
//
//
//    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 copyTempImage(String files) throws Exception {
//        String tempPath = SystemConfEntity.getInstance().getTempPath() + File.separator;
//        // 文件保存的临时路径
//        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();
//                    }
//                }
//            }
//        }
//        System.out.println("文件地址:"+fileUrls);
//        return fileUrls;
//
//    }
//}

+ 3 - 4
common/common-util/src/main/java/com/yihu/jw/util/DoctorAssistantUtil.java

@ -1,10 +1,9 @@
package com.yihu.jw.util;
package com.yihu.jw.hospital.utils;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
@ -17,9 +16,9 @@ import java.util.List;
@Component
public class DoctorAssistantUtil {
    @Value("${doctorAssistant.api}")
//    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
//    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;