Browse Source

Merge branch 'dev' of yeshijie/wlyy2.0 into dev

叶仕杰 3 năm trước cách đây
mục cha
commit
d0110d33f2

+ 2 - 137
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -1,10 +1,8 @@
package com.yihu.jw.im.service;
import ch.qos.logback.core.joran.conditional.ElseAction;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibm.mq.jmqi.MQPD;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
@ -56,8 +54,6 @@ import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import com.yihu.jw.wechat.service.WxTemplateService;
import com.ylzinfo.onepay.sdk.domain.ext.WaitPayDetailVO;
import com.ylzinfo.onepay.sdk.utils.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -68,7 +64,6 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.Element;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@ -488,22 +483,6 @@ public class ImService {
		String[] arr = null;
		if (type == 3) {//语音文件处理
//			if(!StringUtils.isEmpty(wechat_appid)){
//				String path = fetchWxVoices(wechat_appid);
//				JSONObject obj = new JSONObject();
//				// 将临时语音拷贝到正式存储路径下
//				if (org.apache.commons.lang3.StringUtils.isNotEmpty(path)) {
//					if("xm_ihealth_wx".equals(wechat_appid)){
//						Map<String, Object> map = fileUploadService.uploadImg(file);
//						uploadVO.setFullUri(map.get("accessory").toString());
//					}else{
//						content = fileUtil.copyTempVoice(path,fastdfs_file_url);
//					}
//					obj.put("path", path);
//					obj.put("times", times);
//					content = obj.toString();
//				}
//			}
			ConsultTeamLogDo log = new ConsultTeamLogDo();
			log.setConsult(consult);
			log.setContent(content);
@ -513,15 +492,7 @@ public class ImService {
			logs.add(log);
		} else if (type == 2) {
//			// 图片消息
//			content = fetchWxImages(wechat_appid);
//			// 将临时图片拷贝到正式存储路径下
//			if (org.apache.commons.lang3.StringUtils.isNotEmpty(content)) {
//				content = fileUtil.copyTempImage(content,upload_temp_path);
//			}
//			if (org.apache.commons.lang3.StringUtils.isEmpty(content)) {
//				throw new Exception("图片上传失败!");
////				return error(-1, "图片上传失败!");
//			}
			String[] images = content.split(",");
			for (String image : images) {
				ConsultTeamLogDo log = new ConsultTeamLogDo();
@ -549,86 +520,14 @@ public class ImService {
		List<String> failed = new ArrayList<>();
		for (ConsultTeamLogDo log : logs) {
//                String response = ImUtill.sendTopicIM(getUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent());
			String response = imUtil.sendTopicIM(patientcode, patient.getName(), consult, String.valueOf(log.getType()), log.getContent(),null,patient.getName(),Integer.parseInt(IdCardUtil.getSexForIdcard_new(patient.getIdcard())), IdCardUtil.getAgeForIdcard(patient.getIdcard()));
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(response)) {
				JSONObject resObj = JSON.parseObject(response);
				if (resObj.getInteger("status")  == -1) {
					throw new Exception("追问失败!" + resObj.getString("message"));
//					return invalidUserException(new RuntimeException(resObj.getString("message")), -1, "追问失败!" + resObj.getString("message"));
				}
				failed.add(String.valueOf(resObj.get("data")));
//				try {
//
//					String sql = "";
//					if (consultModel.getType() == 2){
//						//家庭咨询
//						sql = "SELECT t.participant_id FROM " + data_base_name +
//								".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 " + data_base_name +
//								".participants t where t.session_id = '" +
//								patient.getId() + "_" + consultModel.getConsult() + "_" + consultModel.getType() +
//								"' and t.participant_role = 0";
//					}
//					if(org.apache.commons.lang3.StringUtils.isEmpty(sql)){
//						throw new Exception("追问失败!不存在该类型!【type】:" + type);
//						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.getCode())) {
//							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
//							Doctor doctor = doctorDao.findByCode(doctorCode);
//							String doctorOpenID = doctor.getOpenid();
//							if (org.apache.commons.lang3.StringUtils.isNotEmpty(doctorOpenID)) {
//								String title = "";
//								Consult 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 failed;
@ -1072,7 +971,7 @@ public class ImService {
	 * @param ct
	 * @throws Exception
	 */
	private String addLogs(ConsultTeamDo ct) throws Exception {
	public String addLogs(ConsultTeamDo ct) throws Exception {
		List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
		// 添加问题咨询日志
		String content = "";
@ -1687,9 +1586,6 @@ public class ImService {
		evalueContent.put("doctorPhoto",doctor.getPhoto());
		evalueContent.put("consultCode",consult);
//		returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "28", evalueContent.toString());
//		String response = imUtil.sendTopicIM(consultTeam.getDoctor(), doctor.getName(), consult, "28", evalueContent.toString(),null);
//		String response = imUtil.sendImMsg(consultTeam.getDoctor(), doctor.getName(), session_id, "28", evalueContent.toString(),null);
		//保存系统消息服务评价
		systemMsgEvaluation(doctor,patient,cons,consultTeam,consult,wxId);
@ -1722,37 +1618,6 @@ public class ImService {
			throw new RuntimeException(String.valueOf(null==obj.get("message")?"无失败信息":obj.get("message")));
		}
//		//推送给IM文字消息
//		if (endType == 1) {
//			BasePatientDO p = basePatientDao.findById(endOperator);
//			name = p.getName();
//			returnJson = imUtil.sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
//		} else {
//			BaseDoctorDO d = baseDoctorDao.findById(endOperator);
//			name = d.getName();
//			returnJson = imUtil.sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
//		}
//		if (org.apache.commons.lang3.StringUtils.isEmpty(returnJson)) {
//			throw new RuntimeException("send consult finished IM message failed!");
////			throw new Exception("send consult finished IM message failed");
//		} else {
//			JSONObject jo = JSON.parseObject(returnJson);            //设置消息ID
//			consultTeam.setEndMsgId(jo.getInteger("startId") + "");
//			consultTeam.setEndOperator(endOperator);
//			consultTeam.setEndType(endType);
//		}
//		org.json.JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());
//
//		if (group != null) {
//			String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");
//
//			if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
//				throw new Exception("send consult finished IM message failed");
//			}
//		}
		consultTeam.setEndMsgId(obj.getString("id"));
		cons.setEndTime(new Date());
		consultTeam.setEndTime(new Date());

+ 2 - 1
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -758,7 +758,8 @@ public class ImUtil {
	public static final String SESSION_TYPE_EMERGENCY_ASSISTANCE = "20";//紧急救助
	public static final String SESSION_TYPE_DOOR_COACH = "21";//上门辅导(上门预约)
	public static final String SESSION_TYPE_SECURITY_WARN = "22";//安防咨询
	
	public static final String SESSION_TYPE_ONLINE = "23";//在线咨询
	public static final String CONTENT_TYPE_TEXT = "1";
	
	

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

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

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

@ -19,6 +19,7 @@ public class SystemMessageDO extends UuidIdentityEntity {
    /**
     *消息类型 上门服务400开头,生活照料500开头 ,安防监控600开头, 上门辅导700开头,紧急救助800开头
     * 在线咨询 850
     */
    private String type;
    /**

+ 192 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/PatientConsultEndpoint.java

@ -2,11 +2,15 @@ package com.yihu.jw.care.endpoint.consult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.consult.ConsultService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.family.service.WlyyFamilyMemberService;
import com.yihu.jw.hospital.message.service.SystemMessageService;
@ -20,12 +24,14 @@ import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.rm.patient.PatientRequestMapping;
import com.yihu.jw.util.common.FileUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.service.WechatInfoService;
import com.yihu.jw.wlyy.service.WlyyBusinessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -94,7 +100,192 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	private String wechat_appid;
	@Autowired
	private FileUtil fileUtil;
	
	@Autowired
	private ConsultService consultService;
	@GetMapping(value = "isExistsUnfinishedOnline")
	@ApiOperation(value = "查询居民是否存在未结束的在线咨询")
	public Envelop isExistsUnfinishedOnline(
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = false) String doctor,
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = true) String patient)throws Exception {
		try {
			String consultCode = consultService.getUnfinishedConsult(patient, doctor);
			return success("请求成功",consultCode);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "addOnlineConsult")
	@ApiOperation(value = "新增在线咨询")
	public Envelop addOnlineConsult(
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = false) String patient,
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor,
			@ApiParam(name = "symptoms", value = "主述")
			@RequestParam(value = "symptoms",required = false) String symptoms,
			@ApiParam(name = "images", value = "图片")
			@RequestParam(value = "images",required = false) String images,
			@ApiParam(name = "voice", value = "语音")
			@RequestParam(value = "voice",required = false) String voice,
			@ApiParam(name = "type", value = "咨询类型:1专家咨询 14导诊助手 17专家视频咨询")
			@RequestParam(value = "type",required = false) Integer type,
			@ApiParam(name = "source", value = "咨询类型来源")
			@RequestParam(value = "source",required = false) String source)throws Exception{
		System.out.println("symptoms="+symptoms);
		if (type == null) {
			type = 23;
		}
		ConsultTeamDo consult = new ConsultTeamDo();
		// 设置咨询类型:23 在线咨询
		consult.setType(type);
		// 设置主要症状
		consult.setSymptoms(symptoms);
		// 设置咨询图片URL
		consult.setImages(images);
		// 设置咨询语音URL
		consult.setVoice(voice);
		consult.setDoctor(doctor);
		consult.setPatient(patient);
		// 保存到数据库
		synchronized (patient.intern()){//新增同步方法
			JSONObject re = null;
			re = consultService.addTeamConsult(consult, patient,doctor,source);
			//发送系统消息
			SystemMessageDO systemMessageDO = new SystemMessageDO();
			systemMessageDO.setTitle("新增在线咨询");
			systemMessageDO.setType("850");
			systemMessageDO.setReceiver(re.getString("doctor"));
			systemMessageDO.setReceiverName(re.getString("doctorName"));
			systemMessageDO.setRelationCode(re.getString("sessiond_id"));
			systemMessageDO.setSender(re.getString("patient"));
			systemMessageDO.setSenderName(re.getString("patientName"));
			net.sf.json.JSONObject data = new net.sf.json.JSONObject();
			data.put("name",re.getString("patientName"));
			data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
			data.put("gender",IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
			data.put("question",symptoms);
			data.put("type",1);
			systemMessageDO.setData(data.toString());
			consultService.saveMessage(systemMessageDO);
		}
		return success("操作成功", consult);
	}
	@GetMapping(value = "records")
	@ApiOperation(value = "患者咨询记录查询")
	public Envelop records(
			@ApiParam(name = "patient", value = "居民id")
			@RequestParam(value = "patient",required = true) String patient,
			@ApiParam(name = "title", value = "咨询标题关键字")
			@RequestParam(value = "title",required = false) String title,
			@ApiParam(name = "id", value = "咨询ID")
			@RequestParam(value = "id",required = false) String id,
			@ApiParam(name = "type", value = "咨询类型")
			@RequestParam(value = "type",required = true) String type,
			@ApiParam(name = "status", value = "咨询状态:0进行中,1已完成,-1患者取消,-2超时未响应自动关闭")
			@RequestParam(value = "status",required = false) Integer status,
			@ApiParam(name = "page", value = "第几页")
			@RequestParam(value = "page",required = false) int page,
			@ApiParam(name = "pagesize", value = "分页大小")
			@RequestParam(value = "pagesize",required = false) int pagesize,
			@ApiParam(name = "doctorName", value = "医生名字")
			@RequestParam(value = "doctorName",required = false) String doctorName)throws Exception{
		try {
			List<Map<String,Object>>  data = consultService.findConsultRecordByPatient(patient, id,type, page,pagesize, title,status,doctorName);
			Long total = imService.countConsultRecordByPatient(patient, id,type,title);
			JSONObject result = new JSONObject();
			result.put("total",total);
			result.put("list",data);
			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "finish")
	@ApiOperation(value = "居民结束咨询", notes = "居民结束咨询")
	public Envelop finish(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult,
			@ApiParam(name = "patientCode", value = "居民COEE")
			@RequestParam(value = "patientCode",required = false) String patientCode) throws Exception {
		int resutl = consultService.finish(consult,patientCode,1);
		BasePatientDO basePatientDO = basePatientService.findByIdAndDel(patientCode);
		JSONObject msgObj = new JSONObject();
		msgObj.put("msg",basePatientDO.getName()+"结束了咨询");
		msgObj.put("consultcode",consult);
		String jsonStr = "";
		if(1 == resutl){
			jsonStr = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"sender_id\":\""+patientCode+"\",\"sender_name\":\"系统\",\"timestamp\":"+System.currentTimeMillis()+",\"content_type\":7,\"content\":"+msgObj.toString()+",\"business_type\":1}";
		}
		return success(jsonStr);
	}
	@GetMapping(value = "getTopic")
	@ApiOperation(value = "根据咨询CODE获取session_id", notes = "根据咨询CODE获取session_id")
	public Envelop getTopic(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult)throws Exception {
		try {
			return success("请求成功",imService.getTopic(consult));
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = "append")
	@ApiOperation(value = "居民咨询发消息(追问接口)")
	public ListEnvelop append(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult,
			@ApiParam(name = "content", value = "追问内容")
			@RequestParam(value = "content",required = true) String content,
			@ApiParam(name = "type", value = "追问内容类型:1文字,2图片,3语音  ... (im消息类型)")
			@RequestParam(value = "type",required = true) Integer type,
			@ApiParam(name = "times", value = "")
			@RequestParam(value = "times",required = false) Integer times,
			@ApiParam(name = "patientCode", value = "居民CODE")
			@RequestParam(value = "patientCode",required = false) String patientCode) throws Exception {
		try {
			List<String> failed = new ArrayList<>();
			//处理语音文件
			if(3 == type){//语音文件
				String voicepath = imService.fetchWxVoices(wechat_appid);
				logger.info("voice_path:"+voicepath);
				JSONObject obj = new JSONObject();
				String voiceurl = "";
				// 将临时语音拷贝到正式存储路径下
				if (StringUtils.isNotEmpty(voicepath)) {
					voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
					obj.put("path", voiceurl);
					obj.put("times", times);
					content = obj.toString();
				}
			}else if(2 == type){//图片文件
				String imagepath = imService.fetchWxImages(wechat_appid);
				logger.info("image_path:"+imagepath);
				// 将临时语音拷贝到正式存储路径下
				if (StringUtils.isNotEmpty(imagepath)) {
					content = fileUploadService.uploadWxImage(imagepath);
				}
			}else{}
			failed = imService.append(consult,content,type,times,patientCode,wechat_appid);
			return success(failed);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.participants)
	@ApiOperation(value = "获取会话成员")

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

@ -0,0 +1,340 @@
package com.yihu.jw.care.service.consult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamDoctorDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.sms.dao.HospitalSysDictDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static jxl.biff.FormatRecord.logger;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/5/28
 * @Description:
 */
@Service
public class ConsultService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private ImService imService;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    /**
     * 居民结束咨询
     * @param consult 咨询CODE
     * @param endOperator 操作人
     * @param endType 1居民 2医生
     * @return
     */
    public int finish(String consult, String endOperator, int endType) {
        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);
        ConsultDo cons = consultDao.findOne(consult);
        if (consultTeam.getStatus() == 1) {
            return -1;
        }
        String endName = "";
        String endId = "";
        JSONObject obj = new JSONObject();
        //结束咨询才发送推送给IM文字消息
        if (endType == 1) {
            BasePatientDO p = basePatientDao.findById(endOperator);
            endName = p.getName();
            endId = p.getId();
            obj = imUtil.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
        } else {
            BaseDoctorDO d = baseDoctorDao.findById(endOperator);
            if (endOperator.equals("admin")) {
                endId = "system";
                endName = "超时,系统自动";
            } else {
                endId = d.getId();
                endName = d.getName();
            }
            obj = imUtil.endTopics(consultTeam.getDoctor(), endId, endName, consultTeam.getConsult());
        }
        if (obj == null) {
            throw new RuntimeException("IM消息结束异常!");
        }
        if (obj.getInteger("status") == -1) {
            throw new RuntimeException(String.valueOf(null==obj.get("message")?"无失败信息":obj.get("message")));
        }
        consultTeam.setEndMsgId(obj.getString("id"));
        cons.setEndTime(new Date());
        consultTeam.setEndTime(new Date());
        consultTeam.setStatus(1);
        consultDao.save(cons);
        consultTeamDao.save(consultTeam);
        return 1;
    }
    /**
     * 查询患者所有的咨询记录
     * @param patient 患者标识
     * @param id 会话ID(等同IM表topicId)
     * @param type 咨询会话类型
     * @param pagesize 分页大小
     * @param title 标题关键字
     * @param status 状态
     * @param doctorName 医生名字
     * @return
     */
    public List<Map<String,Object>>  findConsultRecordByPatient(String patient, String id,String type, int page,int pagesize, String title,Integer status,String doctorName) {
        String  sql = "SELECT " +
                "a.id AS \"id\"," +
                "a.type AS \"type\"," +
                "a.title AS \"title\"," +
                "a.symptoms AS \"symptoms\","+
                "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\","+
                "b.status AS \"status\"," +
                "b.evaluate AS \"evaluate\"," +
                "d.name AS \"doctorName\"," +
                "d.photo AS \"doctorphoto\"," +
                "d.id AS \"doctorCode\"," +
                "d.job_title_name AS \"jobTitleName\", " +
                "h.dept_name AS \"deptName\", " +
                "h.org_name AS \"hospitalName\", " +
                "a.pay_status AS \"payStatus\", "+
                "a.source AS \"source\" "+
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_doctor d, " +
                "base_doctor_hospital h " +
                "WHERE a.id=b.consult and d.id = h.doctor_code " +
                "AND b.doctor=d.id AND a.patient='"+patient+"' AND a.type in ("+type+")";
        if(!StringUtils.isEmpty(title)){
            title="%"+title+"%";
            sql +=" and a.title like '"+title+"'";
        }
        if(!StringUtils.isEmpty(doctorName)){
            title="%"+doctorName+"%";
            sql +=" and d.name like '"+title+"'";
        }
        //咨询状态
        if(status != null && status != 0){
            sql +=" and b.status ="+status;
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql += " ORDER BY a.czrq desc ";
        logger.info("sql="+sql);
        List<Map<String,Object>> result = hibenateUtils.createSQLQuery(sql,page,pagesize);
        return result;
    }
    /**
     * 保存系统消息&发送IM外层刷新事件的消息
     * @param systemMessageDO
     * @throws Exception
     */
    public void saveMessage(SystemMessageDO systemMessageDO) throws Exception{
        //发送系统消息
        systemMessageDO.setIsRead("0");
        systemMessageDO.setDel("1");
        systemMessageDO.setCreateTime(new Date());
        systemMessageDao.save(systemMessageDO);
        //发型IM外层消息
        JSONObject object = new JSONObject();
        object.put("socket_sms_type",11);//系统消息刷新事件
        object.put("relation_code",systemMessageDO.getType());
        imService.sendWaiSocketMessage(systemMessageDO.getSender(),systemMessageDO.getReceiver(),object.toString(),"1");
    }
    /**
     * 患者端
     * 发起在线咨询
     * @param ct      在线咨询对象
     * @param patient 患者标识
     * @return
     * @throws Exception
     */
    public JSONObject addTeamConsult(ConsultTeamDo ct, String patient, String doctor, String source) throws Exception {
        JSONObject re = new JSONObject();
        boolean boo = StringUtils.isEmpty(getUnfinishedConsult(patient, doctor));
        logger.info("boo"+boo);
        WlyyHospitalSysDictDO sysDictDO = hospitalSysDictDao.findById("consultClose");
        boolean flag = false;
        if (sysDictDO!=null){
            if (sysDictDO.getDictCode().equalsIgnoreCase("1")){
                flag = true;
            }
        }
        if (!flag){
            if (!StringUtils.isEmpty(getUnfinishedConsult(patient, doctor))) {
                throw new RuntimeException("居民还有未结束的在线咨询!");
            }
        }
        JSONObject users = new JSONObject();
        users.put(doctor,0);
        // 设置医生名称
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        // 设置患者信息
        ct.setPatient(patient);
        // 查询患者信息
        BasePatientDO tempPatient = basePatientDao.findById(patient);
        // 设置患者姓名
        ct.setName(tempPatient.getName());
        // 设置患者生日
        ct.setBirthday(tempPatient.getBirthday());
        //新增性别
        ct.setSex(tempPatient.getSex());
        // 设置患者头像
        ct.setPhoto(tempPatient.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        ct.setEvaluate(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 添加咨询记录
        ConsultDo consult = imService.addConsult(ct.getPatient(), "在线咨询", ct.getSymptoms(), ct.getImages(), ct.getType(),source);
//		// 设置关联指导
//		consult.setGuidance(ct.getGuidance());
        // 设置咨询标识
        ct.setConsult(consult.getId());
        // 设置医生CODE
        ct.setDoctor(doctor);
        // 设置医生名称
        ct.setDoctorName(baseDoctorDO.getName());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", tempPatient.getName() + "申请在线咨询");
        jsonObject.put("content",ct.getSymptoms());
        jsonObject.put("age", DateUtil.getAgeForIdcard(tempPatient.getIdcard()));
        jsonObject.put("sex",tempPatient.getSex());
        jsonObject.put("name",tempPatient.getName());
        //推送给IM去创建议题,取得成员消息
        JSONObject messages = imUtil.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), jsonObject.toJSONString(), consult.getImages(), doctor);
        users.put(patient, 0);
        users.put(doctor, 0);
        String session_type = ImUtil.SESSION_TYPE_ONLINE;
        JSONObject obj = imUtil.createTopics(patient + "_" + doctor + "_" + ct.getType(), consult.getId(), tempPatient.getName(), users, messages, session_type);
        if (obj == null) {
            throw new RuntimeException("IM消息发送异常!");
        }
        if (obj.getInteger("status") == -1) {//im议题创建失败
            throw new RuntimeException(obj.getString("message"));
        }
        ct.setStartMsgId(obj.get("start_msg_id").toString());
        consultTeamDao.save(ct);
        consultDao.save(consult);
        JSONArray doctors = new JSONArray();
        for (String key : users.keySet()) {
            if (patient.equals(key)) {
                continue;
            }
            doctors.add(key);
            //记录咨询的医生详情误删
            ConsultTeamDoctorDo cd = new ConsultTeamDoctorDo();
            cd.setConsult(consult.getId());
            cd.setDel("1");
            cd.setCzrq(new Date());
            cd.setTo(key);
            consultTeamDoctorDao.save(cd);
        }
        // 保存医生咨询信息
        // 添加咨询转发记录
        // 添加医生咨询日志
        String content = imService.addLogs(ct);
        re.put("doctor", doctor);
        re.put("doctorName", baseDoctorDO.getName());
        re.put("status", 1);
        re.put("sessiond_id",patient + "_" + doctor + "_" + ct.getType());
        re.put("patient",patient);
        re.put("patientName",tempPatient.getName());
        re.put("patient_idcard",tempPatient.getIdcard());
        re.put("consult",consult.getId());
        return re;
    }
    /**
     * 查询居民是否有未结束的在线咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public String  getUnfinishedConsult(String patient, String doctor) {
        String totalSql = "SELECT a.consult as \"consultCode\" " +
                "FROM wlyy_consult_team a,wlyy_consult_team_doctor b " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" +patient+"' "+
//                "AND b.to_doctor='" +doctor+"' "+
                "AND a.del='1' " +
                "AND type = 23" +
                "AND a.status=0";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
        }
        logger.info("未结束判断语句"+totalSql+"======consultCode"+consultCode);
        return consultCode;
    }
}