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

评价和bug修复

suqinyi 1 éve
szülő
commit
3174120f05
17 módosított fájl, 2935 hozzáadás és 159 törlés
  1. 114 47
      business/base-service/src/main/java/com/yihu/jw/hospital/message/service/SystemMessageService.java
  2. 22 0
      business/base-service/src/main/java/com/yihu/jw/message/dao/WlyyDynamicMessagesDao.java
  3. 113 0
      business/base-service/src/main/java/com/yihu/jw/message/service/MessageService.java
  4. 3 1
      business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultDao.java
  5. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/message/WlyyDynamicMessages.java
  6. 236 2
      common/common-util/src/main/java/com/yihu/jw/util/common/CommonUtil.java
  7. 22 21
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/consult/DoctorConsultController.java
  8. 57 12
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java
  9. 1 1
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/consult/ConsultTeamService.java
  10. 1856 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/ConsultController.java
  11. 23 18
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  12. 93 56
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  13. 4 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/WlyyDoorCommentDoctorDao.java
  14. 102 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorCommentService.java
  15. 0 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java
  16. 79 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/controller/DoorCommentController.java
  17. 124 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/score/service/DoorCommentService.java

+ 114 - 47
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,12 @@ 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.mysql.query.BaseJpaService;
import com.yihu.jw.system.service.SystemDictService;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.jw.utils.YkyySMSService;
import com.yihu.jw.utils.hibernate.HibenateUtils;
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 +30,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 +40,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;
@ -67,11 +69,12 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
    /**
     * 新增线上就诊消息
     *
     * @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 +85,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 +111,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 +125,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 +138,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 +152,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 +209,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 +236,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 +272,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 +307,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 +315,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,11 +325,11 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
            specialistDynamicMessages.setResult(result);
            specialistDynamicMessages.setName(patientName);
            specialistDynamicMessages.setCode(patient.getId());
            if(doctor!=null){
            if (doctor != null) {
//                specialistDynamicMessages.setDoctor(doctor.getCode());
//                specialistDynamicMessages.setHospital(doctor.getHospital());
                doctorName = doctor.getName();
            }else if(signFamily!=null){
            } else if (signFamily != null) {
                specialistDynamicMessages.setDoctor(signFamily.getDoctor());
                specialistDynamicMessages.setHospital(signFamily.getHospital());
                doctorName = signFamily.getDoctorName();
@ -333,16 +341,16 @@ public class SystemMessageService extends BaseJpaService<SystemMessageDO,SystemM
            specialistDynamicMessages.setCreateTime(DateUtil.getStringDate());
            specialistDynamicMessages.setType(type);
            Map<String,String> copywritingMap = systemDictService.getDictMap("DynamicMessages"+type);
            Map<String, String> copywritingMap = systemDictService.getDictMap("DynamicMessages" + type);
            //获取文案模板
            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 +359,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;
    }
}

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

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

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

+ 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消息发送异常!");

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

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

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

@ -41,6 +41,9 @@ import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.utils.Clock;
import java.text.DecimalFormat;
@ -3357,24 +3360,24 @@ public class ConsultTeamService extends ConsultService {
//        return result;
//    }
//    public JSONObject updateIMMsg(String sessionId, String sessionType, String msgId, String content) {
//        JSONObject result = new JSONObject();
//        if (StringUtils.isEmpty(sessionId) || StringUtils.isEmpty(sessionType) || StringUtils.isEmpty(msgId) || StringUtils.isEmpty(content)) {
//            result.put("data", "参数【sessionId,sessionType,msgId,content】不可为空!");
//            result.put("status", -1);
//            return result;
//        }
//        JSONObject contentJsonObj = null;
//        try {
//            contentJsonObj = new JSONObject(content);
//        } catch (Exception e) {
//            result.put("status", -1);
//            result.put("data", "【content】必须是json格式:" + e.getMessage());
//            return result;
//        }
//        String response = ImUtill.updateMessage(sessionId, sessionType, msgId, content);
//        return new JSONObject(response);
//    }
    public 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();
@ -3479,4 +3482,6 @@ public class ConsultTeamService extends ConsultService {
//        return result;
//    }
}

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

@ -175,6 +175,27 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    }
    /**
     * 调度平台修改预约信息
     * 参数:{"orderId":"4028f8f68b216198018b22bcfcbb018f","patientName":"黄小蕾","patientCode":"0fab4dd67e074e16ac86db6b6c15233e","number":"26669809","serveAddress":"明丰财富中心","serveTown":"思明区","phone":"15200000001","serviceStatus":"1","patientExpectedServeTime":"2023-10-12 15:00-15:30","sex":"男","age":43,"doctor":null,"status":1,"expectedDoctor":null,"serveDesc":"工程师测试1"}
     */
    @PostMapping(value = "updateOrderCardInfo")
    @ApiOperation(value = "更新预约简要信息")
    public Envelop updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("保存成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping("/getDispatchOrderSwitch")
    @ApiOperation(value = "获取医生分派订单开关状态")
    public Envelop getDispatchOrderSwitch(
@ -289,6 +310,65 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    }
    /**
     * 参数
     * orderId: 4028f8f68b216198018b22bcfcbb018f
     * dispatcher: 361aef4891de492cb0e6a47cf9fe31f3
     * dispatcherName: 黄琴
     */
    @PostMapping(value = "saveLastDispatcher")
    @ApiOperation(value = "保存最后一个回复内容的调度员到工单")
    public Envelop saveLastDispatcher(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "dispatcher", value = "调度员code", required = true) @RequestParam String dispatcher,
            @ApiParam(name = "dispatcherName", value = "调度员姓名", required = true) @RequestParam String dispatcherName
    ) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.saveLastDispatcher(orderId, dispatcher, dispatcherName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("保存成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    /**
     * 参数:
     * orderId: 4028f8f68b216198018b22bcfcbb018f
     * remark: 111111
     * dispatcher: 361aef4891de492cb0e6a47cf9fe31f3
     * dispathcherName: 黄琴
     * doctor: 215d03f7a6b84361851f6af8a6cd9121
     * doctorName: 周丹琪
     * doctorJobName: 医师
     */
    @PostMapping(value = "sendOrderToDoctor")
    @ApiOperation(value = "调度员给医生派单")
    public Envelop sendOrderToDoctor(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "调度员备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(name = "dispatcher", value = "调度员code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "dispathcherName", value = "调度员姓名") @RequestParam(value = "dispathcherName", required = true) String dispathcherName,
            @ApiParam(name = "doctor", value = "医生code") @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = true) String doctorName,
            @ApiParam(name = "doctorJobName", value = "医生职称") @RequestParam(value = "doctorJobName", required = true) String doctorJobName) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.sendOrderToDoctor(orderId, remark, dispatcher, dispathcherName, doctor, doctorName, doctorJobName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("派单成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @GetMapping("/topStatusBarNum")
    @ApiOperation(value = "顶部状态栏订单分类tab")
    public Envelop topStatusBarNum(
@ -304,6 +384,12 @@ public class DoorOrderController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 参数:
     * orderId: 4028f8f68b216198018b22bcfcbb018f
     * doctor: 215d03f7a6b84361851f6af8a6cd9121
     * level: 3
     */
    @GetMapping("getByOrderId")
    @ApiOperation(value = "根据工单id获取相应的工单,如果为空,则获取该医生当前最新一条的工单")
    public Envelop getByOrderId(
@ -329,6 +415,13 @@ public class DoorOrderController extends EnvelopRestEndpoint {
        }
    }
    /**
     * 参数:
     * orderId: 4028f8f68b216198018b22bcfcbb018f
     * jobCode: 95b0d29e5f0a11e68344fa163e8aee56
     * jobCodeName: 医师
     * hospitalLevel: 3
     */
    @PostMapping("acceptOrder")
    @ApiOperation(value = "接单")
    public Envelop acceptOrder(
@ -679,7 +772,6 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    @PostMapping("updateDoctorInfoNoPatient")
    @ApiOperation(value = "修改保存服务医生(不用经过居民同意)")
    public Envelop updateDoctorInfoNoPatient(
            @ApiParam(value = "jsonData", name = "jsonData")
            @RequestParam(value = "jsonData", required = false) String jsonData) {
@ -824,28 +916,6 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    }
    @PostMapping(value = "sendOrderToDoctor")
    @ApiOperation(value = "调度员给医生派单")
    public Envelop sendOrderToDoctor(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "调度员备注") @RequestParam(value = "remark", required = false) String remark,
            @ApiParam(name = "dispatcher", value = "调度员code") @RequestParam(value = "dispatcher", required = true) String dispatcher,
            @ApiParam(name = "dispathcherName", value = "调度员姓名") @RequestParam(value = "dispathcherName", required = true) String dispathcherName,
            @ApiParam(name = "doctor", value = "医生code") @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(value = "doctorName", required = true) String doctorName,
            @ApiParam(name = "doctorJobName", value = "医生职称") @RequestParam(value = "doctorJobName", required = true) String doctorJobName) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.sendOrderToDoctor(orderId, remark, dispatcher, dispathcherName, doctor, doctorName, doctorJobName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("派单成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
@ -907,42 +977,9 @@ public class DoorOrderController extends EnvelopRestEndpoint {
    }
    @PostMapping(value = "saveLastDispatcher")
    @ApiOperation(value = "保存最后一个回复内容的调度员到工单")
    public Envelop saveLastDispatcher(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "dispatcher", value = "调度员code", required = true) @RequestParam String dispatcher,
            @ApiParam(name = "dispatcherName", value = "调度员姓名", required = true) @RequestParam String dispatcherName
    ) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.saveLastDispatcher(orderId, dispatcher, dispatcherName);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("保存成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "updateOrderCardInfo")
    @ApiOperation(value = "更新预约简要信息")
    public Envelop updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            JSONObject result = wlyyDoorServiceOrderService.updateOrderCardInfo(jsonData);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return failed(result.getString(ResponseContant.resultMsg));
            }
            return success("保存成功", result.get(ResponseContant.resultMsg));
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
    @PostMapping(value = "updateServiceStatus")
    @ApiOperation(value = "更新预约服务项目类型")

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

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

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

@ -1688,7 +1688,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"));

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

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