package com.yihu.jw.im.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
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.im.ConsultTeamLogDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalWaitingRoomDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDoctorDO;
import com.yihu.jw.entity.hospital.message.BaseUserMessageDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyConsultAdvice;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.entity.order.BusinessOrderDO;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateDao;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateScoreDao;
import com.yihu.jw.hospital.consult.dao.HospitalWaitingRoomDao;
import com.yihu.jw.hospital.consult.dao.WlyyConsultAdviceDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.message.dao.BaseBannerDoctorDao;
import com.yihu.jw.hospital.message.dao.BaseUserMessageDao;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
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.dao.ConsultTeamLogDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.im.util.ImageCompress;
import com.yihu.jw.order.dao.BusinessOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionDiagnosisVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.restmodel.im.ConsultVO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.common.FileUtil;
import com.yihu.jw.util.common.IdCardUtil;
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 org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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 {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(ImService.class);

    @Autowired
    public ConsultDao consultDao;

    @Autowired
    public ConsultTeamDao consultTeamDao;

    @Autowired
    public ConsultTeamDoctorDao consultTeamDoctorDao;

    @Autowired
    public ConsultTeamLogDao consultTeamLogDao;

    @Autowired
    public BasePatientDao basePatientDao;

    @Autowired
    public BaseEvaluateScoreDao baseEvaluateScoreDao;
    @Autowired
    public BaseEvaluateDao baseEvaluateDao;

    @Autowired
    private HospitalWaitingRoomDao hospitalWaitingRoomDao;

    @Autowired
    public ImUtil imUtil;

    public FileUtil fileUtil;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    public WxAccessTokenService wxAccessTokenService;

    @Autowired
    private YkyyService ykyyService;
    @Autowired
    private BusinessOrderDao businessOrderDao;

    @Autowired
    private PrescriptionService prescriptionService;
    @Autowired
    private BaseBannerDoctorDao baseBannerDoctorDao;
    @Autowired
    private WlyyHospitalSysDictDao hospitalSysDictDao;

    @Value("${im.data_base_name}")
    private String data_base_name;

    @Value("${FileTempPath.upload_temp_path}")
    private String upload_temp_path;

    @Value("${FileTempPath.image_path}")
    private String image_path;

    @Value("${FileTempPath.voice_path}")
    private String voice_path;

    @Value("${FileTempPath.chat_file_path}")
    private String chat_file_path;

    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;

    @Value("${demo.flag}")
    private boolean demoFlag;
    @Autowired
    private WxTemplateService wxTemplateService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private SystemMessageService systemMessageService;
    @Autowired
    private BaseUserMessageDao userMessageDao;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private WlyyConsultAdviceDao wlyyConsultAdviceDao;

    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;

    @Value("${wechat.id}")
    private String wxId;


    @Value("${wechat.flag}")
    private boolean flag;


    /**
     * 查询患者所有的咨询记录
     *
     * @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, Integer payStatus, String doctorName) {


        String sql = "SELECT " +
                "a.id AS \"id\"," +
                "a.type AS \"type\"," +
                "a.title AS \"title\"," +
                "a.symptoms AS \"symptoms\",";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            } else {
                sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
            }
        } else {
            sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
        }
        sql = sql + "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 + ")";
        /*List<ConsultVO> result = new ArrayList<>();*/

        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) {

            if (status == 2) {//就诊中
                sql += " and b.status = 0 ";
            } else if (status == 3) {
                sql += " and b.status = 1 ";
            } else {
            }

        }

        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }

        if (!StringUtils.isEmpty(payStatus)) {
            sql += " and a.pay_status = " + payStatus + "";
        }
        sql += " ORDER BY a.czrq desc ";
        logger.info("sql=" + sql);
        List<Map<String, Object>> result = hibenateUtils.createSQLQuery(sql, page, pagesize);
        /*result = jdbcTemplate.query(sql, new BeanPropertyRowMapper(ConsultVO.class));*/
        return result;
    }

    /**
     * 查询患者所有的咨询记录总数
     *
     * @param patient 患者标识
     * @param id      会话ID（等同IM表topicId）
     * @param type    咨询会话类型
     * @param title   标题关键字
     * @return
     */
    public Long countConsultRecordByPatient(String patient, String id, String type, String title) {

        String sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_doctor d " +
                "WHERE a.id=b.consult " +
                "AND b.doctor=d.id AND a.patient='" + patient + "' AND a.type in (" + type + ") ";
        List<ConsultVO> result = new ArrayList<>();

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and a.title like '" + title + "'";
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        return count;
    }

    /**
     * 查询居民与某个医生未结束的专家咨询
     *
     * @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 (a.type<> 9 and a.type<> 16 and a.type<>12 )" +
                "AND a.status=0";

        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
        }
        logger.info("未结束判断语句" + totalSql + "======consultCode" + consultCode);
        return consultCode;
    }

    /**
     * 查询居民与某个医生未结束的专家咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public String getUnfinishedConsult2(String patient, String doctor) {

        String totalSql = "SELECT a.id as \"consultCode\" " +
                "FROM wlyy_outpatient a " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" + patient + "' " +
                "AND a.doctor='" + doctor + "' " +
                "AND a.type in (1,2 )" +
                "AND a.status in (0,1)" +
                "AND a.outpatient_type = 3";

        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        String consultCode = null;
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
        }
        logger.info("未结束判断语句" + totalSql + "======consultCode" + consultCode);
        return consultCode;
    }

    /**
     * 根据咨询Code,查询咨询详情
     *
     * @param consultCode
     * @return
     */
    public ConsultTeamDo getConsultTeamDo(String consultCode) {
        ConsultTeamDo consultTeamDo = consultTeamDao.findByConsult(consultCode);
        return consultTeamDo;
    }

    /**
     * 查询全科医生与某个医生未结束的专家咨询
     *
     * @param patient        居民
     * @param general_doctor 全科医生
     * @return
     */
    public JSONObject getUnfinishedConsultByActualSender(String patient, String general_doctor) {
        JSONObject result = new JSONObject();

        String totalSql = "SELECT a.consult as \"consultCode\",a.doctor as \"specialDoctor\"  " +
                "FROM wlyy_consult_team a,wlyy_consult_team_doctor b " +
                "WHERE a.consult=b.consult " +
                "AND a.patient= '" + patient + "' " +
                "AND a.actual_sender='" + general_doctor + "' " +
                "AND a.del='1' " +
                "AND a.type<> 12 " +
                "AND a.status=0";

        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);

        String consultCode = "";
        String specialDoctor = "";
        if (rstotal != null && rstotal.size() > 0) {
            consultCode = rstotal.get(0).get("consultCode").toString();
            specialDoctor = rstotal.get(0).get("specialDoctor").toString();
            result.put("consultCode", consultCode);
            result.put("specialDoctor", specialDoctor);

        }
        return result;
    }


    /**
     * 获取会话成员
     *
     * @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(currentUid);
        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, currentUid, intoUserName);
        return 0;

    }

    /**
     * 居民咨询发消息（追问接口）
     *
     * @param consult      咨询标识-咨询CODE
     * @param content      消息内容
     * @param type         消息类型
     * @param times        次数
     * @param patientcode  发送的居民CODE
     * @param wechat_appid 微信公众号appid
     * @return
     */
    public List<String> append(String consult, String content, Integer type, Integer times, String patientcode, String wechat_appid, String agent) throws Exception {
        List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
        ConsultTeamDo consultModel = consultTeamDao.findByConsult(consult);
        if (consultModel == null) {
            throw new Exception("咨询记录不存在！");
        }
        try {
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                prescriptionService.wxTempalteJPush("consult_remind_doctor", null, consultModel, content, "", "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (consultModel.getEndMsgId() != null) {
            throw new Exception("咨询已结束！");
        }

        String[] arr = null;
        if (type == 3) {//语音文件处理
            ConsultTeamLogDo log = new ConsultTeamLogDo();
            log.setConsult(consult);
            log.setContent(content);
            log.setDel("1");
            log.setChatType(type);
            log.setType(type);
            logs.add(log);
        } else if (type == 2) {
//			// 图片消息

            String[] images = content.split(",");
            for (String image : images) {
                ConsultTeamLogDo log = new ConsultTeamLogDo();
                log.setConsult(consult);
                log.setContent(image);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);
            }
        } else {
            ConsultTeamLogDo log = new ConsultTeamLogDo();
            log.setConsult(consult);
            log.setContent(content);
            log.setDel("1");
            log.setChatType(type);
            log.setType(type);
            logs.add(log);

            arr = new String[]{content};
        }
//            Patient patient = patientDao.findByCode(getUID());
        BasePatientDO patient = basePatientDao.findById(patientcode);
        int i = 0;
        List<String> failed = new ArrayList<>();

        for (ConsultTeamLogDo log : logs) {
            String response = imUtil.sendTopicIM(patientcode, patient.getName(), consult, String.valueOf(log.getType()), log.getContent(), agent, 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"));
                }
                failed.add(String.valueOf(resObj.get("data")));
            }
        }
        return failed;
    }

    /**
     * 居民咨询发消息（追问接口）
     *
     * @param consult      咨询标识-咨询CODE
     * @param content      消息内容
     * @param type         消息类型
     * @param times        次数
     * @param patientcode  发送的居民CODE
     * @param wechat_appid 微信公众号appid
     * @return
     */
    public List<String> append(String consult, String content, Integer type, Integer times, String patientcode, String wechat_appid) throws Exception {
        List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
        ConsultTeamDo consultModel = consultTeamDao.findByConsult(consult);
        if (consultModel == null) {
            throw new Exception("咨询记录不存在！");
        }
        try {
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                prescriptionService.wxTempalteJPush("consult_remind_doctor", null, consultModel, content, "", "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (consultModel.getEndMsgId() != null) {
            throw new Exception("咨询已结束！");
        }

        String[] arr = null;
        if (type == 3) {//语音文件处理
            ConsultTeamLogDo log = new ConsultTeamLogDo();
            log.setConsult(consult);
            log.setContent(content);
            log.setDel("1");
            log.setChatType(type);
            log.setType(type);
            logs.add(log);
        } else if (type == 2) {
//			// 图片消息

            String[] images = content.split(",");
            for (String image : images) {
                ConsultTeamLogDo log = new ConsultTeamLogDo();
                log.setConsult(consult);
                log.setContent(image);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);
            }
        } else {
            ConsultTeamLogDo log = new ConsultTeamLogDo();
            log.setConsult(consult);
            log.setContent(content);
            log.setDel("1");
            log.setChatType(type);
            log.setType(type);
            logs.add(log);

            arr = new String[]{content};
        }
//            Patient patient = patientDao.findByCode(getUID());
        BasePatientDO patient = basePatientDao.findById(patientcode);
        int i = 0;
        List<String> failed = new ArrayList<>();

        for (ConsultTeamLogDo log : logs) {
            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"));
                }
                failed.add(String.valueOf(resObj.get("data")));
            }
        }
        return failed;
    }

    /**
     * 获取微信服务器图片
     *
     * @param wechat_appid 微信公众号appid
     * @return
     */
    public String fetchWxImages(String wechat_appid) {
        String photos = "";
        try {
            String images = request.getParameter("mediaIds");
            if (org.apache.commons.lang3.StringUtils.isEmpty(images)) {
                return photos;
            }
            String[] mediaIds = images.split(",");
            for (String mediaId : mediaIds) {
                if (org.apache.commons.lang3.StringUtils.isEmpty(mediaId)) {
                    continue;
                }
                String temp = saveImageToDisk(mediaId, wechat_appid);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(temp)) {
                    if (photos.length() == 0) {
                        photos = temp;
                    } else {
                        photos += "," + temp;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//			error(e);
        }
        return photos;
    }

    /**
     * 获取微信服务器语音
     *
     * @return
     */
    public String fetchWxVoices(String wecha_appid) {
        String voiceIds = "";
        try {
            String voices = request.getParameter("voices");
            System.out.println("voices" + 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, wecha_appid);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(temp)) {
                    if (voiceIds.length() == 0) {
                        voiceIds = temp;
                    } else {
                        voiceIds += "," + temp;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//			error(e);
        }
        return voiceIds;
    }

    /**
     * 获取下载语音信息（jpg）
     *
     * @param mediaId 文件的id
     * @throws Exception
     */
    public String saveVoiceToDisk(String mediaId, String wechat_appid) throws Exception {
        // 文件保存的临时路径
        String tempPath = upload_temp_path + File.separator;
        System.out.println("tempPath:" + tempPath);
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        System.out.println("datePath:" + datePath);
        // 重命名文件
        String fileBase = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000);
        System.out.println("fileBase:" + fileBase);
        String newFileName = fileBase + ".amr";
        String mp3FileName = fileBase + ".mp3";
        System.out.println("newFileName:" + newFileName);
        System.out.println("mp3FileName:" + mp3FileName);
        // 保存路径
        File uploadFile = new File(tempPath + datePath + newFileName);

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            inputStream = getInputStream(mediaId, wechat_appid);
            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;
            System.out.println("amrFilePath:" + amrFilePath);
            System.out.println("Mp3FilePath:" + Mp3FilePath);
//			fileUtil.changeToMp3(amrFilePath,Mp3FilePath);
            // 返回保存路径
            return amrFilePath;
        } 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;
    }


    /**
     * 获取下载图片信息（jpg）
     *
     * @param mediaId      文件的id
     * @param wechat_appid 微信appid
     * @throws Exception
     */
    public String saveImageToDisk(String mediaId, String wechat_appid) throws Exception {
        // 文件保存的临时路径
        String tempPath = upload_temp_path + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        // 重命名文件
        String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
        // 保存路径
        File uploadFile = new File(tempPath + datePath + newFileName);

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            inputStream = getInputStream(mediaId, wechat_appid);
            byte[] data = new byte[1024];
            int len = 0;
            fileOutputStream = new FileOutputStream(uploadFile);
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
            // 生成缩略图
            ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
            // 返回保存路径
            return datePath + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 下载多媒体文件（请注意，视频文件不支持下载，调用该接口需http协议）
     *
     * @return
     */
    public InputStream getInputStream(String mediaId, String wechat_appid) throws Exception {
        String accessToken = "";
        //中山医院互联网医院
        if ("xm_zsyy_wx".equals(wechat_appid)) {
            accessToken = entranceService.getAccessToken("100033");
            net.sf.json.JSONObject object1 = net.sf.json.JSONObject.fromObject(accessToken);
            if (null != object1 && null != object1.get("respCode") && "00".equals(object1.get("respCode"))) {
                accessToken = object1.getJSONObject("respEntity").getString("access_token");
            } else {
                throw new Exception("获取ACCESSTOKEN失败");
            }
        } else {
            accessToken = wxAccessTokenService.getWxAccessTokenById(wechat_appid).getAccessToken();
        }
        InputStream is = null;
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
//		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=30_OBJbMMPW9TnyGHKf32bcjkXtxWnzBrtqWlSMBnNk8MWpJ6qis2TnsecRYNZImgahdx30WrsI1bGco6K67-j4sT1QkDxYKBrVvjaYF6QgbY8dgBMzuoARKoaxtX3ehiYvdCLSUHvogrpF3n0GANIfCHAHUP&media_id=R_060hnyXAFyHD9HaOLl15xhDIzDvcA61-Wz34GkXmCakdrsFJqxrPEBHewmAEK9";
        logger.info("media/get" + url);
        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();
            if (is.available() <= 200) {
                logger.info("下载多媒体文件 accessToken 过期");
                //中山医院互联网医院
                if ("xm_zsyy_wx".equals(wechat_appid)) {
                    accessToken = entranceService.getAccessToken("100033");

                    net.sf.json.JSONObject object1 = net.sf.json.JSONObject.fromObject(accessToken);
                    if (null != object1 && null != object1.get("respCode") && "00".equals(object1.get("respCode"))) {
                        accessToken = object1.getJSONObject("respEntity").getString("access_token");
                    } else {
                        throw new Exception("获取ACCESSTOKEN失败");
                    }
                    is = getInputStreamReLoad(mediaId, wechat_appid, accessToken);
                    return is;
                } else {
                    wxAccessTokenService.deleteByWechatId(wechat_appid);
                    accessToken = wxAccessTokenService.updateAccessToken(wechat_appid);
                    is = getInputStreamReLoad(mediaId, wechat_appid, accessToken);
                    return is;
                }
            }


        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new Exception("下载失败，" + e.getMessage());
        }
        return is;
    }


    /**
     * accessToken 过期时重新下载多媒体文件
     * 下载多媒体文件（请注意，视频文件不支持下载，调用该接口需http协议）
     *
     * @return
     */
    public InputStream getInputStreamReLoad(String mediaId, String wechat_appid, String accessToken) throws Exception {
        logger.info("accessToken 过期时重新下载多媒体文件：accessToken：" + accessToken);
        logger.info("accessToken 过期时重新下载多媒体文件：wechat_appid：" + wechat_appid);
        logger.info("accessToken 过期时重新下载多媒体文件：mediaId：" + mediaId);
        InputStream is = null;
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
        logger.info("media/get" + url);
        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) {
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new Exception("下载失败，" + e.getMessage());
        }
        return is;
    }


    /**
     * 患者端
     * 发起专家咨询
     *
     * @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))) {//判断是否有未结束的咨询移到同步方法中
//			re.put("status", -3);
//			return re;
                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 = 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);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
        String session_type = imUtil.SESSION_TYPE_MUC;
        if (17 == ct.getType()) {
            session_type = imUtil.SESSION_TYPE_MUC_VIDEO;//专家咨询-视频
        }
        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 = 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 title   咨询标题
     * @param type    咨询类型：9在线复诊，13专家咨询，23在线咨询
     * @return
     */
    public ConsultDo addConsult(String patient, String title, String symptoms, String images, int type, String source) {
        ConsultDo consult = new ConsultDo();
        consult.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        consult.setCzrq(new Date());
        consult.setDel("1");
        consult.setPatient(patient);
        consult.setTitle(title);
        consult.setSymptoms(symptoms);
        consult.setImages(images);
        consult.setType(type);
        consult.setPayStatus(0);
        consult.setSource(source);
        return consultDao.save(consult);
    }

    /**
     * 添加咨询日志
     *
     * @param ct
     * @throws Exception
     */
    public String addLogs(ConsultTeamDo ct) throws Exception {
        List<ConsultTeamLogDo> logs = new ArrayList<ConsultTeamLogDo>();
        // 添加问题咨询日志
        String content = "";

        content += "咨询问题：" + (org.apache.commons.lang3.StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());

        // 生成提问日志，并推送相关消息
        ConsultTeamLogDo infoLog = new ConsultTeamLogDo();
        infoLog.setConsult(ct.getConsult());
        if (content.length() > 2500) {
            content = content.substring(0, 2500);
        }
        infoLog.setContent(content);
        infoLog.setDel("1");
        infoLog.setType(0);
        infoLog.setChatType(1);
        infoLog.setCzrq(new Date());
        logs.add(infoLog);
        // 图片日志
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (org.apache.commons.lang3.StringUtils.isNoneEmpty(image)) {
                    ConsultTeamLogDo imgLog = new ConsultTeamLogDo();
                    // 设置咨询标识
                    imgLog.setConsult(ct.getConsult());
                    // 设置图片URL
                    imgLog.setContent(image);
                    imgLog.setDel("1");
                    infoLog.setType(0);
                    imgLog.setCzrq(new Date());
                    // 图片类型
                    imgLog.setChatType(2);
                    // 添加到待保存队列
                    logs.add(imgLog);
                }
            }
        }
        // 语音日志
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ct.getVoice())) {
            ConsultTeamLogDo voiceLog = new ConsultTeamLogDo();
            // 设置咨询标识
            voiceLog.setConsult(ct.getConsult());
            // 设置语音URL
            voiceLog.setContent(ct.getVoice());
            voiceLog.setDel("1");
            infoLog.setType(0);
            // 语音类型
            voiceLog.setChatType(3);
            voiceLog.setCzrq(new Date());
            // 添加到待保存队列
            logs.add(voiceLog);
        }
        if (!logs.isEmpty()) {
            Iterable<ConsultTeamLogDo> iterable = consultTeamLogDao.save(logs);
            if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
                // 日志保存失败
                throw new Exception("consult team log save failed!");
            }
        }
        // 患者提问或追问，给医生发消息
        // sendMessage(ct.getDoctor(), ct.getPatient(), "三师咨询", "您有新的三师咨询消息", ct.getConsult(), 116, 1, 0, 0);
        return content;
    }

    /**
     * 添加续方咨询
     *
     * @param outpatientCode
     * @param patient
     * @param doctorCode
     * @param reason
     * @return
     */
    public JSONObject addPrescriptionConsult(String outpatientCode, String patient, String doctorCode, ConsultTeamDo ct, String reason, Integer type, String wxId, String source) throws Exception {

        synchronized (outpatientCode.intern()) {

            //1、获取his就诊记录详情（保存续方表、药品续方信息表、续方疾病类型表）
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outpatientCode);

            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                //眼科接诊时更新眼科通状态
                if (!flag) {
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(wlyyOutpatientDO.getId());
                    if (businessOrderDO != null) {
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "5");
                    }
                }
            }


            //2. 调用HIS挂号接口---START  移到CONTROLER层，直接调用挂号接口
//			DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(doctorCode,wlyyOutpatientDO.getHospital());
//			if(doctorMappingDO==null){
//				throw new RuntimeException("未找到医生映射信息");
//			}
//
//			net.sf.json.JSONObject rs = entranceService.BS10111(wlyyOutpatientDO.getCardNo(),doctorMappingDO.getMappingCode(),wlyyOutpatientDO.getDept(),null,wlyyOutpatientDO.getWinNo(),demoFlag);
//			String rsCode = (String)rs.get("@RESULT");
//			if("0".equals(rsCode)){
//				//存储挂号号
//				String serialNo = (String)rs.get("serial_no");
//				wlyyOutpatientDO.setRegisterNo(serialNo);
//				String conNo = (String)rs.get("@times");
//				wlyyOutpatientDO.setConNo(conNo);
//			}
//
//			//保存日志
//			WlyyHttpLogDO log = new WlyyHttpLogDO();
//			log.setCode("registerOutPatient");
//			log.setName("挂号");
//			log.setPatient(wlyyOutpatientDO.getPatient());
//			log.setDoctor(doctorCode);
//			log.setResponse(rs.toString());
//			log.setRequest("outPatientId="+outpatientCode+"&doctor="+doctorCode);
//			log.setStatus(rsCode);
//			log.setCreateTime(new Date());
//			wlyyHttpLogDao.save(log);

            // 调用HIS挂号接口---END


            /**
             * toto 判断是否存在未审核的复诊
             */


            BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
//			doctorCode = doctor.getCode();
            // 查询患者信息
            BasePatientDO p = basePatientDao.findById(patient);

            if (!"0".equals(wlyyOutpatientDO.getStatus())) {
                throw new RuntimeException("该就诊记录已被取消，无法接单！");
            }
            BasePatientDO patientDO = basePatientDao.findById(wlyyOutpatientDO.getPatient());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", patientDO.getName() + "申请复诊");
            jsonObject.put("content", wlyyOutpatientDO.getDescription());
            jsonObject.put("age", DateUtil.getAgeForIdcard(patientDO.getIdcard()));
            jsonObject.put("sex", patientDO.getSex());
            jsonObject.put("name", patientDO.getName());

            ConsultDo consultDo = consultDao.findByRelationCode(outpatientCode);
            if (consultDo == null) {
                //4、创建咨询
                JSONObject users = new JSONObject();//咨询参与者

                String consultTitle = "";
                //协同门诊
                if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
                    users.put(wlyyOutpatientDO.getGeneralDoctor(), 0);
                    ct.setType(12);
                    consultTitle = "申请协同门诊";

                    JSONObject consultName = new JSONObject();
                    consultName.put("patientName", p.getName());
                    consultName.put("doctorName", doctor.getName());
                    jsonObject.put("name", consultName.toJSONString());
                } else if ("3".equals(wlyyOutpatientDO.getOutpatientType())) {
                    if (wlyyOutpatientDO.getType().equalsIgnoreCase("1")) {
                        users.put(patient, 0);
                        ct.setType(1);
                        consultTitle = "图文咨询";
                    } else if (wlyyOutpatientDO.getType().equalsIgnoreCase("2")) {
                        users.put(patient, 0);
                        ct.setType(17);
                        consultTitle = "视频咨询";
                    } else {
                        users.put(patient, 0);
                        ct.setType(15);
                        consultTitle = "家医咨询";
                    }

                } else {
                    users.put(patient, 0);
                    consultTitle = "申请复诊";
                }

                String content = jsonObject.toString();

                users.put(doctorCode, 0);
                //关联业务code
                ct.setRelationCode(outpatientCode);
                //医生信息
                ct.setDoctor(doctorCode);
                ct.setDoctorName(doctor.getName());
                // 设置患者信息
                ct.setPatient(patient);
                ct.setSymptoms(wlyyOutpatientDO.getDescription());

                // 设置患者姓名
                ct.setName(p.getName());
                // 设置患者生日
                ct.setBirthday(p.getBirthday());
                //新增性别
                ct.setSex(p.getSex());
                // 设置患者头像
                ct.setPhoto(p.getPhoto());
                // 设置操作日期
                ct.setCzrq(new Date());
                ct.setDel("1");
                ct.setStatus(0);
                ct.setEvaluate(0);
                // 医生未读数量为1
                ct.setDoctorRead(1);
                //添加就诊图片
                ct.setImages(wlyyOutpatientDO.getDiseaseImg());
                // 添加咨询记录
                ConsultDo consult = addConsult(ct.getPatient(), consultTitle, ct.getSymptoms(), ct.getImages(), ct.getType(), wlyyOutpatientDO.getSource());
                // 设置关联指导
                consult.setGuidance(ct.getGuidance());
                //关联业务code
                consult.setRelationCode(outpatientCode);
                //支付状态为1
                consult.setPayStatus(1);
                // 设置咨询标识
                ct.setConsult(consult.getId());

                //推送给IM去创建议题，取得成员消息

                JSONObject messages = new JSONObject();
                JSONObject obj = new JSONObject();
                String sessionId = "";
                //协同门诊
                if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
                    BaseDoctorDO generalDoctor = baseDoctorDao.findById(wlyyOutpatientDO.getGeneralDoctor());
                    messages = imUtil.getCreateTopicMessage(generalDoctor.getId(), generalDoctor.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
                    //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+12(图文,视频,图文+视频)
                    sessionId = patient + "_" + outpatientCode + "_" + ct.getType();
                    obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_COLLABORATION_HOSPITAL);

                } else if ("3".equals(wlyyOutpatientDO.getOutpatientType())) {
                    messages = imUtil.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
                    //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+9(图文,视频,图文+视频)
                    sessionId = patient + "_" + outpatientCode + "_" + ct.getType();

                    if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        //图文咨询
                        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_MUC);
                    } else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        //视频咨询
                        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_MUC_VIDEO);
                    } else {
                        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_GENERAL_EXPERT);
                    }
                } else {
                    messages = imUtil.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
                    //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+9(图文,视频,图文+视频)
                    sessionId = patient + "_" + outpatientCode + "_" + ct.getType();

                    if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                        //图文复诊
                        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_EXAMINATION);
                    } else {
                        //视频复诊+图文复诊
                        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_EXAMINATION_VIDEO);
                    }

                }


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

                //设置咨询code
//			wlyyOutpatientDO.setConsult(consult.getCode());
//			prescriptionDao.save(prescription);

                //6、记录咨询的医生详情
                ConsultTeamDoctorDo cd = new ConsultTeamDoctorDo();
                cd.setConsult(consult.getId());
                cd.setDel("1");
                cd.setCzrq(new Date());
                cd.setTo(doctorCode);
                consultTeamDoctorDao.save(cd);

                //7、发送系统消息提示团队长有未审核的消息
//			addCheckMessage(prescription, sessionId, p);

                //8、 保存医生咨询信息
                // 添加咨询转发记录
                // 添加医生咨询日志
                addLogs(ct);
                //只有勾选同同时发起视频邀请的时候才发送模板消息
				/*if("2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
					wxTemplateService.sendWeTempMesMiniProgram(wlyyOutpatientDO.getDoctor(),wlyyOutpatientDO.getDoctorName(),wlyyOutpatientDO.getConsumer(),wlyyOutpatientDO.getConsumerName(),consult.getId());
				}*/
            }
            String sessionIds = patient + "_" + outpatientCode + "_" + ct.getType();
            JSONObject result = imUtil.getSingleSessionInfo(sessionIds, doctorCode);
            wlyyOutpatientDO.setStatus("1");//修改就诊记录为就诊中
            wlyyOutpatientDO.setConDate(new Date());
            wlyyOutpatientDO.setDoctor(doctorCode);
            wlyyOutpatientDO.setDoctorName(doctor.getName());
            outpatientDao.save(wlyyOutpatientDO);

            //修改候诊室状态为已诊
            List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientCode);
            if (roomDOs != null && roomDOs.size() > 0) {
                for (WlyyHospitalWaitingRoomDO roomDO : roomDOs) {
                    roomDO.setVisitStatus(2);//修改候诊室状态为已诊
                    roomDO.setDoctor(doctorCode);
                    roomDO.setDoctorName(doctor.getName());
                    hospitalWaitingRoomDao.save(roomDO);
                }
            }


            //发送外层SOCKET消息 在线复诊
            if ("1".equals(wlyyOutpatientDO.getOutpatientType())) {
                System.out.println("发送外层SOCKET消息:在线复诊");
                JSONObject object = new JSONObject();
                object.put("socket_sms_type", 5);
                object.put("relation_code", wlyyOutpatientDO.getId());
                imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), wlyyOutpatientDO.getConsumer(), "1", object.toString());
                //医生接诊发送导诊护士外层消息
                this.sendOutpatientGuaidanceMessage(wlyyOutpatientDO);
            } else if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
                //协同门诊
                System.out.println("发送外层SOCKET消息:协同门诊");
                JSONObject object = new JSONObject();
                object.put("socket_sms_type", 5);
                object.put("relation_code", wlyyOutpatientDO.getId());
                imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), wlyyOutpatientDO.getGeneralDoctor(), "1", object.toString());
                //医生接诊发送导诊护士外层消息
                this.sendOutpatientGuaidanceMessage(wlyyOutpatientDO);
            } else {
                //专家咨询
                System.out.println("发送外层SOCKET消息:专家咨询");
                JSONObject object = new JSONObject();
                object.put("socket_sms_type", 5);
                object.put("relation_code", wlyyOutpatientDO.getId());
                imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), wlyyOutpatientDO.getConsumer(), "1", object.toString());
                //医生接诊发送导诊护士外层消息
                this.sendOutpatientGuaidanceMessage(wlyyOutpatientDO);
            }
            return result;
        }
    }

    /**
     * 添加复诊咨询
     *
     * @return
     */
    public JSONObject addConsult(String outpatientCode, String patient, String doctorCode, ConsultTeamDo ct, String reason, Integer type, String wxId, String source) throws Exception {
        //1、获取his就诊记录详情（保存续方表、药品续方信息表、续方疾病类型表）
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outpatientCode);
        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
//			doctorCode = doctor.getCode();
        // 查询患者信息
        BasePatientDO p = basePatientDao.findById(patient);
        JSONObject jsonObject = new JSONObject();
        if ("3".equals(wlyyOutpatientDO.getOutpatientType())) {
            jsonObject.put("title", p.getName() + "申请咨询");
        } else {
            jsonObject.put("title", p.getName() + "申请复诊");
        }
        jsonObject.put("content", wlyyOutpatientDO.getDescription());
        jsonObject.put("age", DateUtil.getAgeForIdcard(p.getIdcard()));
        jsonObject.put("sex", p.getSex());
        jsonObject.put("name", p.getName());
        if (null != wlyyOutpatientDO) {
            BasePatientDO outPatient = basePatientDao.findById(wlyyOutpatientDO.getPatient());
            if (null != outPatient) {
                jsonObject.put("age", DateUtil.getAgeForIdcard(outPatient.getIdcard()));
                jsonObject.put("sex", outPatient.getSex());
                jsonObject.put("name", outPatient.getName());
            }

        }
        //4、创建咨询
        JSONObject users = new JSONObject();//咨询参与者

        String consultTitle = "";
        //协同门诊
        if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
            users.put(wlyyOutpatientDO.getGeneralDoctor(), 0);
            ct.setType(12);
            consultTitle = "申请协同门诊";
            JSONObject consultName = new JSONObject();
            consultName.put("patientName", p.getName());
            consultName.put("doctorName", doctor.getName());
            jsonObject.put("name", consultName.toJSONString());
        } else if ("3".equals(wlyyOutpatientDO.getOutpatientType())) {
            if (wlyyOutpatientDO.getType().equalsIgnoreCase("1")) {
                users.put(patient, 0);
                ct.setType(1);
                consultTitle = "图文咨询";
            } else if (wlyyOutpatientDO.getType().equalsIgnoreCase("2")) {
                users.put(patient, 0);
                ct.setType(17);
                consultTitle = "视频咨询";
            } else {
                users.put(patient, 0);
                ct.setType(15);
                consultTitle = "家医咨询";
            }

        } else {
            users.put(patient, 0);
            consultTitle = "申请复诊";
        }

        String content = jsonObject.toString();

        users.put(doctorCode, 0);
        //关联业务code
        ct.setRelationCode(outpatientCode);
        //医生信息
        ct.setDoctor(doctorCode);
        ct.setDoctorName(doctor.getName());
        // 设置患者信息
        ct.setPatient(patient);
        ct.setSymptoms(wlyyOutpatientDO.getDescription());

        // 设置患者姓名
        ct.setName(p.getName());
        // 设置患者生日
        ct.setBirthday(p.getBirthday());
        //新增性别
        ct.setSex(p.getSex());
        // 设置患者头像
        ct.setPhoto(p.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        ct.setEvaluate(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        //添加就诊图片
        ct.setImages(wlyyOutpatientDO.getDiseaseImg());
        // 添加咨询记录
        ConsultDo consult = addConsult(ct.getPatient(), consultTitle, ct.getSymptoms(), ct.getImages(), ct.getType(), wlyyOutpatientDO.getSource());
        // 设置关联指导
        consult.setGuidance(ct.getGuidance());
        //关联业务code
        consult.setRelationCode(outpatientCode);
        //支付状态为1
        consult.setPayStatus(1);
        // 设置咨询标识
        ct.setConsult(consult.getId());

        //推送给IM去创建议题，取得成员消息

        JSONObject messages = new JSONObject();
        JSONObject obj = new JSONObject();
        String sessionId = "";
        //协同门诊
        if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
            BaseDoctorDO generalDoctor = baseDoctorDao.findById(wlyyOutpatientDO.getGeneralDoctor());
            messages = imUtil.getCreateTopicMessage(generalDoctor.getId(), generalDoctor.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
            //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+12(图文,视频,图文+视频)
            sessionId = patient + "_" + outpatientCode + "_" + ct.getType();
            obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_COLLABORATION_HOSPITAL);

        } else if ("3".equals(wlyyOutpatientDO.getOutpatientType())) {
            messages = imUtil.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
            //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+1，17.15图文,视频,家医
            sessionId = patient + "_" + outpatientCode + "_" + ct.getType();

            if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                //图文咨询
                obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_MUC);
            } else if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                //视频咨询
                obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_MUC_VIDEO);
            } else {
                obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_GENERAL_EXPERT);
            }
        } else {
            messages = imUtil.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), doctorCode);
            //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+9(图文,视频,图文+视频)
            sessionId = patient + "_" + outpatientCode + "_" + ct.getType();

            if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                //图文复诊
                obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_EXAMINATION);
            } else {
                //视频复诊+图文复诊
                obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_EXAMINATION_VIDEO);
            }

        }

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

        //设置咨询code
//			wlyyOutpatientDO.setConsult(consult.getCode());
//			prescriptionDao.save(prescription);

        //6、记录咨询的医生详情
        ConsultTeamDoctorDo cd = new ConsultTeamDoctorDo();
        cd.setConsult(consult.getId());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(doctorCode);
        consultTeamDoctorDao.save(cd);

        //7、发送系统消息提示团队长有未审核的消息
//			addCheckMessage(prescription, sessionId, p);

        //8、 保存医生咨询信息
        // 添加咨询转发记录
        // 添加医生咨询日志
        addLogs(ct);
        JSONObject result = imUtil.getSingleSessionInfo(sessionId, doctorCode);
        //发送外层SOCKET消息 在线复诊
        if ("1".equals(wlyyOutpatientDO.getOutpatientType()) || "3".equals(wlyyOutpatientDO.getOutpatientType())) {
            System.out.println("发送外层SOCKET消息:在线复诊");
            JSONObject object = new JSONObject();
            object.put("socket_sms_type", 5);
            object.put("relation_code", wlyyOutpatientDO.getId());
            imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), wlyyOutpatientDO.getConsumer(), "1", object.toString());
            //医生接诊发送导诊护士外层消息
            this.sendOutpatientGuaidanceMessage(wlyyOutpatientDO);
        } else if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
            //协同门诊
            System.out.println("发送外层SOCKET消息:协同门诊");
            JSONObject object = new JSONObject();
            object.put("socket_sms_type", 5);
            object.put("relation_code", wlyyOutpatientDO.getId());
            imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), wlyyOutpatientDO.getGeneralDoctor(), "1", object.toString());
            //医生接诊发送导诊护士外层消息
            this.sendOutpatientGuaidanceMessage(wlyyOutpatientDO);
        }
        return result;
    }


    /**
     * 医生接诊发送导诊护士外层消息
     *
     * @param wlyyOutpatientDO
     */
    private void sendOutpatientGuaidanceMessage(WlyyOutpatientDO wlyyOutpatientDO) {

        System.out.println("发送导诊护士外层SOCKET消息:医生接诊");
        JSONObject object = new JSONObject();
        object.put("socket_sms_type", 7);
        object.put("relation_code", "");
        object.put("msg_time", DateUtil.dateToStrLong(new Date()));
        String msgStr = wlyyOutpatientDO.getDoctorName() + "医生诊室 " + wlyyOutpatientDO.getPatientName();
        if ("1".equals(wlyyOutpatientDO.getOutpatientType())) {
            msgStr = msgStr + "  已开始复诊";
        } else if ("2".equals(wlyyOutpatientDO.getOutpatientType())) {
            msgStr = msgStr + "  已开始协同门诊";
        } else {
            msgStr = msgStr + "  已开始专家咨询";
        }
        object.put("msg", msgStr);

        List<BaseDoctorRoleDO> assistantList = baseDoctorRoleDao.findByRoleCode("assistant");
        for (BaseDoctorRoleDO baseDoctorRoleDO : assistantList) {
            imUtil.sendMessage(wlyyOutpatientDO.getDoctor(), baseDoctorRoleDO.getDoctorCode(), "1", object.toString());
        }
    }


    /**
     * 居民结束咨询
     *
     * @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 name = "";
        String returnJson = "";

        /**
         * 发送评价消息
         */
        BaseDoctorDO doctor = baseDoctorDao.findById(consultTeam.getDoctor());
        BasePatientDO patient = basePatientDao.findById(consultTeam.getPatient());
        JSONObject evalueContent = new JSONObject();
        evalueContent.put("patientCode", consultTeam.getPatient());
        evalueContent.put("patientName", patient.getName());
        evalueContent.put("doctorCode", consultTeam.getDoctor());
        evalueContent.put("doctorName", doctor.getName());
        evalueContent.put("doctorPhoto", doctor.getPhoto());
        evalueContent.put("consultCode", consult);

        //保存系统消息服务评价
        systemMsgEvaluation(doctor, patient, cons, consultTeam, consult, wxId);

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

        //判断是否是在线复诊
        if (cons.getRelationCode() != null) {
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(cons.getRelationCode());
            if (wlyyOutpatientDO != null && wlyyOutpatientDO.getId() != null) {
                if (wlyyOutpatientDO.getStatus().equalsIgnoreCase("0")) {
                    wlyyOutpatientDO.setStatus("-1");
                } else {
                    wlyyOutpatientDO.setStatus("3");
                }
                outpatientDao.save(wlyyOutpatientDO);

            }

            List<WlyyHospitalWaitingRoomDO> wlyyHospitalWaitingRoomDOS = hospitalWaitingRoomDao.findByOutpatientId(cons.getRelationCode());
            if (!wlyyHospitalWaitingRoomDOS.isEmpty()) {
                for (WlyyHospitalWaitingRoomDO wlyyHospitalWaitingRoomDO : wlyyHospitalWaitingRoomDOS) {
                    wlyyHospitalWaitingRoomDO.setVisitStatus(2);
                    hospitalWaitingRoomDao.save(wlyyHospitalWaitingRoomDO);
                }
            }
        }

        if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
            if (!flag) {
                BusinessOrderDO businessOrderDO = new BusinessOrderDO();
                if (cons.getRelationCode() != null) {
                    businessOrderDO = businessOrderDao.selectByRelationCode(cons.getRelationCode());
                } else {
                    businessOrderDO = businessOrderDao.selectByRelationCode(consult);
                }
                if (businessOrderDO != null) {
                    String sql = "SELECT * FROM topics t where " +
                            "t.id='" + consult + "' and t.reply_user is null and t.reply is null and t.status IN(0,1) ";
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
                    System.out.println("sql+-----" + sql);
                    if (null != mapList && mapList.size() > 0 && mapList.size() == 1) {
                        //医生没回复的话要把状态改为关闭 status=？
                        System.out.println("-------------------进入未回复状态同步--------------------");
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "3");
                    } else {
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "4");
                    }
                }
            }
        }


        return 1;
    }

    /**
     * 居民取消复诊
     *
     * @param consult     咨询CODE
     * @param endOperator 操作人
     * @param endType     1居民 2医生
     * @return
     */
    public int cancelRevisit(String consult, String endOperator, int endType) {

        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(consult);

        ConsultDo cons = consultDao.findOne(consult);

        if (consultTeam.getStatus() == 1) {
            return -1;
        }


        String name = "";
        String returnJson = "";

        /**
         * 发送评价消息
         */
        BaseDoctorDO doctor = baseDoctorDao.findById(consultTeam.getDoctor());
        BasePatientDO patient = basePatientDao.findById(consultTeam.getPatient());
		/*JSONObject evalueContent = new JSONObject();
		evalueContent.put("patientCode",consultTeam.getPatient());
		evalueContent.put("patientName",patient.getName());
		evalueContent.put("doctorCode",consultTeam.getDoctor());
		evalueContent.put("doctorName",doctor.getName());
		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);

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

        //判断是否是在线复诊
		/*if(cons.getRelationCode() != null){
			WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(cons.getRelationCode());
			if(wlyyOutpatientDO != null && wlyyOutpatientDO.getId() != null){
				if (wlyyOutpatientDO.getStatus().equalsIgnoreCase("0")){
					wlyyOutpatientDO.setStatus("-1");
				}else {
					wlyyOutpatientDO.setStatus("3");
				}
				outpatientDao.save(wlyyOutpatientDO);

			}

			List<WlyyHospitalWaitingRoomDO> wlyyHospitalWaitingRoomDOS = hospitalWaitingRoomDao.findByOutpatientId(cons.getRelationCode());
			if(!wlyyHospitalWaitingRoomDOS.isEmpty()){
				for (WlyyHospitalWaitingRoomDO wlyyHospitalWaitingRoomDO:wlyyHospitalWaitingRoomDOS){
					wlyyHospitalWaitingRoomDO.setVisitStatus(2);
					hospitalWaitingRoomDao.save(wlyyHospitalWaitingRoomDO);
				}
			}
		}*/

        if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
            if (!flag) {
                BusinessOrderDO businessOrderDO = new BusinessOrderDO();
                if (cons.getRelationCode() != null) {
                    businessOrderDO = businessOrderDao.selectByRelationCode(cons.getRelationCode());
                } else {
                    businessOrderDO = businessOrderDao.selectByRelationCode(consult);
                }
                if (businessOrderDO != null) {
                    String sql = "SELECT * FROM topics t where " +
                            "t.id='" + consult + "' and t.reply_user is null and t.reply is null and t.status IN(0,1) ";
                    List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
                    System.out.println("sql+-----" + sql);
                    if (null != mapList && mapList.size() > 0 && mapList.size() == 1) {
                        //医生没回复的话要把状态改为关闭 status=？
                        System.out.println("-------------------进入未回复状态同步--------------------");
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "3");
                    } else {
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "4");
                    }
                }
            }
        }


        return 1;
    }

    public void systemMsgEvaluation(BaseDoctorDO doctor, BasePatientDO patient, ConsultDo cons, ConsultTeamDo consultTeam, String consult, String wxId) {

        SystemMessageDO messageDO = new SystemMessageDO();
        messageDO.setType("10");
        messageDO.setTitle("服务评价");
        messageDO.setSender(doctor.getId());
        messageDO.setSenderName(doctor.getName());
        messageDO.setRelationCode(consult);
        messageDO.setReceiver(patient.getId());
        messageDO.setReceiverName(patient.getName());

        net.sf.json.JSONObject data = new net.sf.json.JSONObject();
        data.put("name", patient.getName());
        data.put("age", IdCardUtil.getAgeForIdcard(patient.getIdcard()));
        data.put("gender", StringUtils.isEmpty(patient.getSex()) ? null : patient.getSex().toString());
        data.put("question", consultTeam.getSymptoms());

        String type = "";
        if (cons.getType() != null && 1 == cons.getType()) {
            String msg = patient.getName() + "，您好！您有1条图文咨询已结束，请及时对咨询医生进行评价。";
            data.put("msg", msg);
            data.put("type", "1");
            type = "1";
        }
        if (cons.getType() != null && 9 == cons.getType()) {
            String msg = patient.getName() + "，您好！您有1条图文复诊已结束，请及时对咨询医生进行评价。";
            data.put("msg", msg);
            data.put("type", "9");
            type = "9";
        }
        if (cons.getType() != null && 16 == cons.getType()) {
            String msg = patient.getName() + "，您好！您有1条视频复诊已结束，请及时对咨询医生进行评价。";
            data.put("msg", msg);
            data.put("type", "16");
            type = "16";
        }
        if (cons.getType() != null && 17 == cons.getType()) {
            String msg = patient.getName() + "，您好！您有1条视频咨询已结束，请及时对咨询医生进行评价。";
            data.put("msg", msg);
            data.put("type", "17");
            type = "17";
        }
        messageDO.setData(data.toString());
        try {
            systemMessageService.saveMessage(messageDO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            ykyyService.pushNotificationToYktPatient(patient.getYktId(), messageDO.getTitle(), data.get("msg").toString());
        }

        prescriptionService.sendWxTemplateMsg(wxId, "", consultTeam, type, "evaluateRemind", "");

    }


    /**
     * 根据咨询CODE获取session_id
     *
     * @param consult
     * @return
     */
    public JSONObject getTopic(String consult) throws Exception {

        JSONObject object = imUtil.getTopic(consult);

        ConsultTeamDo consultTeamDo = consultTeamDao.findByConsult(consult);

        ConsultDo consultDo = consultDao.findOne(consult);

        object.put("doctorCode", consultTeamDo.getDoctor());
        //支付状态
        object.put("payStatus", consultDo.getPayStatus());

        return object;
    }


    /**
     * 获取咨询问题，图片，居民信息
     *
     * @param consult
     * @param patientCode
     * @return
     */
    public JSONObject getConsultInfoAndPatientInfo(String consult, String patientCode) {
        ConsultDo consultDo = consultDao.findOne(consult);
        BasePatientDO basePatientDO = null;
        if (StringUtils.isEmpty(patientCode)) {
            patientCode = consultDo.getPatient();
        }
        basePatientDO = basePatientDao.findById(patientCode);

        JSONObject result = new JSONObject();

        JSONObject patientinfoObj = new JSONObject();
        patientinfoObj.put("name", basePatientDO.getName());
        patientinfoObj.put("sex", basePatientDO.getSex());
        patientinfoObj.put("mobile", basePatientDO.getMobile());
        patientinfoObj.put("address", basePatientDO.getAddress());
        patientinfoObj.put("photo", basePatientDO.getPhoto());
        patientinfoObj.put("idCard", basePatientDO.getIdcard());
        Integer age = DateUtil.getAgeForIdcard(basePatientDO.getIdcard());
        patientinfoObj.put("age", age);
        result.put("patientInfo", patientinfoObj);
        result.put("consultDo", consultDo);
        return result;
    }


    /**
     * 根据复诊记录获取咨询CODE
     *
     * @param outpatientid
     * @return
     */
    public String getConsultCodeByOutpatientId(String outpatientid) {
        String totalSql = "SELECT id as \"id\" FROM wlyy_consult WHERE relation_code='" + outpatientid + "' ";
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);
        String id = "";
        if (rstotal != null && rstotal.size() > 0) {
            id = rstotal.get(0).get("id").toString();
        }
        return id;
    }

    /**
     * 根据咨询CODE获取就诊记录ID
     *
     * @param consult
     * @return
     */
    public String getOutpatientidByConsoultCode(String consult) {
        String totalSql = "SELECT relation_code as \"relation_code\" FROM wlyy_consult WHERE id='" + consult + "' ";
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql);
        String id = "";
        if (rstotal != null && rstotal.size() > 0) {
            id = rstotal.get(0).get("relation_code").toString();
        }
        return id;
    }

    /**
     * 评价咨询
     *
     * @param consult
     * @param scoreContent
     * @param type
     */
    public void evaluationByConsultCode(String consult, String scoreContent, Integer type, String bannerList) throws Exception {

        JSONArray jsonArray = JSONArray.parseArray(scoreContent);

        Integer totalScore = 0;

        ConsultTeamDo consultTeamDo = consultTeamDao.findByConsult(consult);
        if (!jsonArray.isEmpty() && jsonArray.size() > 0) {
            BaseEvaluateScoreDO evaluateScoreDO = new BaseEvaluateScoreDO();
            evaluateScoreDO.setDoctor(consultTeamDo.getDoctor());
            evaluateScoreDO.setDoctorName(consultTeamDo.getDoctorName());
            evaluateScoreDO.setPatient(consultTeamDo.getPatient());
            evaluateScoreDO.setPatientName(consultTeamDo.getName());
            evaluateScoreDO.setRelationCode(consult);
            evaluateScoreDO.setEvaluateType(1);
            evaluateScoreDO.setType(type);
            evaluateScoreDO.setId(UUID.randomUUID().toString());

            String content = "";//评价内容

            List<BaseEvaluateDO> baseEvaluateDOS = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject job = jsonArray.getJSONObject(i);
                if ("4".equals(job.getString("scoreType"))) {//非评价类型

                    content = job.getString("content");
                    BaseEvaluateDO baseEvaluateDO = new BaseEvaluateDO();
                    baseEvaluateDO.setScoreType(job.getString("scoreType"));
                    baseEvaluateDO.setScore(new Double(String.valueOf(job.getInteger("score"))));
                    baseEvaluateDO.setRelationCode(evaluateScoreDO.getId());
                    baseEvaluateDO.setContent(content);
                    baseEvaluateDOS.add(baseEvaluateDO);
                } else {
                    BaseEvaluateDO baseEvaluateDO = new BaseEvaluateDO();
                    baseEvaluateDO.setScoreType(job.getString("scoreType"));
                    baseEvaluateDO.setScore(new Double(String.valueOf(job.getInteger("score"))));
                    baseEvaluateDO.setRelationCode(evaluateScoreDO.getId());
                    totalScore += job.getInteger("score");
                    baseEvaluateDOS.add(baseEvaluateDO);
                }
            }
            evaluateScoreDO.setScore((double) totalScore / 3);

            evaluateScoreDO = baseEvaluateScoreDao.save(evaluateScoreDO);

            for (BaseEvaluateDO baseEvaluateDO : baseEvaluateDOS) {
                baseEvaluateDO.setRelationCode(evaluateScoreDO.getId());
                baseEvaluateDO = baseEvaluateDao.save(baseEvaluateDO);
                if ("4".equalsIgnoreCase(baseEvaluateDO.getScoreType())) {
                    BaseUserMessageDO baseUserMessageDO = new BaseUserMessageDO();
                    baseUserMessageDO.setCreateTime(new Date());
                    baseUserMessageDO.setReceiver(consultTeamDo.getDoctor());
                    BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(consultTeamDo.getDoctor());
                    if (baseDoctorDO != null) {
                        baseUserMessageDO.setReceiverName(baseDoctorDO.getName());
                    }
                    baseUserMessageDO.setSender(consultTeamDo.getPatient());
                    baseUserMessageDO.setSenderName(consultTeamDo.getName());
                    baseUserMessageDO.setRelationCode(baseEvaluateDO.getRelationCode());
                    if (consultTeamDo.getType() == 1 || 15 == consultTeamDo.getType()) {
                        baseUserMessageDO.setRelationType(3);
                        baseUserMessageDO.setRelationName("专家咨询");
                    } else if (consultTeamDo.getType() == 9 || 16 == consultTeamDo.getType()) {
                        baseUserMessageDO.setRelationType(4);
                        baseUserMessageDO.setRelationName("在线复诊");
                    }
                    baseUserMessageDO.setContent(baseEvaluateDO.getContent());
                    baseUserMessageDO.setDel(1);
                    baseUserMessageDO.setStatus(1);
                    baseUserMessageDO.setType(type);
                    baseUserMessageDO.setUpdateTime(new Date());
                    baseUserMessageDO.setIsRead(0);
                    userMessageDao.save(baseUserMessageDO);
                    if (!StringUtils.isEmpty(bannerList)) {
                        System.out.println("-------");
                        System.out.println(bannerList);
                        String[] str = bannerList.split(",");
                        for (int i = 0; i < str.length; i++) {
                            BaseBannerDoctorDO bannerDoctorDO = new BaseBannerDoctorDO();
                            bannerDoctorDO.setCreateTime(new Date());
                            bannerDoctorDO.setUpdateTime(new Date());
                            bannerDoctorDO.setPatientId(baseUserMessageDO.getSender());
                            bannerDoctorDO.setPatientName(baseUserMessageDO.getSenderName());
                            bannerDoctorDO.setDoctor(baseUserMessageDO.getReceiver());
                            bannerDoctorDO.setDoctorName(baseUserMessageDO.getReceiverName());
                            bannerDoctorDO.setBannerId(str[i]);
                            bannerDoctorDO.setRelationCode(consult);
                            if (consultTeamDo.getType() == 1 || 15 == consultTeamDo.getType()) {
                                bannerDoctorDO.setRelationType(3);
                                bannerDoctorDO.setRelationName("专家咨询");
                            } else if (consultTeamDo.getType() == 9 || 16 == consultTeamDo.getType()) {
                                bannerDoctorDO.setRelationType(4);
                                bannerDoctorDO.setRelationName("在线复诊");
                            }
                            bannerDoctorDO.setContent(baseEvaluateDO.getContent());
                            baseBannerDoctorDao.save(bannerDoctorDO);
                        }
                    }
                }

            }

            consultTeamDo.setEvaluate(1);//保存已评价标识
            consultTeamDo.setEvaluateTime(new Date());
            consultTeamDao.save(consultTeamDo);

            ConsultDo consultDo = consultDao.findOne(consult);

            //如果是复诊咨询，或者协同门诊，则修改成已评价
            if (9 == consultDo.getType() || 12 == consultDo.getType() || 16 == consultDo.getType()) {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(consultTeamDo.getRelationCode());
                wlyyOutpatientDO.setEvaluateStatus("1");
                outpatientDao.save(wlyyOutpatientDO);
            }


        }

    }

    /**
     * 修改医生在线状态
     *
     * @param consultStatus
     * @param doctor
     */
    public void updateDoctorConsultStatus(String consultStatus, String doctor) {
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        baseDoctorDO.setConsultStatus(consultStatus);
        baseDoctorDao.save(baseDoctorDO);
    }

    public List<Map<String, Object>> getEvaluationByConsultCode(String consult) {
        //查询评价明细
        String sqlScoreList = "SELECT " +
                "a.score as \"score\"," +
                "a.score_type as \"score_type\"," +
                "a.content as \"content\",";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sqlScoreList += "date_format(b.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"create_time\",";
            } else {
                sqlScoreList += "to_char(b.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"create_time\",";
            }
        } else {
            sqlScoreList += "date_format(b.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"create_time\",";
        }

        sqlScoreList += "c.type as \"type\"," +
                "c.name as \"patientname\"," +
                "b.id as \"id\"," +
                "c.photo as \"patientphoto\"," +
                "b.type as \"niming\" " +
                "FROM " +
                "base_evaluate a " +
                "LEFT JOIN base_evaluate_score b ON b.id=a.relation_code " +
                "LEFT JOIN wlyy_consult_team c ON c.consult=b.relation_code " +
                "WHERE a.relation_code=b.id " +
                "AND c.consult='" + consult + "'";
        System.out.println(sqlScoreList);
        List<Map<String, Object>> scoreList = hibenateUtils.createSQLQuery(sqlScoreList);
        if (scoreList.isEmpty()) {
            return null;
        } else {
            Map<String, Object> map = new HashMap<>();
            String sql = "select b.id AS \"id\", b.name AS \"name\",b.img AS \"img\" from base_banner_doctor a LEFT JOIN base_banner b on a.banner_id= b.id where a.relation_code = '" + consult + "'";
            List<Map<String, Object>> bannerlist = hibenateUtils.createSQLQuery(sql);
            map.put("bannerList", bannerlist);
            scoreList.add(map);
            return scoreList;
        }
    }

    /**
     * 按会话类型获取会话总数
     *
     * @param userid
     * @param type
     * @return
     */
    public Integer sessionCountByType(String userid, Integer type, Integer status) {
        return imUtil.sessionCountByType(userid, type, status);
    }

    /**
     * 获取所有会话未读消息数
     *
     * @param userid
     * @param type
     * @return
     */
    public Integer SessionsUnreadMessageCount(String userid, String type) {
        return imUtil.SessionsUnreadMessageCount(userid, type);
    }

    public Integer SessionsUnreadMessageCountByUserId(String userid) {
        return imUtil.SessionsUnreadMessageCountByUserId(userid);
    }

    /**
     * 发送复诊诊断和药品消息
     *
     * @param wlyyPrescriptionVO
     * @return
     */
    public void pushPrescriptionImMessage(WlyyPrescriptionVO wlyyPrescriptionVO) throws Exception {

        //获取诊断
        List<WlyyPrescriptionDiagnosisVO> wlyyPrescriptionDiagnosisVOS = wlyyPrescriptionVO.getDiagnosisVOs();
        if (wlyyPrescriptionDiagnosisVOS != null && wlyyPrescriptionDiagnosisVOS.size() != 0) {
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(wlyyPrescriptionVO.getOutpatientId());
            if (wlyyOutpatientDO.getOutpatientType() != null) {
                if (wlyyOutpatientDO.getOutpatientType().equalsIgnoreCase("1") && wlyyOutpatientDO.getType().equalsIgnoreCase("1")) {
                    String response = imUtil.sendImMsg(wlyyPrescriptionVO.getDoctor(), wlyyPrescriptionVO.getDoctorName(), wlyyOutpatientDO.getConsumer() + "_" + wlyyPrescriptionVO.getOutpatientId() + "_9", "24", JSON.toJSONString(wlyyPrescriptionDiagnosisVOS), "1", null);
                } else if (wlyyOutpatientDO.getOutpatientType().equalsIgnoreCase("1") && wlyyOutpatientDO.getType().equalsIgnoreCase("2")) {
                    String response = imUtil.sendImMsg(wlyyPrescriptionVO.getDoctor(), wlyyPrescriptionVO.getDoctorName(), wlyyOutpatientDO.getConsumer() + "_" + wlyyPrescriptionVO.getOutpatientId() + "_16", "24", JSON.toJSONString(wlyyPrescriptionDiagnosisVOS), "1", null);
                }
            }
        }

        //获取药品
        List<WlyyPrescriptionInfoVO> infoVOs = wlyyPrescriptionVO.getInfoVOs();
        JSONObject object = new JSONObject();
        object.put("info", infoVOs);
        object.put("outpatientid", wlyyPrescriptionVO.getOutpatientId());
        object.put("prescriptionid", wlyyPrescriptionVO.getId());
        object.put("ispay", wlyyPrescriptionVO.getPayStatus());
        if (infoVOs != null && infoVOs.size() != 0) {
            WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(wlyyPrescriptionVO.getOutpatientId());
            if (wlyyOutpatientDO.getOutpatientType() != null) {
                if (wlyyOutpatientDO.getOutpatientType().equalsIgnoreCase("1") && wlyyOutpatientDO.getType().equalsIgnoreCase("1")) {
                    String response = imUtil.sendImMsg(wlyyPrescriptionVO.getDoctor(), wlyyPrescriptionVO.getDoctorName(), wlyyOutpatientDO.getConsumer() + "_" + wlyyPrescriptionVO.getOutpatientId() + "_9", "27", JSON.toJSONString(object), "1", null);
                } else if (wlyyOutpatientDO.getOutpatientType().equalsIgnoreCase("1") && wlyyOutpatientDO.getType().equalsIgnoreCase("2")) {
                    String response = imUtil.sendImMsg(wlyyPrescriptionVO.getDoctor(), wlyyPrescriptionVO.getDoctorName(), wlyyOutpatientDO.getConsumer() + "_" + wlyyPrescriptionVO.getOutpatientId() + "_16", "27", JSON.toJSONString(object), "1", null);
                }
            }
        }

//		imUtil.sendImMsg("402803816babc778016babca6d540008", "梁敬兴", "3ae2673512154d5280d1dcf5ffa5626d_808080eb6c84eacb016c8dc118e9002f_9", "24", "[{\"id\":\"808080eb6c84eacb016c8dc172810037\",\"createTime\":null,\"createUser\":null,\"createUserName\":null,\"updateTime\":null,\"updateUser\":null,\"updateUserName\":null,\"prescriptionId\":\"808080eb6c84eacb016c8dc1727f0036\",\"code\":\"D21.002  \",\"name\":\"耳软骨良性肿瘤\",\"type\":1}]","1");
//
//		imUtil.sendImMsg("402803816babc778016babca6d540008", "梁敬兴", "3ae2673512154d5280d1dcf5ffa5626d_808080eb6c84eacb016c8dc118e9002f_9", "27", "[{\"id\":\"808080eb6c84eacb016c8dc172d30038\",\"createTime\":null,\"createUser\":null,\"createUserName\":null,\"updateTime\":null,\"updateUser\":null,\"updateUserName\":null,\"prescriptionId\":\"808080eb6c84eacb016c8dc1727f0036\",\"drugNo\":\"07610 \",\"drugName\":\"吡柔比星粉针\",\"dispDeposite\":null,\"dosage\":\"1\",\"quantity\":\"1\",\"unit\":\"05\",\"unitName\":\"盒\",\"packUnit\":\"05\",\"packUnitName\":\"盒\",\"usageCode\":\"6id\",\"usageName\":\"每日6次\",\"supplyCode\":\"002\",\"supplyName\":\"静脉滴注\",\"days\":\"1\",\"frequency\":\"10\",\"serial\":\"01\",\"groupNo\":\"72\",\"specification\":\"10mg/盒\",\"packRetprice\":120.89,\"del\":1}]","1");
//
    }

    /**
     * 发送会诊建议
     *
     * @param jsonObject
     * @param doctor
     * @param doctorName
     * @param outpatientId
     * @param patient
     * @return
     * @throws Exception
     */
    public String pushHuiZhenMsg(com.alibaba.fastjson.JSONObject jsonObject, String doctor, String doctorName, String outpatientId, String patient, String outpatientType) throws Exception {
//		if("1".equals(outpatientType)){
//			return imUtil.sendImMsg(doctor, doctorName, patient+"_"+outpatientId+"_9", "31",jsonObject.toString(),"1");
//		}else
        if ("2".equals(outpatientType)) {
            return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_12", "31", jsonObject.toString(), "1", null);
        } else {
            return null;
        }
    }

    /**
     * 发送咨询建议
     *
     * @param doctor
     * @param doctorName
     * @return
     * @throws Exception
     */
    public String sendOutPatientSuggestMsg(String msg, String doctor, String doctorName, String sessionid) throws Exception {
        return imUtil.sendImMsg(doctor, doctorName, sessionid, "34", msg, "1", null);
    }


    /**
     * 发送处方驳回消息
     *
     * @param jsonObject
     * @param doctor
     * @param doctorName
     * @param outpatientId
     * @param patient
     * @return
     * @throws Exception
     */
    public String pushPrescriptionBackMsg(com.alibaba.fastjson.JSONObject jsonObject, String doctor, String doctorName, String outpatientId, String patient, String outpatientType, String type) throws Exception {
        if ("1".equals(outpatientType)) {
            if ("1".equalsIgnoreCase(type)) {
                return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_9", "33", jsonObject.toString(), "1", null);
            } else {
                return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_16", "33", jsonObject.toString(), "1", null);
            }
        } else if ("2".equals(outpatientType)) {
            return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_12", "33", jsonObject.toString(), "1", null);
        } else {
            return null;
        }
    }

    /**
     * 发送处方支付消息
     *
     * @param jsonObject
     * @param doctor
     * @param doctorName
     * @param outpatientId
     * @param patient
     * @return
     * @throws Exception
     */
    public String sendOutPatientPayMsg(com.alibaba.fastjson.JSONObject jsonObject, String doctor, String doctorName, String outpatientId, String patient, String outpatientType) throws Exception {
        if ("1".equals(outpatientType)) {
            return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_9", "35", jsonObject.toString(), "1", null);
        } else if ("2".equals(outpatientType)) {
            return imUtil.sendImMsg(doctor, doctorName, patient + "_" + outpatientId + "_12", "35", jsonObject.toString(), "1", null);
        } else {
            return null;
        }
    }

    /**
     * 查询医生所有的咨询记录
     *
     * @param doctor     医生标识
     * @param id         会话ID（等同IM表topicId）
     * @param type       咨询会话类型 ： 0 全部
     * @param status     咨询状态：0全部，1候诊中，2就诊中，3结束
     * @param pagesize   分页大小
     * @param title      标题关键字
     * @param start_time 开始时间
     * @param end_time   结束时间
     * @return
     */
    public List<Map<String, Object>> findConsultRecordByDoctor(String doctor, String id,
                                                               String type, Integer status,
                                                               int page, int pagesize,
                                                               String title, String start_time, String end_time) {
        String sql = "";
        //专家咨询
        if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {
            sql = "SELECT " +
                    "a.id AS \"id\"," +
                    "a.type AS \"type\"," +
                    "a.title AS \"title\"," +
                    "a.symptoms AS \"symptoms\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                } else {
                    sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                }
            } else {
                sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            }
            sql = sql + "b.status AS \"status\"," +
                    "b.evaluate AS \"evaluate\"," +
                    "d.name AS \"patientName\"," +
                    "d.id as \"patientId\"," +
                    "d.idcard as \"patientIdcard\"," +
                    "d.sex as \"patientSex\"," +
                    "d.photo AS \"patientPhoto\", " +
                    "b.doctor as \"doctor\" ," +
                    "a.source as \"source\"  " +
                    "FROM wlyy_consult a," +
                    "wlyy_consult_team b," +
                    "base_patient d " +
                    "WHERE a.id=b.consult " +
                    "AND b.patient=d.id ";
            if (status == -1) {
                sql += " and b.status = -1 ";
            }//候诊中
            else if (status == 1) {
                sql += " and b.status = 10 ";
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                sql += " AND b.doctor='" + doctor + "' ";
            }

            if (!StringUtils.isEmpty(title)) {
                title = "%" + title + "%";
                sql += " and a.symptoms like '" + title + "'";
            }
            if (!StringUtils.isEmpty(start_time)) {
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                    } else {
                        sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql += " and a.czrq >= '" + start_time + "'";
                }

            }

            if (!StringUtils.isEmpty(end_time)) {
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                    } else {
                        sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql += " and a.czrq <= '" + end_time + "'";
                }

            }
            //咨询状态
            if (status != 0) {

                if (status == 2) {//就诊中
                    sql += " and b.status = 0 ";
                } else if (status == 3) {
                    sql += " and b.status = 1 ";
                } else {
                }

            }

            //咨询类型
            if (!StringUtils.isEmpty(type) && !type.equalsIgnoreCase("0")) {
                sql += " AND a.type in (" + type + ")";
            }

            if (!StringUtils.isEmpty(id)) {
                sql += " and a.id = '" + id + "'";
            }
            sql += " ORDER BY a.czrq desc ";
        } else {
            if ((-1 == status || 1 == status) && (type.equalsIgnoreCase("0") || type.equalsIgnoreCase("9") || type.equalsIgnoreCase("16"))) {
                sql = "SELECT " +
                        "a.id AS \"id\"," +
                        "op.pay_status AS \"payStatus\"," +
                        "case op.type  when '1' then '9' when '2' then '16' else op.type end \"type\"," +
                        "op.description AS \"title\"," +
                        "op.description AS \"symptoms\",";
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                    } else {
                        sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                    }
                } else {
                    sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                }
                sql = sql + "op.status AS \"status\"," +
                        "b.evaluate AS \"evaluate\"," +
                        "d.name AS \"patientName\"," +
                        "d.id as \"patientId\"," +
                        "d.idcard as \"patientIdcard\"," +
                        "d.sex as \"patientSex\"," +
                        "op.consumer as \"consumer\"," +
                        "op.consumer_name as \"consumerName\"," +
                        "op.consumer_mobile as \"consumerMobile\"," +
                        "op.id as \"outpatientId\"," +
                        "op.type as \"consultType\"," +
                        "op.general_doctor as \"generalDoctor\"," +
                        "op.icd10_name as \"icd10Name\"," +
                        "d.photo AS \"patientPhoto\" , " +
                        "op.doctor as \"doctor\" ," +
                        "op.source as \"source\"  " +
                        "FROM wlyy_outpatient op LEFT JOIN wlyy_consult a  ON a.relation_code = op.id \n" +
                        " LEFT join wlyy_consult_team b on a.id = b.consult" +
                        " LEFT JOIN base_patient d on op.patient = d.id " +
                        " WHERE 1=1 ";
                if (status == 1) {
                    sql += " and op.status = 0 ";
                }
                if (status == -1) {
                    sql += " and op.status = -1 ";


                }

                if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                    sql += " AND op.doctor='" + doctor + "' ";
                }

                if (!StringUtils.isEmpty(title)) {
                    title = "%" + title + "%";
                    sql += " and op.description like '" + title + "'";
                }
                if (!StringUtils.isEmpty(start_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.create_time >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.create_time >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and op.create_time >= '" + start_time + "'";
                    }

                }

                if (!StringUtils.isEmpty(end_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.create_time <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.create_time <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and op.create_time <= '" + end_time + "'";
                    }

                }
                //咨询状态
                if (status != 0) {

                    if (status == 2) {//就诊中
                        sql += " and b.status = 0 ";
                    } else if (status == 3) {
                        sql += " and b.status = 1 ";
                    } else {
                    }

                }

                //咨询类型
                if (!StringUtils.isEmpty(type)) {
                    if (type.equalsIgnoreCase("9")) {
                        sql += " AND op.type in (1) and op.outpatient_type = 1";
                    } else if (type.equalsIgnoreCase("16")) {
                        sql += " AND op.type in (2) and op.outpatient_type = 1";
                    } else {
                        sql += " AND op.type in (1,2) and op.outpatient_type = 1";
                    }

                }


                if (!StringUtils.isEmpty(id)) {
                    sql += " and a.id = '" + id + "'";
                }
                sql += " ORDER BY op.create_time desc ";

            } else {
                sql = "SELECT " +
                        "a.id AS \"id\"," +
                        "op.pay_status AS \"payStatus\"," +
                        "a.type AS \"type\"," +
                        "a.title AS \"title\"," +
                        "a.symptoms AS \"symptoms\",";
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                    } else {
                        sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                    }
                } else {
                    sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                }
                sql = sql + "b.status AS \"status\"," +
                        "b.evaluate AS \"evaluate\"," +
                        "d.name AS \"patientName\"," +
                        "d.id as \"patientId\"," +
                        "d.idcard as \"patientIdcard\"," +
                        "d.sex as \"patientSex\"," +
                        "op.consumer as \"consumer\"," +
                        "op.consumer_name as \"consumerName\"," +
                        "op.consumer_mobile as \"consumerMobile\"," +
                        "op.id as \"outpatientId\"," +
                        "op.type as \"consultType\"," +
                        "op.general_doctor as \"generalDoctor\"," +
                        "op.icd10_name as \"icd10Name\"," +
                        "d.photo AS \"patientPhoto\" , " +
                        "b.doctor as \"doctor\" ," +
                        "a.source as \"source\"  " +
                        "FROM wlyy_consult_team b," +
                        "base_patient d," +
                        "wlyy_consult a   " +
                        "left join wlyy_outpatient op on  a.relation_code = op.id " +
						/*"FROM wlyy_outpatient op left join wlyy_consult_team b," +
						"base_patient d," +
						"wlyy_consult a   " +
						" on  a.relation_code = op.id " +*/
                        "WHERE a.id=b.consult " +
                        "AND b.patient=d.id ";
                if (status == 1) {
                    sql += " and op.status = 0 ";
                }
                if (status == -1) {
                    sql += " and b.status = -1 ";
                }

                if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                    sql += " AND b.doctor='" + doctor + "' ";
                }

                if (!StringUtils.isEmpty(title)) {
                    title = "%" + title + "%";
                    sql += " and a.symptoms like '" + title + "'";
                }
                if (!StringUtils.isEmpty(start_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and a.czrq >= '" + start_time + "'";
                    }

                }

                if (!StringUtils.isEmpty(end_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and a.czrq <= '" + end_time + "'";
                    }

                }
                //咨询状态
                if (status != 0) {

                    if (status == 2) {//就诊中
                        sql += " and b.status = 0 ";
                    } else if (status == 3) {
                        sql += " and b.status = 1 ";
                    } else {
                    }

                }

                //咨询类型
                if (!StringUtils.isEmpty(type) && !type.equalsIgnoreCase("0")) {
                    sql += " AND a.type in (" + type + ")";
                }

                if (!StringUtils.isEmpty(id)) {
                    sql += " and a.id = '" + id + "'";
                }
                sql += " ORDER BY a.czrq desc ";
            }
        }
        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql, page, pagesize);
        for (Map<String, Object> map : mapList) {
            if (map.get("patientIdcard") != null) {
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge", age);
            } else {
                map.put("patientAge", null);
            }
            if (map.get("doctor") != null) {
                String doctorId = map.get("doctor").toString();
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctorId);
                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(doctorId);
                if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                    map.put("deptName", doctorHospitalDOS.get(0).getDeptName());
                }
                if (baseDoctorDO != null) {
                    map.put("doctorName", baseDoctorDO.getName());
                }
            }
            if (map.get("id") != null) {
                if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                } else if ("0".equals(type) && null != map.get("type") && ("17".equalsIgnoreCase(map.get("type").toString()) || "1".equalsIgnoreCase(map.get("type").toString()))) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                }
            }
        }
        return mapList;
    }

    /**
     * 查询患者所有的咨询记录总数
     * * @param doctor 患者标识
     * * @param id 会话ID（等同IM表topicId）
     * * @param type 咨询会话类型
     * * @param status 咨询状态：0全部，1候诊中，2就诊中，3结束
     * * @param title 标题关键字
     * * @param start_time 开始时间
     * * @param end_time 结束时间
     *
     * @return
     */
    public Long countConsultRecordByDoctor(String doctor, String id, String type, Integer status, String title, String start_time, String end_time) {
		/*String  sql = "SELECT " +
				" COUNT(1) AS \"total\" " +
				"FROM wlyy_consult_team b," +
				"base_patient d," +
				"wlyy_consult a  " +
				"left join wlyy_outpatient op on  a.relation_code = op.id " +
				"WHERE a.id=b.consult " +
				"AND b.patient=d.id AND b.doctor='"+doctor+"'   ";
		List<ConsultVO> result = new ArrayList<>();

		if(!StringUtils.isEmpty(title)){
			title="%"+title+"%";
			sql +=" and a.symptoms like '"+title+"'";
		}

		if(!StringUtils.isEmpty(start_time)){
			if("xm_ykyy_wx".equals(wxId)){
				if (flag){
					sql +=" and a.czrq >= str_to_date('"+start_time+"','YYYY-MM-DD HH24:MI:SS')";
				}else {
					sql +=" and a.czrq >= to_date('"+start_time+"','YYYY-MM-DD HH24:MI:SS')";
				}

			}else {
				sql +=" and a.czrq >= '"+start_time+"'";
			}
			*//*sql +=" and a.czrq >= '"+start_time+"'";*//*
		}

		if(!StringUtils.isEmpty(end_time)){
			if("xm_ykyy_wx".equals(wxId)){
				if (flag){
					sql +=" and a.czrq <= str_to_date('"+end_time+"','YYYY-MM-DD HH24:MI:SS')";
				}else {
					sql +=" and a.czrq <= to_date('"+end_time+"','YYYY-MM-DD HH24:MI:SS')";
				}

			}else {
				sql +=" and a.czrq <= '"+end_time+"'";
			}
		}

		//咨询状态
		if(status != 0){

			if(status ==2 ){//就诊中
				sql +=" and b.status = 0 ";
			}else if(status ==3 ){
				sql +=" and b.status = 1 ";
			}else{}

		}


		//咨询类型
		if(!StringUtils.isEmpty(type)&&!type.equalsIgnoreCase("0")){
			sql +=" AND a.type in ("+type+")";
		}

		if (!StringUtils.isEmpty(id)) {
			sql += " and a.id = '" + id + "'";
		}

		List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(sql);
		Long count = 0L;
		if (rstotal != null && rstotal.size() > 0) {
			count = Long.parseLong(rstotal.get(0).get("total").toString());
		}*/
        String sql = "";
        //专家咨询
        if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {
            sql = "SELECT " +
                    " COUNT(1) AS \"total\" " +
                    "FROM wlyy_consult a," +
                    "wlyy_consult_team b," +
                    "base_patient d " +
                    "WHERE a.id=b.consult " +
                    "AND b.patient=d.id ";
            if (status == -1) {
                sql += " and b.status = -1 ";
            }//候诊中
            else if (status == 1) {
                sql += " and b.status = 10 ";
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                sql += " AND b.doctor='" + doctor + "' ";
            }

            if (!StringUtils.isEmpty(title)) {
                title = "%" + title + "%";
                sql += " and a.symptoms like '" + title + "'";
            }

            if (!StringUtils.isEmpty(start_time)) {
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                    } else {
                        sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql += " and a.czrq >= '" + start_time + "'";
                }

            }

            if (!StringUtils.isEmpty(end_time)) {
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                    } else {
                        sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql += " and a.czrq <= '" + end_time + "'";
                }

            }


            //咨询状态
            if (status != 0) {

                if (status == 2) {//就诊中
                    sql += " and b.status = 0 ";
                } else if (status == 3) {
                    sql += " and b.status = 1 ";
                } else {
                }

            }

            //咨询类型
            if (!StringUtils.isEmpty(type) && !type.equalsIgnoreCase("0")) {
                sql += " AND a.type in (" + type + ")";
            }

            if (!StringUtils.isEmpty(id)) {
                sql += " and a.id = '" + id + "'";
            }
            sql += " ORDER BY a.czrq desc ";
        } else {
            if ((-1 == status || 1 == status) && (type.equalsIgnoreCase("0") || type.equalsIgnoreCase("9") || type.equalsIgnoreCase("16"))) {
                sql = "SELECT " +
                        " COUNT(1) AS \"total\" " +
                        "FROM wlyy_outpatient op LEFT JOIN wlyy_consult a  ON a.relation_code = op.id \n" +
                        " LEFT join wlyy_consult_team b on a.id = b.consult" +
                        " LEFT JOIN base_patient d on op.patient = d.id " +
                        " WHERE 1=1 ";
                if (status == 1) {
                    sql += " and op.status = 0 ";
                }
                if (status == -1) {
                    sql += " and op.status = -1 ";


                }

                if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                    sql += " AND op.doctor='" + doctor + "' ";
                }

                if (!StringUtils.isEmpty(title)) {
                    title = "%" + title + "%";
                    sql += " and op.description like '" + title + "'";
                }
                if (!StringUtils.isEmpty(start_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.create_time >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.create_time >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and op.create_time >= '" + start_time + "'";
                    }

                }

                if (!StringUtils.isEmpty(end_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.create_time <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.create_time <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and op.create_time <= '" + end_time + "'";
                    }

                }
                //咨询状态
                if (status != 0) {

                    if (status == 2) {//就诊中
                        sql += " and b.status = 0 ";
                    } else if (status == 3) {
                        sql += " and b.status = 1 ";
                    } else {
                    }

                }

                //咨询类型
                if (!StringUtils.isEmpty(type)) {
                    if (type.equalsIgnoreCase("9")) {
                        sql += " AND op.type in (1) and op.outpatient_type = 1";
                    } else if (type.equalsIgnoreCase("16")) {
                        sql += " AND op.type in (2) and op.outpatient_type = 1";
                    } else {
                        sql += " AND op.type in (1,2) and op.outpatient_type = 1";
                    }

                }

                if (!StringUtils.isEmpty(id)) {
                    sql += " and a.id = '" + id + "'";
                }
                sql += " ORDER BY op.create_time desc ";
            } else {
                sql = "SELECT " +
                        " COUNT(1) AS \"total\" " +
                        "FROM wlyy_consult_team b," +
                        "base_patient d," +
                        "wlyy_consult a   " +
                        "left join wlyy_outpatient op on  a.relation_code = op.id " +
                        "WHERE a.id=b.consult " +
                        "AND b.patient=d.id ";
                if (status == -1) {
                    sql += " and b.status = -1 ";
                }//候诊中
                else if (status == 1) {
                    sql += " and op.status = 0 ";
                }
                if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
                    sql += " AND b.doctor='" + doctor + "' ";
                }

                if (!StringUtils.isEmpty(title)) {
                    title = "%" + title + "%";
                    sql += " and a.symptoms like '" + title + "'";
                }

                if (!StringUtils.isEmpty(start_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and a.czrq >= '" + start_time + "'";
                    }

                }

                if (!StringUtils.isEmpty(end_time)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " and a.czrq <= '" + end_time + "'";
                    }

                }


                //咨询状态
                if (status != 0) {

                    if (status == 2) {//就诊中
                        sql += " and b.status = 0 ";
                    } else if (status == 3) {
                        sql += " and b.status = 1 ";
                    } else {
                    }

                }

                //咨询类型
                if (!StringUtils.isEmpty(type) && !type.equalsIgnoreCase("0")) {
                    sql += " AND a.type in (" + type + ")";
                }


                if (!StringUtils.isEmpty(id)) {
                    sql += " and a.id = '" + id + "'";
                }
                sql += " ORDER BY a.czrq desc ";
            }
        }

        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql);
        Long count = 0L;
        if (mapList != null && mapList.size() > 0) {
            count = Long.parseLong(mapList.get(0).get("total").toString());
        }
        return count;
    }

    public void testSendWaiSocketMessage(String sender, String reciver) {
        imUtil.sendMessage(sender, reciver, "1", "111");
    }

    public void sendWaiSocketMessage(String sender, String reciver, String content, String contentType) {
        imUtil.sendMessage(sender, reciver, contentType, content);
    }

    /**
     * 导诊的咨询对话
     *
     * @param patientCode
     * @param session_id
     * @return
     */
    public String getPatientGuaidenceConsult(String patientCode, String session_id, String type) throws Exception {

        Boolean re = false;
        re = imUtil.sessionIsExist(session_id);
        if (re) {
            return session_id;
        } else {
            JSONObject participants = new JSONObject();
            participants.put(patientCode, 0);
            BasePatientDO basePatientDO = basePatientDao.findById(patientCode);
            String patientSex = "";
            if (basePatientDO.getSex() != null && 1 == basePatientDO.getSex()) {
                patientSex = "男";
            } else {
                patientSex = "女";
            }
            String sessionType = null;
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(type)) {
                sessionType = type;
            } else {
                sessionType = imUtil.SESSION_TYPE_GUIDANCE_HOSPITAL;
            }
            String patientAge = "";
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(basePatientDO.getIdcard())) {
                int age = DateUtil.getAgeForIdcard(basePatientDO.getIdcard());
                patientAge = "" + age;
            }

            JSONObject sessionJson = imUtil.createSession(participants, sessionType, basePatientDO.getName() + " " + patientSex + " " + patientAge, session_id);
            if (sessionJson.getInteger("status") == -1) {
                throw new RuntimeException(sessionJson.getString("message"));
            } else {
                return session_id;
            }
        }
    }

    /**
     * 更新会话成员（新增或删除）
     */
    public String updateParticipant(String sessionid, String userid, String olduserid) throws Exception {
        return imUtil.updateParticipant(sessionid, userid, olduserid);
    }

    /**
     * 会话发送消息
     *
     * @param sender_id
     * @param sender_name
     * @param session_id
     * @param content_type
     * @param content
     * @param business_type
     * @return
     */
    public String patientGuaidenceAppend(String sender_id, String sender_name, String session_id, String content_type, String content, String business_type, String extend) throws Exception {
        return imUtil.sendImMsg(sender_id, sender_name, session_id, content_type, content, "1", extend);
    }

    /**
     * 全科医生发起求助专科医生的专家咨询
     *
     * @param patient_code
     * @param general_doctor
     * @param special_doctor
     * @param when
     * @param symptoms
     * @param images
     * @return
     */
    public String generalAddExpertConsult(String patient_code, String general_doctor, String special_doctor, String when, String symptoms, String images, ConsultTeamDo ct, String source) throws Exception {
        // 设置咨询类型：15
        ct.setType(15);
        // 设置发病时间
        ct.setWhen(when);
        // 设置主要症状
        ct.setSymptoms(symptoms);
        // 设置咨询图片URL
        ct.setImages(images);
        // 设置咨询语音URL
        ct.setVoice(null);

        BaseDoctorDO generalDoctor = baseDoctorDao.findById(general_doctor);
        BaseDoctorDO specialDoctor = baseDoctorDao.findById(special_doctor);
//			doctorCode = doctor.getCode();
        // 查询患者信息
        BasePatientDO p = basePatientDao.findById(patient_code);

        String consultTitle = "居民：" + p.getName() + "(医生：)-" + specialDoctor.getName() + "发起咨询！";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", consultTitle);
        jsonObject.put("content", symptoms);
        jsonObject.put("age", DateUtil.getAgeForIdcard(p.getIdcard()));
        jsonObject.put("sex", p.getSex());

        JSONObject consultName = new JSONObject();
        consultName.put("patientName", p.getName());
        consultName.put("doctorName", specialDoctor.getName());
        jsonObject.put("name", consultName.toJSONString());

        String content = jsonObject.toString();

        //4、创建咨询
        JSONObject users = new JSONObject();//咨询参与者
        users.put(general_doctor, 0);//全科医生
        users.put(special_doctor, 0);//专科医生

        //关联业务code
//		ct.setRelationCode(outpatientCode);
        //医生信息
        ct.setDoctor(special_doctor);
        ct.setDoctorName(specialDoctor.getName());
        // 设置患者信息
        ct.setPatient(p.getId());
        ct.setSymptoms(symptoms);

        // 设置患者姓名
        ct.setName(p.getName());
        // 设置患者生日
        ct.setBirthday(p.getBirthday());
        //新增性别
        ct.setSex(p.getSex());
        // 设置患者头像
        ct.setPhoto(p.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        ct.setEvaluate(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 添加咨询记录
        ConsultDo consult = addConsult(ct.getPatient(), consultTitle, ct.getSymptoms(), ct.getImages(), ct.getType(), source);
        // 设置关联指导
//		consult.setGuidance(ct.getGuidance());
        //关联业务code
//		consult.setRelationCode(outpatientCode);
        // 设置咨询标识
        ct.setConsult(consult.getId());

        //推送给IM去创建议题，取得成员消息

        JSONObject messages = new JSONObject();
        JSONObject obj = new JSONObject();
        String sessionId = "";
        messages = imUtil.getCreateTopicMessage(generalDoctor.getId(), generalDoctor.getName(), consult.getTitle(), content, consult.getImages(), special_doctor);
        //5、（im创建咨询） 续方咨询的sessionid为居民code+就诊code+12(图文,视频,图文+视频)
        sessionId = patient_code + "_" + general_doctor + "_" + special_doctor + "_" + ct.getType();
        obj = imUtil.createTopics(sessionId, consult.getId(), p.getName(), users, messages, imUtil.SESSION_TYPE_GENERAL_EXPERT);

        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());
        ct.setActualSender(generalDoctor.getId());//实际发起人-全科医生
        ct.setActualSenderName(generalDoctor.getName());//实际发起人-全科医生
        consultTeamDao.save(ct);
        consult = consultDao.save(consult);

        //设置咨询code
//			wlyyOutpatientDO.setConsult(consult.getCode());
//			prescriptionDao.save(prescription);

        //6、记录咨询的医生详情
        ConsultTeamDoctorDo cd = new ConsultTeamDoctorDo();
        cd.setConsult(consult.getId());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(special_doctor);
        consultTeamDoctorDao.save(cd);

        //7、发送系统消息提示团队长有未审核的消息
//			addCheckMessage(prescription, sessionId, p);

        //8、 保存医生咨询信息
        // 添加咨询转发记录
        // 添加医生咨询日志
        addLogs(ct);

        JSONObject result = imUtil.getSingleSessionInfo(sessionId, special_doctor);


        //外层消息-通知
        System.out.println("发送外层SOCKET消息:全科求助专科医生");
        JSONObject object = new JSONObject();
        object.put("socket_sms_type", 5);
        imUtil.sendMessage(special_doctor, general_doctor, "1", object.toString());

        return consult.getId();
    }

    /**
     * 查询全科医生与专科医生是否存在未结束的咨询
     *
     * @param session_id
     * @return
     */
    public String isExistsUnfinishedConsult(String session_id) throws Exception {

        Boolean re = false;
        re = imUtil.sessionIsExist(session_id);
        if (re) {
            return session_id;
        } else {
            return null;
        }
    }

    /**
     * (健康咨询)医生咨询记录查询
     *
     * @param doctor     医生标识
     * @param id         会话ID（等同IM表topicId）
     * @param type       咨询会话类型 ： 0 全部
     * @param status     咨询状态：0全部，1候诊中，2就诊中，3结束
     * @param pagesize   分页大小
     * @param title      标题关键字
     * @param start_time 开始时间
     * @param end_time   结束时间
     * @return
     */
    public List<Map<String, Object>> findexpertConsultRecordByDoctor(String doctor, String id,
                                                                     Integer type, Integer status,
                                                                     int page, int pagesize,
                                                                     String title, String start_time, String end_time, String patinet) {

        String sql = "SELECT " +
                "a.id AS \"id\"," +
                "a.type AS \"type\"," +
                "a.title AS \"title\"," +
                "a.symptoms AS \"symptoms\",";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            } else {
                sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
            }
        } else {
            sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
        }
        sql = sql + "b.status AS \"status\"," +
                "b.evaluate AS \"evaluate\"," +
                "d.name AS \"patientName\"," +
                "d.id as \"patientId\"," +
                "d.idcard as \"patientIdcard\"," +
                "d.sex as \"patientsex\"," +
                "d.photo AS \"patientphoto\", " +
                "doctor.name AS \"doctorName\", " +
                "doctor.job_title_name AS \"jobTitleName\" " +
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_doctor doctor," +
                "base_patient d " +
                "WHERE a.id=b.consult " +
                "AND b.patient=d.id AND b.doctor = doctor.id AND b.patient='" + patinet + "' " +
                "AND b.actual_sender='" + doctor + "' ";
        List<ConsultVO> result = new ArrayList<>();

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and a.title like '" + title + "'";
        }

        if (!StringUtils.isEmpty(start_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.czrq >= '" + start_time + "'";
            }

        }

        if (!StringUtils.isEmpty(end_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.czrq <= '" + end_time + "'";
            }
        }


        //咨询状态
        if (status != 0) {

            if (status == 2) {//就诊中
                sql += " and b.status = 0 ";
            } else if (status == 3) {
                sql += " and b.status = 1 ";
            } else {
            }

        }

        //咨询状态
        if (type != 0) {
            sql += " AND a.type=" + type;
        }

        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql += " ORDER BY a.czrq desc ";

//		result = jdbcTemplate.query(sql, new BeanPropertyRowMapper(ConsultVO.class));

        return hibenateUtils.createSQLQuery(sql, page, pagesize);
    }


    /**
     * (健康咨询)查询患者所有的咨询记录总数
     *
     * @param doctor     患者标识
     * @param id         会话ID（等同IM表topicId）
     * @param type       咨询会话类型
     * @param status     咨询状态：0全部，1候诊中，2就诊中，3结束
     * @param title      标题关键字
     * @param start_time 开始时间
     * @param end_time   结束时间
     * @param patient    居民CODE
     * @return
     */
    public Long findexpertConsultRecordByDoctor(String doctor, String id, Integer type, Integer status, String title, String start_time, String end_time, String patient) {

        String sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                "FROM wlyy_consult a," +
                "wlyy_consult_team b," +
                "base_patient d " +
                "WHERE a.id=b.consult " +
                "AND b.patient=d.id AND b.patient='" + patient + "' " +
                "AND b.actual_sender='" + doctor + "' ";
        List<ConsultVO> result = new ArrayList<>();

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and a.title like '" + title + "'";
        }

        if (!StringUtils.isEmpty(start_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.czrq >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.czrq >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.czrq >= '" + start_time + "'";
            }
        }

        if (!StringUtils.isEmpty(end_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.czrq <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.czrq <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.czrq <= '" + end_time + "'";
            }
        }

        //咨询状态
        if (status != 0) {

            if (status == 2) {//就诊中
                sql += " and b.status = 0 ";
            } else if (status == 3) {
                sql += " and b.status = 1 ";
            } else {
            }

        }


        //咨询状态
        if (type != 0) {
            sql += " AND a.type=" + type;
        }

        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        return count;
    }

    /**
     * 根据消息ID请求转发的消息内容，组装并返回JSON
     * 返回json
     *
     * @param sessionType
     * @param content
     * @return
     */
    public JSONObject getMessageById(String sessionType, String content, String title) {
        JSONObject re = new com.alibaba.fastjson.JSONObject();
        re.put("title", title);
        content = "'" + content.replace(",", "','") + "'";
        String tableName = "";
        switch (sessionType) {
            case "1":
            case "8":
                tableName = "muc_messages";
                break;
            case "15":
                tableName = "muc_messages";
                break;
            case "2":
                tableName = "p2p_messages";
                break;
            default:
                tableName = "group_messages";
                break;
        }

        String sql = "id AS \"id\",session_id AS \"session_id\",sender_id AS \"sender_id\",sender_name AS \"sender_name\",content_type AS \"content_type\",content AS \"content\",timestamp AS \"timestamp\"  from " + data_base_name + "." +
                tableName + " where id in(" + content + ") order by timestamp desc ";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        com.alibaba.fastjson.JSONArray ja = new com.alibaba.fastjson.JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", map.get("id"));
            json.put("session_id", map.get("session_id"));
            json.put("sender_id", map.get("sender_id"));
            json.put("sender_name", map.get("sender_name"));
            json.put("content_type", map.get("content_type"));
            json.put("content", map.get("content"));
            json.put("timestamp", map.get("timestamp"));
            ja.add(json);
        }
        re.put("list", ja);
        return re;
    }

    /**
     * 健管平台模拟上传数据
     *
     * @param list outpatientlist
     * @param date 日期
     */
    public void setJobData(List<WlyyOutpatientDO> list, String date) throws Exception {
        for (WlyyOutpatientDO outpatient : list) {
            ConsultTeamDo ct = new ConsultTeamDo();

            if ("1" == outpatient.getOutpatientType()) {
                if ("1".equals(outpatient.getType())) {
                    ct.setType(9);//图文复诊
                } else if ("2".equals(outpatient.getType())) {
                    ct.setType(16);//视频复诊
                } else {
                }
            } else if ("2" == outpatient.getOutpatientType()) {
                ct.setType(12);//协同门诊
            } else {
                ct.setType(1);//协同门诊
            }

            BaseDoctorDO doctor = baseDoctorDao.findById(outpatient.getDoctor());
//			doctorCode = doctor.getCode();
            // 查询患者信息
            BasePatientDO p = basePatientDao.findById(outpatient.getPatient());

            String title = "";
            //协同门诊
            if ("2".equals(outpatient.getOutpatientType())) {
                title = "申请协同门诊";
            } else {
                title = "申请复诊";
            }

            //关联业务code
            ct.setRelationCode(outpatient.getId());
            //医生信息
            ct.setDoctor(outpatient.getDoctor());
            ct.setDoctorName(doctor.getName());
            // 设置患者信息
            ct.setPatient(outpatient.getPatient());
            ct.setSymptoms(outpatient.getDescription());

            // 设置患者姓名
            ct.setName(p.getName());
            // 设置患者生日
            ct.setBirthday(p.getBirthday());
            //新增性别
            ct.setSex(p.getSex());
            // 设置患者头像
            ct.setPhoto(p.getPhoto());
            // 设置操作日期
            ct.setCzrq(new Date());
            ct.setDel("1");
            ct.setStatus(0);
            ct.setEvaluate(0);
            // 医生未读数量为1
            ct.setDoctorRead(1);
            ct.setCzrq(outpatient.getAdmDate());

            ConsultDo consult = new ConsultDo();
            consult.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            consult.setCzrq(new Date());
            consult.setDel("1");
            consult.setPatient(p.getId());
            consult.setTitle(title);
            consult.setSymptoms(outpatient.getDescription());
//			consult.setImages(images);
            consult.setType(ct.getType());
            consult = consultDao.save(consult);
            ct.setConsult(consult.getId());
            ct.setCzrq(outpatient.getAdmDate());
            ct = consultTeamDao.save(ct);

            String scoreContent = "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"五星好评！\"}]";

            this.evaluationByConsultCode(consult.getId(), scoreContent, 2, "");
        }
    }

    /**
     * 健管平台模拟删除数据
     *
     * @param list outpatientlist
     * @param date 日期
     */
    @Transactional
    public void deleteJobData(List<WlyyOutpatientDO> list, String date) throws Exception {
        for (WlyyOutpatientDO outpatient : list) {
            String consultCode = this.getConsultCodeByOutpatientId(outpatient.getId());
            if (!StringUtils.isEmpty(consultCode)) {
                ConsultTeamDo consultTeamDo = consultTeamDao.findByConsult(consultCode);
                consultTeamDao.delete(consultTeamDo.getId());
                consultTeamDao.delete(consultCode);

                //根据咨询查找评价
                List<BaseEvaluateScoreDO> baseEvaluateScoreDOS = new ArrayList<>();
                baseEvaluateScoreDOS = baseEvaluateScoreDao.findByRelationCode(consultCode);

                for (BaseEvaluateScoreDO evaluateScoreDO : baseEvaluateScoreDOS) {
                    List<BaseEvaluateDO> baseEvaluateDOS = new ArrayList<>();
                    baseEvaluateDOS = baseEvaluateDao.findByRelationCode(evaluateScoreDO.getId());
                    for (BaseEvaluateDO baseEvaluateDO : baseEvaluateDOS) {
                        //删除评价评分表
                        baseEvaluateDao.delete(baseEvaluateDO.getId());
                    }
                    //删除评分主表
                    baseEvaluateDao.delete(evaluateScoreDO.getId());
                }
            }


        }
    }


    public Long doctorConsults(String doctorCode) {
		/*String sql=  "SELECT count(1) AS \"total\"  " +
				" FROM wlyy_consult a," +
				"wlyy_consult_team b," +
				"base_patient d  " +
				" WHERE a.id=b.consult " +
				" AND b.patient=d.id AND b.doctor='" + doctorCode + "' AND b.type in (1,15,17) and b.status = 0 and a.pay_status=1" +
				" ORDER BY a.czrq desc ";*/
        String sql = "SELECT count(1) AS \"total\"  " +
                " FROM wlyy_outpatient a " +
                " WHERE a.outpatient_type in (1,2,3)" +
                " AND a.doctor='" + doctorCode + "' AND a.type in (1,2,3) and a.status in (0,1) and a.pay_status=1" +
                " ORDER BY a.create_time desc ";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long consultCount = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            consultCount = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        return consultCount;
    }

    public Long doctorConsultsNew(String doctorCode) {
        String sql = "SELECT count(1) AS \"total\"  " +
                " FROM wlyy_outpatient a " +
                " WHERE a.outpatient_type in (1,2,3)" +
                " AND b.doctor='" + doctorCode + "' AND a.type in (1,2,3) and a.status in (0,1,2) and a.pay_status=1" +
                " ORDER BY a.create_time desc ";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long consultCount = 0l;
        if (rstotal != null && rstotal.size() > 0) {
            consultCount = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        return consultCount;
    }

    /**
     * 医生待办事项列表
     *
     * @param doctorCode
     * @param type
     * @return
     */
    public List<Map<String, Object>> doctorUpcomingList(String doctorCode, String type) {
        String sql = "";
        if ("1,15,17".equals(type)) {
			/*sql = "SELECT " +
					"a.id AS \"id\"," +
					"a.type AS \"type\"," +
					"a.title AS \"title\"," +
					"a.symptoms AS \"symptoms\",";
			if("xm_ykyy_wx".equals(wxId)){
				if (flag){
					sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
				}else{
					sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
				}
			}else{
				sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
			}
			sql = sql +"b.status AS \"status\"," +
					"b.evaluate AS \"evaluate\"," +
					"b.doctor AS \"doctorCode\"," +
					"b.actual_sender AS \"generalDoctor\"," +
					"d.name AS \"patientName\"," +
					"d.id as \"patientId\"," +
					"d.idcard as \"patientIdcard\"," +
					"d.sex as \"patientsex\"," +
					"d.photo AS \"patientphoto\" " +
					"FROM wlyy_consult a," +
					"wlyy_consult_team b," +
					"base_patient d  " +
					"WHERE a.id=b.consult " +
					"AND b.patient=d.id AND b.doctor='" + doctorCode + "' AND b.type in (" + type + ") and b.status = 0 and a.pay_status=1 " +
					"ORDER BY a.czrq desc ";*/
            sql = "SELECT " +
                    " DISTINCT op.id AS \"outpatientId\"," +
                    "op.description AS \"title\"," +
                    "op.description AS \"symptoms\"," +
                    //添加排序的列
                    "op.create_time AS \"createTime\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                } else {
                    sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                }
            } else {
                sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            }
            sql = sql + "op.status AS \"status\"," +
                    "op.evaluate_status AS \"evaluate\"," +
                    "op.doctor AS \"doctorCode\"," +
                    "case op.type when '1' then '1'  when '3' then '15' else  '17' end \"type\"," +
                    "op.general_doctor AS \"generalDoctor\"," +
                    "patient.NAME AS \"patientName\"," +
                    "patient.id AS \"patientId\"," +
                    "op.consumer AS \"consumer\"," +
                    "patient.idcard AS \"patientIdcard\"," +
                    "patient.sex AS \"patientsex\"," +
                    "patient.photo AS \"patientphoto\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
                } else {
                    sql = sql + "to_char(op.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"registerDate\",";
                }
            } else {
                sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
            }
            sql = sql + "op.status AS \"outpatientstatus\", " +
                    "p.check_status as \"checkStatus\"," +
                    "p.check_reason as \"checkReason\"" +
                    "FROM base_patient patient," +
                    "wlyy_outpatient op " +
                    " left join wlyy_prescription p on p.outpatient_id = op.id " +
                    "WHERE op.patient=patient.id " +
                    "AND op.doctor='" + doctorCode + "' " +
                    "AND op.status in ('0','1','2') and  op.pay_status=1 ";
			/*if("9".equals(type)){
				//图文复诊
				sql =sql +"AND op.type=1 AND op.outpatient_type=1 ";
			}else if("16".equals(type)){
				//视频复诊
				sql =sql +"AND op.type=2 AND op.outpatient_type=1 ";
				if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}

				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}
			}else if("12".equals(type)){
				//视频复诊
				sql =sql +"AND op.outpatient_type=2";
				if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else  {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}
				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}
			}else{}*/
			/*if("xm_ykyy_wx".equals(wxId)){
				if (flag){
					sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
				}else {
					sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
				}

			}else {
				sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
			}*/
            sql = sql + " AND op.type in ('1','2') AND op.outpatient_type = 3 ";
            sql = sql + " ORDER BY op.create_time DESC";

        }
        if ("9".equals(type) || "16".equals(type) || "12".equals(type)) {
            sql = "SELECT " +
                    " DISTINCT op.id AS \"outpatientId\"," +
                    "op.description AS \"title\"," +
                    "op.description AS \"symptoms\"," +
                    //添加排序的列
                    "op.create_time AS \"createTime\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                } else {
                    sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                }
            } else {
                sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            }
            sql = sql + "op.status AS \"status\"," +
                    "op.evaluate_status AS \"evaluate\"," +
                    "op.doctor AS \"doctorCode\"," +
                    "op.general_doctor AS \"generalDoctor\"," +
                    "op.consumer AS \"consumer\"," +
                    "patient.NAME AS \"patientName\"," +
                    "patient.id AS \"patientId\"," +
                    "patient.idcard AS \"patientIdcard\"," +
                    "patient.sex AS \"patientsex\"," +
                    "patient.photo AS \"patientphoto\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
                } else {
                    sql = sql + "to_char(op.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"registerDate\",";
                }
            } else {
                sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
            }
            sql = sql + "op.status AS \"outpatientstatus\", " +
                    "p.check_status as \"checkStatus\"," +
                    "p.check_reason as \"checkReason\"" +
                    "FROM base_patient patient," +
                    "wlyy_outpatient op " +
                    " left join wlyy_prescription p on p.outpatient_id = op.id " +
                    "WHERE op.patient=patient.id " +
                    "AND op.doctor='" + doctorCode + "' " +
                    "AND op.status in ('0','1','2') and  op.pay_status=1 ";
            if ("9".equals(type)) {
                //图文复诊
                sql = sql + "AND op.type=1 AND op.outpatient_type=1 ";
            } else if ("16".equals(type)) {
                //视频复诊
                sql = sql + "AND op.type=2 AND op.outpatient_type=1 ";
				/*if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}

				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}*/
            } else if ("12".equals(type)) {
                //视频复诊
                sql = sql + "AND op.outpatient_type=2";
				/*if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else  {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}
				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}*/
            } else {
            }

            sql = sql + " ORDER BY op.create_time DESC";
        }

        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql);
        for (Map<String, Object> map : mapList) {
            if (map.get("patientIdcard") != null) {
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge", age);
            }
        }
        return mapList;
    }

    /**
     * TnyyEntranceService
     * 修改视频会话邀请状态
     *
     * @param session_id session_id
     * @param status     1发起，0挂断
     */
    public void changeVideoInviteStatus(String session_id, Integer status) throws Exception {
        if (1 == status) {
            redisTemplate.opsForValue().set("video_invite_" + session_id, "1");
        }
        if (0 == status) {
            redisTemplate.opsForValue().set("video_invite_" + session_id, "0");
        }
    }

    /**
     * 查询会话视频邀请状态
     *
     * @param doctorids
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getDoctorConsultCount(String doctorids) throws Exception {

        String ids[] = doctorids.replace("'", "").split(",");
        String dotorIds = "";
        for (int i = 0; i < ids.length; i++) {
            dotorIds = "'" + ids[i] + "',";
        }
        dotorIds = dotorIds.substring(0, dotorIds.length() - 1);
        //医生角色
        String sql = "SELECT " +
                "count(id) AS \"total\"," +
                "doctor as \"doctor\"" +
                "FROM wlyy_consult_team " +
                "WHERE doctor IN (" + dotorIds + ") AND (type=1 OR type=15 OR type=9 OR type =16) and status = 0 GROUP BY doctor";
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }

    /**
     * 发送医生取消IM消息
     *
     * @param patientName
     * @param doctor
     * @param cancleReason
     * @param cancleContent
     * @return
     */
    public String sendOutPatientCancle(String patientName, String patientCode, String doctor, String cancleReason, String cancleContent, String outPatientId) {
        JSONObject msg = new JSONObject();
        msg.put("content", patientName + ",您好！您的复诊已被医生取消");
        msg.put("cancleReason", cancleReason);
        msg.put("cancleContent", cancleContent);
        msg.put("outPatientId", outPatientId);
        logger.info("开始发送" + msg.toJSONString());
        return imUtil.sendMessage(doctor, patientCode, "2", msg.toString());
    }


    public boolean guidanceFinishConsult(String sessionId, String participants) {
        boolean flag = false;
        //踢出会员成员
        imUtil.deleteParticipants(sessionId, participants);
        //修改session状态
        imUtil.updateSessionStatus(sessionId, "1");
        flag = true;
        return flag;
    }


    public void doctorReplyUpdateYktState(String consult, String doctor, String wxId) {
        if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
            String sql = "SELECT * FROM topics t where " +
                    "t.id='" + consult + "' and t.reply_user='" + doctor + "' and t.reply=1 and t.status IN(0,1) ";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
            logger.info("sql======" + sql);
            if (mapList != null && mapList.size() != 0 && mapList.size() == 1) {
                //眼科接诊时更新眼科通状态
                if (!flag) {
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(consult);
                    if (businessOrderDO != null) {
                        System.out.println("11111");
                        ykyyService.updateYktOrderStatus(businessOrderDO.getOrderNo(), "5");
                    }
                }
            }
        }
    }

    /**
     * 查询医生所有的咨询记录
     *
     * @param doctor     医生标识
     * @param id         会话ID（等同IM表topicId）
     * @param type       咨询会话类型 ： 0 全部
     * @param status     咨询状态：0全部，1候诊中，2就诊中，3结束
     * @param pagesize   分页大小
     * @param title      标题关键字
     * @param start_time 开始时间
     * @param end_time   结束时间
     * @return
     */
    @Transactional(readOnly = true)
    public List<Map<String, Object>> findConsultRecordByDoctorNew(String doctor, String id,
                                                                  String type, Integer status,
                                                                  int page, int pagesize,
                                                                  String title, String start_time, String end_time, String patient) {
        String sql = "";
        sql = "SELECT " +
                "a.id AS \"id\"," +
                "op.pay_status AS \"payStatus\"," +
                "op.type as \"type\"," +
                "op.outpatient_type as \"outpatientType\"," +
                "op.description AS \"title\"," +
                "op.description AS \"symptoms\",";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (flag) {
                sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                sql = sql + "date_format(op.end_time,'%Y-%m-%d %H:%i:%S' )  AS \"endTime\", ";
            } else {
                sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                sql = sql + "to_char(op.end_time,'YYYY-MM-DD hh24:mi:ss')  AS \"endTime\",";
            }
        } else {
            sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            sql = sql + "date_format(op.end_time,'%Y-%m-%d %H:%i:%S' )  AS \"endTime\",";
        }
        sql = sql + "op.status AS \"status\"," +
                "b.evaluate AS \"evaluate\"," +
                "d.name AS \"patientName\"," +
                "d.id as \"patientId\"," +
                "d.idcard as \"patientIdcard\"," +
                "d.sex as \"patientSex\"," +
                "op.consumer as \"consumer\"," +
                "op.consumer_name as \"consumerName\"," +
                "op.consumer_mobile as \"consumerMobile\"," +
                "op.id as \"outpatientId\"," +
                "op.type as \"consultType\"," +
                "op.general_doctor as \"generalDoctor\"," +
                "op.icd10_name as \"icd10Name\"," +
                "d.photo AS \"patientPhoto\" , " +
                "op.doctor as \"doctor\" ," +
                "op.source as \"source\"  ," +
                "op.card_no as \"cardNo\"  ," +
                "op.patient_cancel_value as \"patientCancelValue\" ," +
                "op.patient_cancel_remark as \"patient_cancel_remark\"  " +
                "FROM wlyy_outpatient op LEFT JOIN wlyy_consult a  ON a.relation_code = op.id \n" +
                " LEFT join wlyy_consult_team b on a.id = b.consult" +
                " LEFT JOIN base_patient d on op.patient = d.id " +
                " WHERE 1=1 ";
        if (status == 1) {
            sql += " and op.status = 0 and op.pay_status =1 ";
        } else if (status == 0) {

        } else if (status == 2) {
            sql += " and op.status = 1";
        } else {
            sql += " and op.status = " + status;
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
            sql += " AND op.doctor='" + doctor + "' ";
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(patient)) {
            sql += " AND (op.consumer='" + patient + "' or op.patient ='" + patient + "')";
        }

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and (op.patient_name like '" + title + "' OR op.doctor_name like '" + title + "' OR op.dept_name like '" + title + "' )";
        }
        if (!StringUtils.isEmpty(start_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and op.create_time >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and op.create_time >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and op.create_time >= '" + start_time + "'";
            }

        }

        if (!StringUtils.isEmpty(end_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and op.create_time <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and op.create_time <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and op.create_time <= '" + end_time + "'";
            }

        }

        //咨询类型
        if (!StringUtils.isEmpty(type)) {
            if (type.equalsIgnoreCase("9")) {
                sql += " AND op.type =1 and op.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("16")) {
                sql += " AND op.type =2 and op.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("1")) {
                sql += " AND op.type =1 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("15")) {
                sql += " AND op.type =3 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("17")) {
                sql += " AND op.type =2 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("12")) {
                sql += " AND op.outpatient_type = 2";
            } else {
                sql += " AND op.type in (1,2,3) ";
            }
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql += " ORDER BY op.create_time desc ";
        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql, page, pagesize);
        for (Map<String, Object> map : mapList) {
            if (map.get("patientIdcard") != null) {
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge", age);
            } else {
                map.put("patientAge", null);
            }
            if (map.get("doctor") != null) {
                String doctorId = map.get("doctor").toString();
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctorId);
                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(doctorId);
                if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                    map.put("deptName", doctorHospitalDOS.get(0).getDeptName());
                }
                if (baseDoctorDO != null) {
                    map.put("doctorName", baseDoctorDO.getName());
                }
            }
            if (map.get("outpatientId") != null) {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(map.get("outpatientId").toString());
                map.put("deptName", wlyyOutpatientDO.getDeptName());
            }
            if (map.get("outpatientType") != null) {
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "1".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 1);
                }
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "2".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 17);
                }
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "3".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 15);
                }
                if ("1".equalsIgnoreCase(map.get("outpatientType").toString()) && "1".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 9);
                }
                if ("1".equalsIgnoreCase(map.get("outpatientType").toString()) && "2".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 16);
                }
                if ("2".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    map.put("type", 12);
                }
            }
            if (map.get("id") != null) {
                if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                } else if ("0".equals(type) && null != map.get("outpatientType") && "3".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                }
            }
        }
        return mapList;
    }

    /**
     * 查询患者所有的咨询记录总数
     * * @param doctor 患者标识
     * * @param id 会话ID（等同IM表topicId）
     * * @param type 咨询会话类型
     * * @param status 咨询状态：0全部，1候诊中，2就诊中，3结束
     * * @param title 标题关键字
     * * @param start_time 开始时间
     * * @param end_time 结束时间
     *
     * @return
     */
    public Long countConsultRecordByDoctor2(String doctor, String id, String type, Integer status, String title, String start_time, String end_time) {
        String sql = "";
        sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                "FROM wlyy_outpatient op LEFT JOIN wlyy_consult a  ON a.relation_code = op.id \n" +
                " LEFT join wlyy_consult_team b on a.id = b.consult" +
                " LEFT JOIN base_patient d on op.patient = d.id " +
                " WHERE 1=1 ";
        if (status == 1) {
            sql += " and op.status = 0";
        } else if (status == 0) {

        } else if (status == 2) {
            sql += " and op.status = 1";
        } else {
            sql += " and op.status = " + status;
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
            sql += " AND op.doctor='" + doctor + "' ";
        }

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and (op.patient_name like '" + title + "' OR op.doctor_name like '" + title + "' OR op.dept_name like '" + title + "' )";
        }
        if (!StringUtils.isEmpty(start_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and op.create_time >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and op.create_time >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and op.create_time >= '" + start_time + "'";
            }

        }

        if (!StringUtils.isEmpty(end_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and op.create_time <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and op.create_time <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and op.create_time <= '" + end_time + "'";
            }

        }

        //咨询类型
        if (!StringUtils.isEmpty(type)) {
            if (type.equalsIgnoreCase("9")) {
                sql += " AND op.type =1 and op.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("16")) {
                sql += " AND op.type =2 and op.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("1")) {
                sql += " AND op.type =1 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("15")) {
                sql += " AND op.type =3 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("17")) {
                sql += " AND op.type =2 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("12")) {
                sql += " AND op.outpatient_type = 2";
            } else {
                sql += " AND op.type in (1,2,3) ";
            }
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql += " ORDER BY op.create_time desc ";
        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql);
        Long count = 0L;
        if (mapList != null && mapList.size() > 0) {
            count = Long.parseLong(mapList.get(0).get("total").toString());
        }
        return count;
    }


    public MixEnvelop recordByDoctor(String doctor, String id,String type, Integer status,String title, String start_time, String end_time, String patient) { //
        String sql = "";
        sql ="SELECT\n" +
                        "\ta.patient_name AS \"pname\",\n" +
                        "\ta.doctor_name AS \"dname\",\n" +
                        "\ta.dept_name AS \"dept\",\n" +
                        "\ta.outpatient_type AS \"type\",\n" +
                        "\ta.create_time AS \"ctime\",\n" +
                        "\ta.register_date AS \"rtime\",\n" +
                        "\ta.end_time AS \"etime\",\n" +
                        "\ta.description AS \"des\",\n" +
                        "\tb. STATUS AS \"pay\",\n" +
                        "\ta. STATUS AS \"STATUS\"\n" +
                        "FROM\n" +
                        "\twlyy_outpatient a\n" +
                        "LEFT JOIN wlyy_prescription b ON a.id = b.outpatient_id\n" +
                        "LEFT JOIN wlyy_consult c ON c.relation_code = a.id\n" +
                        "LEFT JOIN wlyy_consult_team d ON c.id = d.consult\n" +
                        "LEFT JOIN base_patient e ON a.patient = e.id\n" +
                        "WHERE\n" +
                        "\t1 = 1 ";


        if (status == null){

        }else if (status == 1) {
            sql += " and a.status = 0 and a.pay_status =1 ";
        } else if (status == 0) {

        } else if (status == 2) {
            sql += " and a.status = 1";
        } else {
            sql += " and a.status = " + status;
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(doctor)) {
            sql += " AND a.doctor='" + doctor + "' ";
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(patient)) {
            sql += " AND (a.consumer='" + patient + "' or a.patient ='" + patient + "')";
        }

        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and (a.patient_name like '" + title + "' OR a.doctor_name like '" + title + "' OR a.dept_name like '" + title + "' )";
        }
        if (!StringUtils.isEmpty(start_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.create_time >= str_to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.create_time >= to_date('" + start_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.create_time >= '" + start_time + "'";
            }

        }

        if (!StringUtils.isEmpty(end_time)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql += " and a.create_time <= str_to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql += " and a.create_time <= to_date('" + end_time + "','YYYY-MM-DD HH24:MI:SS')";
                }

            } else {
                sql += " and a.create_time <= '" + end_time + "'";
            }

        }

        //咨询类型
        if (!StringUtils.isEmpty(type)) {
            if (type.equalsIgnoreCase("9")) {
                sql += " AND a.type =1 and a.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("16")) {
                sql += " AND a.type =2 and a.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("1")) {
                sql += " AND a.type =1 and a.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("15")) {
                sql += " AND a.type =3 and a.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("17")) {
                sql += " AND a.type =2 and a.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("12")) {
                sql += " AND a.outpatient_type = 2";
            } else {
                sql += " AND a.type in (1,2,3) ";
            }
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        sql = sql + "\tORDER BY a.create_time desc ";


        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql);
        for (Map<String, Object> map : mapList) {
            if (map.get("patientIdcard") != null) {
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge", age);
            } else {
                map.put("patientAge", null);
            }
            if (map.get("doctor") != null) {
                String doctorId = map.get("doctor").toString();
                BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctorId);
                List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(doctorId);
                if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                    map.put("deptName", doctorHospitalDOS.get(0).getDeptName());
                }
                if (baseDoctorDO != null) {
                    map.put("doctorName", baseDoctorDO.getName());
                }
            }
            if (map.get("outpatientId") != null) {
                WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(map.get("outpatientId").toString());
                map.put("deptName", wlyyOutpatientDO.getDeptName());
            }
            if (map.get("outpatientType") != null) {
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "1".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 1);
                }
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "2".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 17);
                }
                if ("3".equalsIgnoreCase(map.get("outpatientType").toString()) && "3".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 15);
                }
                if ("1".equalsIgnoreCase(map.get("outpatientType").toString()) && "1".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 9);
                }
                if ("1".equalsIgnoreCase(map.get("outpatientType").toString()) && "2".equalsIgnoreCase(map.get("type").toString())) {
                    map.put("type", 16);
                }
                if ("2".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    map.put("type", 12);
                }
            }
            if (map.get("id") != null) {
                if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                } else if ("0".equals(type) && null != map.get("outpatientType") && "3".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    String consultCode = map.get("id").toString();
                    List<WlyyConsultAdvice> consultAdvices = wlyyConsultAdviceDao.getByConsult(consultCode);
                    StringBuffer content = new StringBuffer();
                    for (WlyyConsultAdvice consultAdvice : consultAdvices) {
                        content.append(consultAdvice.getAdviceValue() + ",");
                    }
                    if (content != null && content.length() > 0) {
                        System.out.println("content+=====" + content);
                        content.deleteCharAt(content.length() - 1);
                    }
                    map.put("icd10Name", content);
                }
            }
        }
        return MixEnvelop.getSuccessListWithPage2(BaseHospitalRequestMapping.Prescription.api_success, mapList);
    }

    public List<Map<String, Object>> doctorUpcomingList2(String doctorCode, String type) {
        String sql = "";
        if ("1,15,17".equals(type)) {
			/*sql = "SELECT " +
					"a.id AS \"id\"," +
					"a.type AS \"type\"," +
					"a.title AS \"title\"," +
					"a.symptoms AS \"symptoms\",";
			if("xm_ykyy_wx".equals(wxId)){
				if (flag){
					sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
				}else{
					sql = sql + "to_char(a.czrq,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
				}
			}else{
				sql = sql + "date_format(a.czrq,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
			}
			sql = sql +"b.status AS \"status\"," +
					"b.evaluate AS \"evaluate\"," +
					"b.doctor AS \"doctorCode\"," +
					"b.actual_sender AS \"generalDoctor\"," +
					"d.name AS \"patientName\"," +
					"d.id as \"patientId\"," +
					"d.idcard as \"patientIdcard\"," +
					"d.sex as \"patientsex\"," +
					"d.photo AS \"patientphoto\" " +
					"FROM wlyy_consult a," +
					"wlyy_consult_team b," +
					"base_patient d  " +
					"WHERE a.id=b.consult " +
					"AND b.patient=d.id AND b.doctor='" + doctorCode + "' AND b.type in (" + type + ") and b.status = 0 and a.pay_status=1 " +
					"ORDER BY a.czrq desc ";*/
            sql = "SELECT " +
                    " DISTINCT op.id AS \"outpatientId\"," +
                    "op.description AS \"title\"," +
                    "op.description AS \"symptoms\"," +
                    //添加排序的列
                    "op.create_time AS \"createTime\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                } else {
                    sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                }
            } else {
                sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            }
            sql = sql + "op.status AS \"status\"," +
                    "op.evaluate_status AS \"evaluate\"," +
                    "op.doctor AS \"doctorCode\"," +
                    "case op.type when '1' then '1'  when '3' then '15' else  '17' end \"type\"," +
                    "op.general_doctor AS \"generalDoctor\"," +
                    "patient.NAME AS \"patientName\"," +
                    "patient.id AS \"patientId\"," +
                    "op.consumer AS \"consumer\"," +
                    "patient.idcard AS \"patientIdcard\"," +
                    "patient.sex AS \"patientsex\"," +
                    "patient.photo AS \"patientphoto\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
                } else {
                    sql = sql + "to_char(op.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"registerDate\",";
                }
            } else {
                sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
            }
            sql = sql + "op.status AS \"outpatientstatus\" " +
                    "FROM base_patient patient," +
                    "wlyy_outpatient op " +
                    "WHERE op.patient=patient.id " +
                    "AND op.doctor='" + doctorCode + "' " +
                    "AND op.status in ('0','1','2') and  op.pay_status=1 ";
			/*if("9".equals(type)){
				//图文复诊
				sql =sql +"AND op.type=1 AND op.outpatient_type=1 ";
			}else if("16".equals(type)){
				//视频复诊
				sql =sql +"AND op.type=2 AND op.outpatient_type=1 ";
				if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}

				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}
			}else if("12".equals(type)){
				//视频复诊
				sql =sql +"AND op.outpatient_type=2";
				if("xm_ykyy_wx".equals(wxId)){
					if (flag){
						sql +=" and op.register_date >= str_to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}else  {
						sql +=" and op.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
					}
				}else {
					sql +=" AND  op.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
				}
			}else{}*/
            if (!"xm_ihealth_wx".equalsIgnoreCase(wxId)) {
                if ("xm_ykyy_wx".equals(wxId)) {
                    if (flag) {
                        sql += " and op.register_date >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                    } else {
                        sql += " and op.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                    }

                } else {
                    sql += " AND  op.register_date >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
                }
            }
            sql = sql + " AND op.type in ('1','2') AND op.outpatient_type = 3 ";
            sql = sql + " ORDER BY op.create_time DESC";

        }
        if ("9".equals(type) || "16".equals(type) || "12".equals(type)) {
            sql = "SELECT " +
                    " DISTINCT op.id AS \"outpatientId\"," +
                    "op.description AS \"title\"," +
                    "op.description AS \"symptoms\"," +
                    //添加排序的列
                    "op.create_time AS \"createTime\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
                } else {
                    sql = sql + "to_char(op.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"czrq\",";
                }
            } else {
                sql = sql + "date_format(op.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"czrq\",";
            }
            sql = sql + "op.status AS \"status\"," +
                    "op.evaluate_status AS \"evaluate\"," +
                    "op.doctor AS \"doctorCode\"," +
                    "op.general_doctor AS \"generalDoctor\"," +
                    "op.consumer AS \"consumer\"," +
                    "patient.NAME AS \"patientName\"," +
                    "patient.id AS \"patientId\"," +
                    "patient.idcard AS \"patientIdcard\"," +
                    "patient.sex AS \"patientsex\"," +
                    "patient.photo AS \"patientphoto\",";
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag) {
                    sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
                } else {
                    sql = sql + "to_char(op.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"registerDate\",";
                }
            } else {
                sql = sql + "date_format(op.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"registerDate\",";
            }
            sql = sql + "op.status AS \"outpatientstatus\" " +
                    "FROM base_patient patient," +
                    "wlyy_outpatient op " +
                    "WHERE op.patient=patient.id " +
                    "AND op.doctor='" + doctorCode + "' " +
                    "AND op.status in ('0','1','2') and  op.pay_status=1 ";
            if ("9".equals(type)) {
                //图文复诊
                sql = sql + "AND op.type=1 AND op.outpatient_type=1 ";
            } else if ("16".equals(type)) {
                //视频复诊
                sql = sql + "AND op.type=2 AND op.outpatient_type=1 ";
                if (!"xm_ihealth_wx".equalsIgnoreCase(wxId)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.register_date >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        }

                    } else {
                        sql += " AND  op.register_date >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
                    }
                }
            } else if ("12".equals(type)) {
                //视频复诊
                sql = sql + "AND op.outpatient_type=2";
                if (!"xm_ihealth_wx".equalsIgnoreCase(wxId)) {
                    if ("xm_ykyy_wx".equals(wxId)) {
                        if (flag) {
                            sql += " and op.register_date >= str_to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        } else {
                            sql += " and op.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                        }
                    } else {
                        sql += " AND  op.register_date >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
                    }
                }
            } else {
            }

            sql = sql + " ORDER BY op.create_time DESC";
        }

        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql);
        for (Map<String, Object> map : mapList) {
            if (map.get("patientIdcard") != null) {
                String idcard = map.get("patientIdcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                map.put("patientAge", age);
            }
        }
        return mapList;
    }

    /**
     * 查询医生所有的咨询记录
     *
     * @param doctor   医生标识
     * @param type     咨询会话类型 ： 0 全部
     * @param pagesize 分页大小
     * @return
     */
    @Transactional(readOnly = true)
    public List<Map<String, Object>> findRecordByDoctor(String doctor,
                                                        String type, String patientIdCard, String patientName,
                                                        int page, int pagesize) throws Exception {
        String sql = "select DISTINCT t.id as \"id\"," +
                "  t.name as \"name\"," +
                "  t.idcard as \"idcard\"," +
                "  t.mobile as \"mobile\"," +
                "  op.doctor as \"doctor\"" +
                " from base_patient t  left join  wlyy_outpatient op " +
                " on (t.id = op.consumer or t.id = op.patient) where t.del ='1' and op.status!= -1";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(doctor)) {
            sql += " and op.doctor = '" + doctor + "'";
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(patientIdCard)) {
            sql += " and t.idcard like '%" + patientIdCard + "%'";
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(patientName)) {
            sql += " and t.name like '%" + patientName + "%'";
        }
        //咨询类型
        if (!StringUtils.isEmpty(type)) {
            if (type.equalsIgnoreCase("1")) {
                sql += " AND  op.outpatient_type = 1";
            } else if (type.equalsIgnoreCase("2")) {
                sql += " AND op.outpatient_type = 2";
            } else if (type.equalsIgnoreCase("3")) {
                sql += " AND  op.outpatient_type = 3";
            } else {
                sql += " AND op.outpatient_type in (1,2,3) ";
            }
        }
        sql += " order by op.create_time  desc ";
        logger.info("findRecordByDoctorSQL===" + sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, pagesize);
        for (Map<String, Object> map : list) {
            if (map.get("idcard") != null) {
                String idcard = map.get("idcard").toString();
                Integer age = IdCardUtil.getAgeForIdcard(idcard);
                String sex = IdCardUtil.getSexForIdcard(idcard);
                map.put("patientAge", age);
                map.put("patientSex", sex);
            }
        }
        return list;
    }

    @Transactional(readOnly = true)
    public Map<String, Object> findRecordCountByDoctor(String doctor,
                                                       String type, String patientIdCard, String patientName) {
        String[] outpatientType = type.split(",");
        Map map = new HashMap();
        for (int i = 0; i < outpatientType.length; i++) {
            String sql = "select DISTINCT t.id as \"id\"," +
                    "  t.name as \"name\"," +
                    "  t.idcard as \"idcard\"," +
                    "  t.mobile as \"mobile\"," +
                    "  op.doctor as \"doctor\"" +
                    " from wlyy_outpatient op left join  base_patient t " +
                    " on (t.id = op.consumer or t.id = op.patient) where t.del ='1' and op.status!= -1";
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(doctor)) {
                sql += " and op.doctor = '" + doctor + "'";
            }
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(patientIdCard)) {
                sql += " and t.idcard like '%" + patientIdCard + "%'";
            }
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(patientName)) {
                sql += " and t.name like '%" + patientName + "%'";
            }
            //咨询类型
            String mapKey = "";

            if (!StringUtils.isEmpty(outpatientType[i])) {
                if (outpatientType[i].equalsIgnoreCase("1")) {
                    sql += " AND  op.outpatient_type = 1";
                    mapKey = "fzNum";
                } else if (outpatientType[i].equalsIgnoreCase("2")) {
                    sql += " AND op.outpatient_type = 2";
                    mapKey = "xtNum";
                } else if (outpatientType[i].equalsIgnoreCase("3")) {
                    sql += " AND  op.outpatient_type = 3";
                    mapKey = "zxNum";
                } else {
                    sql += " AND op.outpatient_type in (1,2,3) ";
                    mapKey = "zxNum";
                }
                logger.info("findRecordCountByDoctor===" + sql);
                List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
                map.put(mapKey, list == null ? 0 : list.size());
            }
        }


        return map;
    }

}
