Explorar el Código

IM-SERVICE代码提交

huangwenjie hace 5 años
padre
commit
1f0b6819fd

+ 6 - 1
business/im-service/pom.xml

@ -11,7 +11,7 @@
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>sms-service</artifactId>
    <artifactId>im-service</artifactId>
    <version>${parent.version}</version>
    <dependencies>
@ -37,6 +37,11 @@
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>base-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--   poi xml导入导出工具 end -->
    </dependencies>
</project>

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

@ -0,0 +1,30 @@
package com.yihu.jw.im.dao;
import com.yihu.jw.entity.base.im.ConsultDo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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;
/**
 * 咨询表DAO类
 * @author huangwenjie
 */
public interface ConsultDao extends PagingAndSortingRepository<ConsultDo, String>, JpaSpecificationExecutor<ConsultDo> {
	
	// 查询患者咨询记录
	Page<Object> findByPatient(String patient, String title, long id, PageRequest pageRequest);
	
	// 查询患者咨询记录
	Page<Object> findByPatient(String patient, String title, PageRequest pageRequest);
	
	// 查询患者咨询记录
	@Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate,a.signCode  from ConsultDo a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.id < ?2 and a.del = '1' and a.type<>8 order by a.czrq desc")
	Page<Object> findByPatient(String patient, long id, Pageable pageRequest);
	
	// 查询患者咨询记录
	@Query("select a.id,a.type,a.code,a.title,a.symptoms,a.czrq,b.status,b.doctor,b.team,b.evaluate,a.signCode  from ConsultDo a,ConsultTeam b where a.code = b.consult and a.patient = ?1 and a.del = '1' and a.type<>8 order by a.czrq desc")
	Page<Object> findByPatient(String patient, Pageable pageRequest);
}

+ 20 - 0
business/im-service/src/main/java/com/yihu/jw/im/dao/ConsultTeamDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.im.dao;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 咨询扩展表DAO类
 * @author huangwenjie
 */
public interface ConsultTeamDao  extends PagingAndSortingRepository<ConsultTeamDo, String>, JpaSpecificationExecutor<ConsultTeamDo> {
	// 根據consult查詢咨询记录
	ConsultTeamDo findByConsult(String consult);
	
	@Query("select a from ConsultTeamDo a,ConsultTeamDoctor b where a.consult = b.consult and a.patient = ?1 and b.to = ?2 and a.del = '1' and a.type<>8 and a.status = 0")
	List<ConsultTeamDo> findUnfinishedConsultType(String patient,String doctor);
}

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

@ -0,0 +1,461 @@
package com.yihu.jw.im.service;
import com.alibaba.fastjson.JSONArray;
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.im.dao.ConsultDao;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.FileUtil;
import com.yihu.jw.util.date.DateUtil;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
 * IM接口业务类
 * @author huangwenjie
 */
@Service
public class ImService {
	@Autowired
	public ConsultDao consultDao;
	
	@Autowired
	public ConsultTeamDao consultTeamDao;
	
	@Autowired
	public BasePatientDao basePatientDao;
	
	public ImUtil imUtil;
	
	public FileUtil fileUtil;
	
	@Autowired
	protected HttpServletRequest request;
	
	/**
	 * 查询患者所有的咨询记录
	 * @param patient 患者标识
	 * @param id 会话ID(等同IM表topicId)
	 * @param pagesize 分页大小
	 * @param title 标题关键字
	 * @return
	 */
	public Page<Object> findConsultRecordByPatient(String patient, long id, int pagesize, String title) {
		if (id < 0) {
			id = 0;
		}
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Sort.Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		if(!StringUtils.isEmpty(title)){
			title="%"+title+"%";
			if (id > 0) {
				return consultDao.findByPatient(patient,title, id, pageRequest);
			} else {
				return consultDao.findByPatient(patient,title, pageRequest);
			}
		}else{
			if (id > 0) {
				return consultDao.findByPatient(patient, id, pageRequest);
			} else {
				return consultDao.findByPatient(patient, pageRequest);
			}
		}
	}
	
	/**
	 * 查询居民与某个医生未结束的咨询
	 *
	 * @param patient 居民
	 * @param doctor  医生
	 * @return
	 */
	public List<ConsultTeamDo> getUnfinishedConsult(String patient, String doctor) {
		return consultTeamDao.findUnfinishedConsultType(patient, doctor);
	}
	
	/**
	 * 获取会话成员
	 *
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	public JSONArray getSessions(String sessionId) {
		JSONArray participants = imUtil.getSessions(sessionId);
		return participants;
	}
	
	/**
	 * 根据会话ID获取消息记录
	 * @param sessionId 会话ID
	 * @param startMsgId 开始的消息记录ID
	 * @param endMsgId  结束的消息记录ID
	 * @param page  第几页
	 * @param pagesize  分页数量
	 * @param uid 居民CODE
	 * @return
	 */
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		JSONArray messageArray = imUtil.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, uid);
		return messageArray;
	}
	
	/**
	 * 根据咨询CODE进入会话
	 * @param consult 咨询CODE
	 * @param currentUid 当前居民ID
	 * @param uid 代理人ID
	 * @return
	 */
	public int intoTopic(String consult, String currentUid, String uid) {
		ConsultTeamDo ct = consultTeamDao.findByConsult(consult);
		if (ct.getStatus() != 0) {
			return -1;
		}
		
		String content = "进入了咨询";
		BasePatientDO p = basePatientDao.findById(uid);
		String intoUserName = p.getName();
		if (currentUid.equals(uid)) {
			content = intoUserName + content;
		} else {
			BasePatientDO member = basePatientDao.findById(currentUid);
			content = intoUserName + content;
			//目前没有家人关系,所以家人名称的名字获取暂时注释
//			content = member.getName() + "(" + relations.get(familyMember.getFamilyRelation()) + ")" + content;
		}
		
		imUtil.sendIntoTopicIM(ct.getPatient(), ct.getPatient(), ct.getConsult(), content, uid, intoUserName);
		return 0;
		
	}
	
	/**
	 * 居民咨询发消息(追问接口)
	 * @param consult 咨询标识-咨询CODE
	 * @param content 消息内容
	 * @param type 消息类型
	 * @param times 次数
	 * @return
	 */
	public List<String> append(String consult, String content, Integer type, Integer times,String patientcode) throws Exception {
		List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
		ConsultTeamDo consultModel = consultTeamDao.findByConsult(consult);
		
		if (consultModel == null) {
			throw new Exception("咨询记录不存在!");
		}
		
		if (consultModel.getEndMsgId() != null) {
			throw new Exception("咨询已结束!");
		}
		
		String[] arr = null;
		if (type == 3) {
			String path = fetchWxVoices();
			JSONObject obj = new JSONObject();
			// 将临时语音拷贝到正式存储路径下
			if (org.apache.commons.lang3.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) {
			// 图片消息
			content = fetchWxImages();
			// 将临时图片拷贝到正式存储路径下
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(content)) {
				content = CommonUtil.copyTempImage(content);
			}
			if (org.apache.commons.lang3.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};
		}
//            Patient patient = patientDao.findByCode(getUID());
		BasePatientDO patient = basePatientDao.findById(patientcode);
		int i = 0;
		List<String> failed = new ArrayList<>();
		
		String agent = getUID()==getRepUID()?null:getUID();
		for (ConsultTeamLogDo log : logs) {
//                String response = ImUtill.sendTopicIM(getUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent());
			String response = ImUtill.sendTopicIM(getRepUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent(),agent);
			
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(response)) {
				JSONObject resObj = new JSONObject(response);
				if (resObj.getInt("status") == -1) {
					return invalidUserException(new RuntimeException(resObj.getString("message")), -1, "追问失败!" + resObj.getString("message"));
				}
				failed.add(String.valueOf(resObj.get("data")));
				try {
                         /*if(messageService.getMessageNoticeSettingByMessageType(consultModel.getDoctor(),"1",MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue())){
                            //            新增发送医生助手模板消息 v1.4.0 by wujunjie
                            Doctor doctor = doctorDao.findByCode(consultModel.getDoctor());
                            String doctorOpenID = doctor.getOpenid();
                            if (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");
                                }
                            }
                        }*/
					
					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";
					}
					
					if(org.apache.commons.lang3.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.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
	 */
	public String fetchWxVoices() {
		String voiceIds = "";
		try {
			String voices = request.getParameter("voices");
			if (org.apache.commons.lang3.StringUtils.isEmpty(voices)) {
				return voices;
			}
			String[] mediaIds = voices.split(",");
			for (String mediaId : mediaIds) {
				if (org.apache.commons.lang3.StringUtils.isEmpty(mediaId)) {
					continue;
				}
				String temp = saveVoiceToDisk(mediaId);
				if (org.apache.commons.lang3.StringUtils.isNotEmpty(temp)) {
					if (voiceIds.length() == 0) {
						voiceIds = temp;
					} else {
						voiceIds += "," + temp;
					}
				}
			}
		} catch (Exception e) {
			error(e);
		}
		return voiceIds;
	}
	
	/**
	 * 获取下载语音信息(jpg)
	 *
	 * @param mediaId 文件的id
	 * @throws Exception
	 */
	public String saveVoiceToDisk(String mediaId) throws Exception {
		// 文件保存的临时路径
		String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
		// 拼接年月日路径
		String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
		// 重命名文件
		String fileBase =  DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000);
		String newFileName = fileBase+ ".amr";
		String mp3FileName  = fileBase + ".mp3";
		// 保存路径
		File uploadFile = new File(tempPath + datePath + newFileName);
		
		InputStream inputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			if (!uploadFile.getParentFile().exists()) {
				uploadFile.getParentFile().mkdirs();
			}
			inputStream = getInputStream(mediaId);
			byte[] data = new byte[1024];
			int len = 0;
			fileOutputStream = new FileOutputStream(uploadFile);
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
			String amrFilePath = tempPath+datePath+newFileName;
			String Mp3FilePath = tempPath+datePath+mp3FileName;
			fileUtil.changeToMp3(amrFilePath,Mp3FilePath);
			// 返回保存路径
			return Mp3FilePath;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 下载多媒体文件(请注意,视频文件不支持下载,调用该接口需http协议)
	 *
	 * @return
	 */
	public InputStream getInputStream(String mediaId) {
		String accessToken = getAccessToken();
		InputStream is = null;
		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			// 获取文件转化为byte流
			is = http.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}
	
}

+ 308 - 0
business/im-service/src/main/java/com/yihu/jw/im/util/HttpClientUtil.java

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

+ 636 - 0
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -0,0 +1,636 @@
package com.yihu.jw.im.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
/**
 * IM工具类
 * @author huangwenjie
 */
public class ImUtil {
	@Autowired
	private HttpClientUtil HttpClientUtil;
	
	@Value("${im.im_list_get}")
	private String im_host;
	
	
	public enum ContentType {
		plainText("信息", "1"),
		image("图片信息", "2"),
		audio("创建处方", "3"),
		article("文章信息", "4"),
		goTo("跳转信息,求组其他医生或者邀请其他医生发送的推送消息", "5"),
		topicBegin("议题开始", "6"),
		topicEnd("议题结束", "7"),
		personalCard("个人名片", "18"),
		messageForward("消息转发", "19"),
		topicInto("进入议题", "14"),
		video("视频", "12"),
		system("系统消息", "13"),
		prescriptionCheck("续方审核消息消息", "15"),
		prescriptionBloodStatus("续方咨询血糖血压咨询消息", "16"),
		prescriptionFollowupContent("续方咨询随访问卷消息", "17"),
		Rehabilitation("康复计划发送","20"),
		Reservation("转诊预约发送","21"),
		Know("已知悉","22");
		
		private String name;
		private String value;
		ContentType(String name, String value) {
			this.name = name;
			this.value = value;
		}
		
		public String getName() {
			return name;
		}
		
		public void setName(String name) {
			this.name = name;
		}
		
		public String getValue() {
			return value;
		}
		
		public void setValue(String value) {
			this.value = value;
		}
	}
	
	/**
	 * 发送消息
	 * @param senderId 发送者的code
	 * @param receiverId 接受者code
	 * @param contentType 消息类型 1二维码内容
	 * @param content 消息内容
	 * @return
	 */
	public String sendMessage(String senderId,String receiverId,String contentType,String content){
		String imAddr = im_host + "api/v2/message/send";
		JSONObject params = new JSONObject();
		params.put("sender_id", senderId);
		params.put("sender_name", receiverId);
		params.put("content_type", contentType);
		params.put("content", content);
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 获取医生统计数据
	 * status reply 为空值是是该医生总咨询量
	 *
	 * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param adminTeamCode
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getConsultData(String user, Integer adminTeamCode, Integer status, Integer reply) {
		String imAddr = im_host + "api/v2/sessions/topics/count/reply";
		imAddr = imAddr + "?user=" + user;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (adminTeamCode != null) {
			imAddr += ("&adminTeamCode=" + adminTeamCode);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	public void updateTopics(String topicId, String jsonValue) {
		String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("data", jsonValue);
		HttpClientUtil.putBody(imAddr, params);
	}
	
	/**
	 * 当前医生下当前团队列表接口
	 * 获取团队内医生的健康咨询状况
	 * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 *
	 * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param adminTeamCode 行政团队code
	 * @param page
	 * @param pagesize
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getTeamConsultByStatus(String user, Integer adminTeamCode, Integer status, Integer reply, int page, int pagesize) {
		String imAddr = im_host + "api/v2/sessions/healthTeamTopics";
		imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
		if (adminTeamCode != null) {
			imAddr += ("&adminTeamCode=" + adminTeamCode);
		}
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 列表接口
	 * 获取团队内医生的健康咨询状况
	 * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 *
	 * @param user     团队就把团队的医生合并起来用,隔开(医生编码)
	 * @param page
	 * @param pagesize
	 * @param status
	 * @param reply
	 * @return
	 */
	public String getConsultByStatus(String user, Integer status, Integer reply, int page, int pagesize) {
		String imAddr = im_host + "api/v2/sessions/healthTopics";
		imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 咨询列表
	 * @param user
	 * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 * @param reply
	 * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public String getConsultByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime,int page,int pagesize){
		String imAddr = im_host + "api/v2/sessions/topicListByType";
		imAddr = imAddr + "?user="+user + "&page=" + page + "&pagesize=" + pagesize;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		if (type != null) {
			imAddr += ("&type=" + type);
		}
		if (patientName != null) {
			imAddr += ("&patientName=" + patientName);
		}
		if (startTime != null) {
			imAddr += ("&startTime=" + startTime);
		}
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 咨询列表总数
	 * @param user
	 * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
	 * @param reply
	 * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
	 * @return
	 */
	public String getConsultCountByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime){
		String imAddr = im_host + "api/v2/sessions/topicListCountByType";
		imAddr = imAddr + "?user="+user;
		if (status != null) {
			imAddr += ("&status=" + status);
		}
		if (reply != null) {
			imAddr += ("&reply=" + reply);
		}
		if (type != null) {
			imAddr += ("&type=" + type);
		}
		if (patientName != null) {
			imAddr += ("&patientName=" + patientName);
		}
		if (startTime != null) {
			imAddr += ("&startTime=" + startTime);
		}
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		return response;
	}
	
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendImMsg(String from, String fromName, String sessionId, String contentType, String content, String businessType) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("sender_name", fromName);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("session_id", sessionId);
		params.put("business_type", businessType);
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 更新会话状态
	 *
	 * @param sessionId 会话ID
	 * @param status    状态
	 */
	public String updateSessionStatus(String sessionId, String status) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
		JSONObject params = new JSONObject();
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	/**
	 * 更新会话状态
	 *
	 * @param sessionId 会话ID
	 * @param status    状态
	 */
	public String updateTopicEvaluate(String sessionId, String status) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
		JSONObject params = new JSONObject();
		String response = HttpClientUtil.postBody(imAddr, params);
		return response;
	}
	
	
	/**
	 * 发送消息给IM
	 *
	 * @param from        来自
	 * @param contentType 1文字 2图片消息
	 * @param content     内容
	 */
	public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent) {
		String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("sender_name", fromName);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("topic_id", topicId);
		params.put("agent", agent);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	/**
	 * 发送进入im消息
	 * IM: ParticipantUpdate:'/:session_id/participant/update'
	 *
	 * @param from
	 * @param sessionId
	 * @param topicId
	 * @return
	 */
	public String sendIntoTopicIM(String from, String sessionId, String topicId, String content, String intoUser, String intoUserName) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/into";
		JSONObject params = new JSONObject();
		params.put("sender_id", from);
		params.put("topic_id", topicId);
		params.put("into_user", intoUser);
		params.put("into_user_name", intoUserName);
		params.put("content", content);
		String response = HttpClientUtil.postBody(url, params);
		return response;
	}
	
	
	/**
	 * 更新会话成员(新增或删除)
	 * @param sessionId 会话id
	 * @param user 新增的成员id
	 * @param oldUserId  删除的成员id
	 */
	public String updateParticipant(String sessionId, String user,String oldUserId) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId );
		params.put("user_id", user );
		if(!StringUtils.isEmpty(oldUserId)){
			params.put("old_user_id", oldUserId);
		}
		return HttpClientUtil.postBody(imAddr, params);
	}
	
	/**
	 * 更新消息内容
	 * @param sessionId 会话id
	 * @param sessionType 会话类型
	 * @param msgId  消息id
	 * @param content  消息内容
	 */
	public String updateMessage(String sessionId, String sessionType,String msgId,String content) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages/"+ msgId +"/update";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId );
		params.put("session_type", sessionType );
		params.put("message_id", msgId );
		params.put("content", content );
		return HttpClientUtil.postBody(imAddr, params);
	}
	
	/**
	 * 结束议题
	 *
	 * @param topicId     议题ID
	 * @param endUser     结束人
	 * @param endUserName 结束人名字
	 * @param sessionId   会话ID
	 */
	public JSONObject endTopics(String sessionId, String endUser, String endUserName, String topicId) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/ended";
		JSONObject params = new JSONObject();
		params.put("session_id", sessionId);
		params.put("end_user", endUser);
		params.put("end_user_name", endUserName);
		params.put("topic_id", topicId);
		String ret = HttpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	
	
	/**
	 * 议题邀请人员
	 *
	 * @param user      结束人名字
	 * @param sessionId 会话ID
	 */
	public void updateTopicUser(String sessionId, String user) {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
		JSONObject params = new JSONObject();
		params.put("user", user + ":" + 0);
		HttpClientUtil.putBody(imAddr, params);
	}
	
	/**
	 * 创建议题
	 *
	 * @param topicId      议题ID
	 * @param topicName    议题名称
	 * @param participants 成员
	 */
	public JSONObject createTopics(String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
		String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("topic_name", topicName);
		params.put("participants", participants.toString());
		params.put("messages", messages.toString());
		params.put("session_id", sessionId);
		params.put("session_type", sessionType);
		String ret = HttpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	
	/**
	 * 判断会话是否存在
	 */
	public Boolean sessionIsExist(String sessionId) {
		Boolean re = false;
		String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
		JSONObject params = new JSONObject();
		String ret = HttpClientUtil.get(url, "UTF-8");
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
			if(obj.getInteger("status") ==200&&sessionId.equals(obj.getString("sessionId"))){
				re = true;
			}
		} catch (Exception e) {
			return null;
		}
		return re;
	}
	
	/**
	 * 创建会话(system)
	 */
	public JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
		String imAddr = im_host + "api/v2/sessions";
		JSONObject params = new JSONObject();
		params.put("participants", participants.toString());
		params.put("session_name", sessionName);
		params.put("session_type", sessionType);
		params.put("session_id", sessionId);
		String ret = HttpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		try {
			obj = JSON.parseObject(ret);
		} catch (Exception e) {
			return null;
		}
		return obj;
	}
	
	/**
	 * 获取会话实例的消息对象
	 *
	 * @param senderId
	 * @param senderName
	 * @param title
	 * @param description
	 * @param images
	 * @param agent
	 * @return
	 */
	public JSONObject getCreateTopicMessage(String senderId, String senderName, String title, String description, String images, String agent) {
		JSONObject messages = new JSONObject();
		messages.put("description", description);
		messages.put("title", title);
		messages.put("img", images);
		messages.put("sender_id", senderId);
		messages.put("sender_name", senderName);
		messages.put("agent", agent);
		return messages;
	}
	
	public JSONObject getTopicMessage(String topicId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
				+ "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException(obj.getString("message"));
			} else {
				return obj.getJSONObject("data");
			}
		} catch (Exception e) {
			return null;
		}
		
	}
	
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			JSONArray obj = JSON.parseArray(ret);
			return obj;
		} catch (Exception e) {
			return null;
		}
		
	}
	
	/**
	 * 删除对应的成员信息在MUC模式中
	 *
	 * @param userId
	 * @param oldUserId
	 * @param sessionId
	 * @return
	 */
	public JSONObject deleteMucUser(String userId, String oldUserId, String sessionId) throws Exception {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
		try {
			JSONObject params = new JSONObject();
			params.put("user_id", userId);
			params.put("old_user_id", oldUserId);
			params.put("session_id", sessionId);
			String ret = HttpClientUtil.postBody(url, params);
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("人员更换失败!");
			} else {
				return obj;
			}
		} catch (Exception e) {
			throw new RuntimeException("人员更换失败!");
		}
	}
	
	
	/**
	 * 获取议题
	 *
	 * @param topicId
	 * @return
	 */
	public JSONObject getTopic(String topicId) throws Exception {
		String url = im_host + "api/v2/sessions/topics/" + topicId + "?topic_id=" + topicId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("获取议题失败!");
			} else {
				return obj;
			}
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
		}
	}
	
	/**
	 * 获取会话成员
	 *
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	public JSONArray getParticipants(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
	
	/**
	 * 获取会话成员
	 *
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	public JSONArray getSessions(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
		}
	}
	
	public JSONObject cleanMessageToRedis(String sessionId){
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
		}
	}
	
	public JSONObject cleanMessageLastFetchTime(String sessionId,String userId){
		String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
		}
	}
	
	
	public static final String SESSION_TYPE_MUC = "1";
	public static final String SESSION_TYPE_P2P = "2";
	public static final String SESSION_TYPE_GROUP = "3";
	public static final String SESSION_TYPE_SYSTEM = "0";
	public static final String SESSION_TYPE_PRESCRIPTION = "8";//续方
	public static final String SESSION_TYPE_EXAMINATION = "9";//在线复诊
	public static final String SESSION_TYPE_ONDOOR_NURSING = "11";//上门护理
	public static final String SESSION_STATUS_PROCEEDINGS = "0";
	public static final String SESSION_STATUS_END = "1";
	
	public static final String CONTENT_TYPE_TEXT = "1";
}

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

@ -0,0 +1,120 @@
package com.yihu.jw.entity.base.im;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 咨询表
 * @author huangwenjie
 */
@Entity
@Table(name = "wlyy_consult")
public class ConsultDo extends UuidIdentityEntity {
	// 患者标识
	private String patient;
	// 咨询类型:1三师咨询,2视频咨询,3图文咨询,4公共咨询,
	//          5病友圈 6、患者名医咨询 7医生名医咨询 8续方咨询
	//          9在线复诊咨询(居民直接咨询专家) 10医生发起的求助 11思明区上门服务在线咨询
	private Integer type;
	// 咨询标题/主诉
	private String title;
	// 主诉
	private String symptoms;
	// 咨询图片URL,多图以逗号分隔
	private String images;
	// 关联指导
	private Long guidance;
	// 咨询时间
	private Date czrq;
	// 作废标识,1正常,0作废
	private String del;
	// 结束时间
	private Date endTime;
	//关联业务表的code
	private String relationCode;
	
	public String getPatient() {
		return patient;
	}
	
	public void setPatient(String patient) {
		this.patient = patient;
	}
	
	public Integer getType() {
		return type;
	}
	
	public void setType(Integer type) {
		this.type = type;
	}
	
	public String getTitle() {
		return title;
	}
	
	public void setTitle(String title) {
		this.title = title;
	}
	
	public String getSymptoms() {
		return symptoms;
	}
	
	public void setSymptoms(String symptoms) {
		this.symptoms = symptoms;
	}
	
	public String getImages() {
		return images;
	}
	
	public void setImages(String images) {
		this.images = images;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEndTime() {
		return endTime;
	}
	
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	
	public String getDel() {
		return del;
	}
	
	public void setDel(String del) {
		this.del = del;
	}
	
	public Long getGuidance() {
		return guidance;
	}
	public void setGuidance(Long guidance) {
		this.guidance = guidance;
	}
	
	public String getRelationCode() {
		return relationCode;
	}
	
	public void setRelationCode(String relationCode) {
		this.relationCode = relationCode;
	}
}

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

@ -0,0 +1,383 @@
package com.yihu.jw.entity.base.im;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Transient;
import java.util.Date;
/**
 * IM咨询扩展表
 * @author huangwenjie
 */
public class ConsultTeamDo extends UuidIdentityEntity {
	
	private String consult;         // 咨询标识
	private String doctor;          // 医生标识
	private String team;            // 三师团队标识
	private Integer type;           //  1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 9在线复诊咨询(居民直接咨询专家) 10医生发起的求助 11思明区上门服务在线咨询
	private String patient;         // 提问者标识
	private String name;            // 患者姓名
	private Integer sex;            // 患者性别
	private Date birthday;          // 患者生日
	private String photo;           // 患者头像
	private String when;            // 发病日期
	private String symptoms;        // 主要症状
	private Integer status;         // 咨询状态(0进行中,1已完成,-1患者取消,-2超时未响应自动关闭)
	private String images;          // 咨询图片URL,多图以逗号分隔
	private String voice;           // 咨询语音URL
	private String comment;         // 用户评价标识
	private String commentContent;  // 用户评价内容
	private Integer commentStar;    // 用户评价星级
	private Integer doctorRead;     // 医生未读数量
	private Integer patientRead;    // 患者未读数量
	private Date czrq;              // 咨询时间
	private String del;             // 作废标识,1正常,0作废
	private Long adminTeamId;//行政团队ID
	private Long guidance;   //关联指导
	private String doctorName;//醫生名字
	//起始消息id
	private String startMsgId;
	//结束消息id
	private String endMsgId;
	// 结束人
	private String endOperator;
	// 结束人类型
	private Integer endType;
	// 结束时间
	private Date endTime;
	//是否评价 1、已评价 0、未评价'
	private Integer evaluate;
	//评价时间
	private Date evaluateTime;
	
	private String relationCode;//关联业务表的code
	
	private Integer healthindexType;//体征数据上传发送IM消息:1血压 2血糖 3血压+血糖
	
	private Integer isRefinement;//是否加精(0未加精 1已加精)
	
	private Integer isAuthentication;//是否认证 0未认证 1已认证通过 2认证不通过
	
	private String authenticationHospital;//认证机构id
	
	private String authenticationHospitalName;//认证机构名称
	
	private String refinementCode;//wlyy_refinement_consult中唯一标识code
	
	public Integer getEvaluate() {
		return evaluate;
	}
	
	public void setEvaluate(Integer evaluate) {
		this.evaluate = evaluate;
	}
	
	public Date getEvaluateTime() {
		return evaluateTime;
	}
	
	public void setEvaluateTime(Date evaluateTime) {
		this.evaluateTime = evaluateTime;
	}
	
	@Column(name = "admin_team_code")
	public Long getAdminTeamId() {
		return adminTeamId;
	}
	
	public void setAdminTeamId(Long adminTeamId) {
		this.adminTeamId = adminTeamId;
	}
	
	public String getConsult() {
		return consult;
	}
	
	public void setConsult(String consult) {
		this.consult = consult;
	}
	
	public ConsultTeamDo() {
	}
	
	public String getDoctor() {
		return doctor;
	}
	
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	
	public String getTeam() {
		return team;
	}
	
	public void setTeam(String team) {
		this.team = team;
	}
	
	public Integer getType() {
		return type;
	}
	
	public void setType(Integer type) {
		this.type = type;
	}
	
	public String getPatient() {
		return patient;
	}
	
	public void setPatient(String patient) {
		this.patient = patient;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
	
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public String getPhoto() {
		return photo;
	}
	
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	
	@Column(name = "fbsj")
	public String getWhen() {
		return when;
	}
	
	public void setWhen(String when) {
		this.when = when;
	}
	
	public Integer getStatus() {
		return status;
	}
	
	public void setStatus(Integer status) {
		this.status = status;
	}
	
	public String getImages() {
		return images;
	}
	
	public void setImages(String images) {
		this.images = images;
	}
	
	public String getVoice() {
		return voice;
	}
	
	public void setVoice(String voice) {
		this.voice = voice;
	}
	
	public String getComment() {
		return comment;
	}
	
	public void setComment(String comment) {
		this.comment = comment;
	}
	
	@Column(name = "comment_content")
	public String getCommentContent() {
		return commentContent;
	}
	
	public void setCommentContent(String commentContent) {
		this.commentContent = commentContent;
	}
	
	@Column(name = "comment_star")
	public Integer getCommentStar() {
		return commentStar;
	}
	
	public void setCommentStar(Integer commentStar) {
		this.commentStar = commentStar;
	}
	
	@Column(name = "doctor_read")
	public Integer getDoctorRead() {
		return doctorRead;
	}
	
	public void setDoctorRead(Integer doctorRead) {
		this.doctorRead = doctorRead;
	}
	
	@Column(name = "patient_read")
	public Integer getPatientRead() {
		return patientRead;
	}
	
	public void setPatientRead(Integer patientRead) {
		this.patientRead = patientRead;
	}
	
	// 设定JSON序列化时的日期格式
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	
	// 设定JSON序列化时的日期格式
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEndTime() {
		return endTime;
	}
	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}
	
	public String getSymptoms() {
		return symptoms;
	}
	
	public void setSymptoms(String symptoms) {
		this.symptoms = symptoms;
	}
	
	public String getDel() {
		return del;
	}
	
	public void setDel(String del) {
		this.del = del;
	}
	
	public Integer getSex() {
		return sex;
	}
	
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	@Transient
	public String getDoctorName() {
		return doctorName;
	}
	
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	
	public Long getGuidance() {
		return guidance;
	}
	public void setGuidance(Long guidance) {
		this.guidance = guidance;
	}
	
	
	public String getStartMsgId() {
		return startMsgId;
	}
	
	public void setStartMsgId(String startMsgId) {
		this.startMsgId = startMsgId;
	}
	
	public String getEndMsgId() {
		return endMsgId;
	}
	
	public void setEndMsgId(String endMsgId) {
		this.endMsgId = endMsgId;
	}
	
	public String getEndOperator() {
		return endOperator;
	}
	public void setEndOperator(String endOperator) {
		this.endOperator = endOperator;
	}
	
	public Integer getEndType() {
		return endType;
	}
	public void setEndType(Integer endType) {
		this.endType = endType;
	}
	
	public String getRelationCode() {
		return relationCode;
	}
	
	public void setRelationCode(String relationCode) {
		this.relationCode = relationCode;
	}
	
	public Integer getHealthindexType() {
		return healthindexType;
	}
	
	public void setHealthindexType(Integer healthindexType) {
		this.healthindexType = healthindexType;
	}
	
	public Integer getIsRefinement() {
		return isRefinement;
	}
	
	public void setIsRefinement(Integer isRefinement) {
		this.isRefinement = isRefinement;
	}
	
	public Integer getIsAuthentication() {
		return isAuthentication;
	}
	
	public void setIsAuthentication(Integer isAuthentication) {
		this.isAuthentication = isAuthentication;
	}
	
	public String getAuthenticationHospital() {
		return authenticationHospital;
	}
	
	public void setAuthenticationHospital(String authenticationHospital) {
		this.authenticationHospital = authenticationHospital;
	}
	
	public String getAuthenticationHospitalName() {
		return authenticationHospitalName;
	}
	
	public void setAuthenticationHospitalName(String authenticationHospitalName) {
		this.authenticationHospitalName = authenticationHospitalName;
	}
	
	public String getRefinementCode() {
		return refinementCode;
	}
	
	public void setRefinementCode(String refinementCode) {
		this.refinementCode = refinementCode;
	}
}

+ 111 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamLogDo.java

@ -0,0 +1,111 @@
package com.yihu.jw.entity.base.im;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import java.util.Date;
/**
 * 咨询日志表
 * @author huangwenjie
 */
public class ConsultTeamLogDo extends UuidIdentityEntity {
	// 咨询标识
	private String consult;
	// 回复医生标识
	private String doctor;
	// 回复医生姓名
	private String doctorName;
	// 回复人头像
	private String photo;
	// 回复内容/追问内容
	private String content;
	// 类型,0问,1回复,2追问,3评价
	private Integer type;
	// 记录类型:1文字,2图片,3语音
	private Integer chatType;
	// 操作时间
	private Date czrq;
	// 作废标识,1正常,0作废
	private String del;
	
	public ConsultTeamLogDo() {
	
	}
	
	public String getConsult() {
		return consult;
	}
	
	public void setConsult(String consult) {
		this.consult = consult;
	}
	
	public String getContent() {
		return content;
	}
	
	public void setContent(String content) {
		this.content = content;
	}
	
	public Integer getType() {
		return type;
	}
	
	public void setType(Integer type) {
		this.type = type;
	}
	
	@Column(name = "chat_type")
	public Integer getChatType() {
		return chatType;
	}
	
	public void setChatType(Integer chatType) {
		this.chatType = chatType;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	
	public String getDoctor() {
		return doctor;
	}
	
	public void setDoctor(String doctor) {
		this.doctor = doctor;
	}
	
	@Column(name = "doctor_name")
	public String getDoctorName() {
		return doctorName;
	}
	
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	
	public String getPhoto() {
		return photo;
	}
	
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	
	public String getDel() {
		return del;
	}
	
	public void setDel(String del) {
		this.del = del;
	}
}

+ 27 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/hospital/BaseHospitalRequestMapping.java

@ -1,5 +1,6 @@
package com.yihu.jw.rm.hospital;
import com.sun.xml.internal.rngom.parse.host.Base;
import com.yihu.jw.rm.base.BaseRequestMapping;
/**
@ -147,5 +148,31 @@ public class BaseHospitalRequestMapping {
    public static class Expressage extends Basic {
        public static final String PREFIX  = "/expressage";
    }
    
    /**
     * 居民端-咨询IM
     */
    public static class PatientIM extends Base{
        public static final String PREFIX  = "/im/patient";
    
        //患者咨询记录查询
        public static final String records ="/records";
    
        //查询居民与某个医生是否存在未结束的咨询
        public static final String isExistsUnfinishedConsult ="/isExistsUnfinishedConsult";
        
        //获取会话成员
        public static final String participants ="/participants";
        
        //根据会话ID获取消息记录
        public static final String getSessionMessage ="/getSessionMessage";
        
        //根据咨询CODE进入会话
        public static final String intoTopic ="/intoTopic";
        
        //居民咨询发消息(追问接口)
        public static final String append ="/append";
        
    }
}

+ 5 - 0
common/common-util/pom.xml

@ -69,5 +69,10 @@
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>jave-ffmpegjave</artifactId>
            <version>1.0.4</version>
        </dependency>
    </dependencies>
</project>

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

@ -0,0 +1,66 @@
package com.yihu.jw.util.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import it.sauronsoftware.jave.*;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * @author huangwenjie
 * @date 2019/6/12 10:34
 */
public class FileUtil {
	public void changeToMp3(String sourcePath, String targetPath) {
		File source = new File(sourcePath);
		File target = new File(targetPath);
		AudioAttributes audio = new AudioAttributes();
		Encoder encoder = new Encoder();
		audio.setCodec("libmp3lame");
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		try {
			encoder.encode(source, target, attrs);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InputFormatException e) {
			e.printStackTrace();
		} catch (EncoderException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 拷贝临时语音文件到存储目录
	 *
	 * @param voices
	 * @return
	 * @throws IOException
	 */
	
	
	public String copyTempVoice(String voices) throws Exception {
		// 文件保存的临时路径
		String serverUrl = fastdfs_file_url;
		FastDFSUtil fastDFSUtil = new FastDFSUtil();
		String fileUrls = "";
		File f = new File(voices);
		if (f.exists()) {
			String fileName = f.getName();
			InputStream in = new FileInputStream(f);
			ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
			in.close();
			if (result != null) {
				fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",") + serverUrl
						+ result.get("groupName").toString().replaceAll("\"", "") + "/"
						+ result.get("remoteFileName").toString().replaceAll("\"", "");
				f.delete();
			}
		}
		return fileUrls;
	}
}

+ 1 - 1
common/common-web/src/main/resources/logback-spring.xml

@ -5,7 +5,7 @@
    <springProperty scope="context" name="appName" source="spring.application.name" />
	<property name="log_home" value="/wlyy-logs/${appName}" />
	<property name="log_home" value="/Users/Mewtwo/ideaSpace/log/wlyy-logs/${appName}" />
    <property name="max_history" value="30"/>
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />

+ 6 - 0
svr/svr-internet-hospital-entrance/pom.xml

@ -136,6 +136,12 @@
            <version>2.0.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>2.0.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>

+ 5 - 0
svr/svr-internet-hospital/pom.xml

@ -202,6 +202,11 @@
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>
    <build>

+ 159 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -0,0 +1,159 @@
package com.yihu.jw.hospital.endpoint.consult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.im.service.ImService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * @author huangwenjie
 */
@RestController
@RequestMapping(value = BaseHospitalRequestMapping.PatientIM.PREFIX)
@Api(value = "居民端咨询IM接口", description = "居民端咨询IM接口", tags = {"居民端咨询IM接口"})
public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	
	@Autowired
	private ImService imService;
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.records)
	@ApiOperation(value = "患者咨询记录查询")
	public ListEnvelop records(
								@ApiParam(name = "patient", value = "居民id")
								@RequestParam(value = "patient",required = false) String patient,
								@ApiParam(name = "title", value = "咨询标题关键字")
								@RequestParam(value = "title",required = false) String title,
								@ApiParam(name = "id", value = "咨询ID")
								@RequestParam(value = "id",required = false) Long id,
								@ApiParam(name = "pagesize", value = "分页大小")
								@RequestParam(value = "pagesize",required = false) int pagesize
								)throws Exception{
		JSONArray array = new JSONArray();
		Page<Object> data = imService.findConsultRecordByPatient(patient, 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.add(json);
			}
		}
		return success(array);
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.isExistsUnfinishedConsult)
	@ApiOperation(value = "查询居民与某个医生是否存在未结束的咨询")
	public Envelop isExistsUnfinishedConsult(
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor)throws Exception {
		org.json.JSONObject result = new org.json.JSONObject();
		List<ConsultTeamDo> consults = imService.getUnfinishedConsult(getUID(), doctor);
		
		if (consults != null && consults.size() > 0) {
			return success("查询成功",consults.get(0).getConsult());
		} else {
			return success("查询成功");
		}
		
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.participants)
	@ApiOperation(value = "获取会话成员")
	public ListEnvelop participants(
			@ApiParam(name = "sessionId", value = "会话ID")
			@RequestParam(value = "sessionId",required = true) String sessionId){
		
		JSONArray participants = imService.getSessions(sessionId);
		return success(participants);
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getSessionMessage)
	@ApiOperation(value = "根据会话ID获取消息记录")
	public ListEnvelop getSessionMessage(
			@ApiParam(name = "sessionId", value = "会话ID")
			@RequestParam(value = "sessionId",required = true) String sessionId,
			@ApiParam(name = "startMsgId", value = "开始的消息记录ID")
			@RequestParam(value = "startMsgId",required = false) String startMsgId,
			@ApiParam(name = "endMsgId", value = "结束的消息记录ID")
			@RequestParam(value = "endMsgId",required = false) String endMsgId,
			@ApiParam(name = "page", value = "第几页")
			@RequestParam(value = "page",required = true) int page,
			@ApiParam(name = "pagesize", value = "分页数")
			@RequestParam(value = "pagesize",required = true) int pagesize){
		JSONArray messageArray = imService.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getUID());
		return success(messageArray);
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.intoTopic)
	@ApiOperation(value = "根据会话ID获取消息记录")
	public Envelop intoTopic(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult){
		int result = imService.intoTopic(consult,"",getUID());
		if(result==-1){
			return failed("该咨询不是进行中");
		}
//		org.json.JSONObject json = new org.json.JSONObject();
//		json.put("consult",consult);
//		json.put("content","进入咨询");
//		BusinessLogs.info(BusinessLogs.BusinessType.consult, getUID(), getRepUID(), json);
		return success("进入成功");
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.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){
		List<String> failed = new ArrayList<>();
		failed = imService.append(consult,content,type,times)
		return success(failed);
	}
}

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

@ -121,6 +121,9 @@ hospital:
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.118:3000/
  data_base_name: im_new
---
spring:
  profiles: jwtest
@ -163,6 +166,9 @@ hospital:
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.118:3000/
  data_base_name: im_new
---
spring:
  profiles: prod
@ -201,4 +207,7 @@ hospital:
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.118:3000/
  data_base_name: im