package com.yihu.jw.hospital.message.service;

import com.alibaba.fastjson.JSONObject;
import com.google.j2objc.annotations.AutoreleasePool;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
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.base.words.BaseSensitiveDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.httplog.BaseOperateLogDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDO;
import com.yihu.jw.entity.hospital.message.BaseBannerDoctorDO;
import com.yihu.jw.entity.hospital.message.BaseUserMessageDO;
import com.yihu.jw.entity.hospital.message.BaseUserMsgContentDO;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateDao;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateScoreDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.httplog.dao.BaseOperateLogDao;
import com.yihu.jw.hospital.message.dao.BaseBannerDao;
import com.yihu.jw.hospital.message.dao.BaseBannerDoctorDao;
import com.yihu.jw.hospital.message.dao.BaseUserMessageDao;
import com.yihu.jw.hospital.message.dao.BaseUserMsgContentDao;
import com.yihu.jw.hospital.prescription.dao.BaseSensitiveDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.mysql.query.URLQueryParser;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.hibernate.dialect.Ingres9Dialect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.provider.HibernateUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.swing.plaf.PanelUI;
import javax.transaction.Transactional;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BaseUserMsgService extends BaseJpaService<BaseUserMessageDO, BaseUserMessageDao> {

    @Autowired
    private BaseUserMessageDao baseUserMessageDao;
    @Autowired
    private BaseUserMsgContentDao baseUserMsgContentDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseEvaluateScoreDao baseEvaluateScoreDao;
    @Autowired
    private BaseEvaluateDao baseEvaluateDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseBannerDoctorDao baseBannerDoctorDao;
    @Autowired
    private BaseBannerDao bannerDao;
    @Autowired
    private BaseSensitiveDao baseSensitiveDao;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BaseBannerDoctorService baseBannerDoctorService;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private BaseOperateLogDao baseOperateLogDao;

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


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

    public ObjEnvelop leaveMessage(String content, String reciverId, String reciverName, String senderId, Integer type, String key, String value)
            throws IOException {
        BaseUserMessageDO baseUserMessageDO = new BaseUserMessageDO();
        ObjEnvelop objEnvelop = new ObjEnvelop();
        boolean checkTimeOut = checkGiveTimeOut(senderId, reciverId);
        if ((StringUtils.isNotBlank(key)) && (StringUtils.isNotBlank(value))) {
            if (this.baseBannerDoctorService.verifyCaptcha(key, value))
            {
                checkTimeOut = true;
            }
            else
            {
                objEnvelop.setMessage("验证码错误");
                objEnvelop.setStatus(Integer.valueOf(78));
                return objEnvelop;
            }
        }
        boolean checkTimes = checkGiveTimes(senderId, reciverId);
        if (checkTimes)
        {
            if (checkTimeOut)
            {
                BasePatientDO patientDO = this.basePatientDao.findById(senderId);
                String senderName = null;
                if (null != patientDO) {
                    senderName = patientDO.getName();
                }
                String relationCode = UUID.randomUUID().toString();
                baseUserMessageDO.setContent(content);
                baseUserMessageDO.setSender(senderId);
                baseUserMessageDO.setSenderName(senderName);
                baseUserMessageDO.setReceiver(reciverId);
                baseUserMessageDO.setReceiverName(reciverName);
                baseUserMessageDO.setRelationCode(relationCode);
                baseUserMessageDO.setRelationName("留言");
                baseUserMessageDO.setRelationType(Integer.valueOf(1));
                baseUserMessageDO.setStatus(Integer.valueOf(1));
                baseUserMessageDO.setDel(Integer.valueOf(1));
                baseUserMessageDO.setType(type);
                baseUserMessageDO.setIsRead(Integer.valueOf(0));
                this.baseUserMessageDao.save(baseUserMessageDO);
                objEnvelop.setStatus(Integer.valueOf(200));
                objEnvelop.setMessage("留言成功");
            }
            else
            {
                objEnvelop.setMessage("生成验证码");
                objEnvelop.setStatus(200);
                objEnvelop.setObj(baseBannerDoctorService.generateCaptcha());
                return objEnvelop;
            }
        }
        else
        {
            objEnvelop.setMessage("当天留言已达规定次数");
            objEnvelop.setStatus(Integer.valueOf(77));
            return objEnvelop;
        }
        return objEnvelop;
    }
    //回复留言接口
    @Transactional
    public void responseMessage(String contentId,String content, String reciverId, String senderId,Integer isDoctor) {
        BaseUserMessageDO baseUserMessageDOS = baseUserMessageDao.findOne(contentId);
        if(null!=baseUserMessageDOS&&1==isDoctor){
            baseUserMessageDOS.setStatus(2);
            baseUserMessageDOS.setIsRead(1);
        }
        baseUserMessageDao.save(baseUserMessageDOS);
        BaseUserMsgContentDO baseUserMsgContentDO =new BaseUserMsgContentDO();
        String senderName = null;
        if(1==isDoctor){
            BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(senderId);
            BasePatientDO reciver= basePatientDao.findById(reciverId);
            if (null!=reciver){
                baseUserMsgContentDO.setReceiverName(reciver.getName());
            }
            if(null!=baseDoctorDO){
                senderName = baseDoctorDO.getName();
            }
            baseUserMsgContentDO.setIsDoctor(1);
        }else {
            BasePatientDO patientDO= basePatientDao.findById(senderId);
            BaseDoctorDO reciver = baseDoctorDao.findById(reciverId);
            if(null!=reciver){
                baseUserMsgContentDO.setReceiverName(reciver.getName());
            }
            if(null!=patientDO){
                senderName = patientDO.getName();
            }
            baseUserMsgContentDO.setIsDoctor(0);
        }
        baseUserMsgContentDO.setBaseUserMsgId(contentId);
        baseUserMsgContentDO.setContent(content);
        baseUserMsgContentDO.setSender(senderId);
        baseUserMsgContentDO.setSenderName(senderName);
        baseUserMsgContentDO.setReceiver(reciverId);
        baseUserMsgContentDO.setDel(1);
        baseUserMsgContentDO.setStatus(1);
        baseUserMsgContentDao.save(baseUserMsgContentDO);
    }

    //评论留言展示
    public Envelop getMessage(String doctor, String showAll, String showAllType, String beginTime, String endTime,String patient, Integer page, Integer pageSize) {
        StringBuffer sql = new StringBuffer();
        Map<String,Object> params = new HashedMap();
        sql.append("select t.id as \"id\" ,t.content as \"content\",t.type as \"type\"," +
                "t.sender as \"sender\",t.sender_name as \"sender_name\",t.receiver as \"receiver\"," +
                "t.receiver_name as \"receiver_name\",t.relation_type as \"relation_type\"," +
                "t.relation_code as \"relation_code\",t.relation_name as \"relation_name\",t.status as \"status\",t.update_time as \"update_time\"");
        /*if("xm_ykyy_wx".equals(wxId)){
            flag = true;
            if (flag){
               sql.append(",date_format(t.update_time,'%Y-%m-%d %H:%i:%S' )  AS \"update_time\"");
            }else {
                sql.append(",to_char(t.update_time,'YYYY-MM-DD hh24:mi:ss')  AS \"update_time\"");
            }
        }else{
            sql.append("date_format(t.update_time,'%Y-%m-%d %H:%i:%S' )  AS \"update_time\"");
        }*/

        sql.append(" from base_user_message t where 1 = 1 and t.del = 1");
        if (StringUtils.isNotEmpty(doctor)) {
            sql.append(" and t.receiver = '" + doctor + "'");
        }
        if (StringUtils.isNotEmpty(patient)) {
            sql.append(" and t.sender = '" + patient + "'");
        }
        if (StringUtils.isNotEmpty(showAll)) {
            sql.append(" and t.status = " + showAll);
        }
        if (StringUtils.isNotEmpty(showAllType)) {
            sql.append(" and t.relation_type = " + showAllType);
        }
        if (StringUtils.isNotEmpty(beginTime)) {
            //sql.append(" and t.update_time > '" + beginTime+"'");//DateUtil.stringToDate(beginTime,"yyyy-MM-dd HH:mm:ss")
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql.append( " and t.update_time >= str_to_date('" + beginTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }else {
                    sql.append(  " and t.update_time >= to_date('" + beginTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }
            } else {
                sql.append( " AND t.update_time >='" + beginTime + " 00:00:00'");
            }
        }

        if (StringUtils.isNotEmpty(endTime)) {
            //sql.append(" and t.update_time < '" + endTime+"'");//DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss")
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql.append( " and t.update_time <= str_to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')");
                }else {
                    sql.append(  " and t.update_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')");
                }
            } else {
                sql.append( " AND t.update_time <='" + endTime + " 23:59:59'");
            }
        }
        sql.append(" ORDER BY t.update_time Desc");
        String sqlcount = "SELECT COUNT(1) AS \"total\" FROM ("+sql.toString()+") q";
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlcount,params);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        System.out.println(sql.toString());
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql.toString(),params,page,pageSize);
        List<Map<String, Object>> returnList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String,Object> returnMap = new HashMap<>();
            String relationCode = null==map.get("relation_code")?"":map.get("relation_code").toString();
            String id =  null==map.get("id")?"":map.get("id").toString();
            String patientID = null==map.get("sender")?"":map.get("sender").toString();
            BaseUserMessageDO baseUserMsgDO =new BaseUserMessageDO();
            baseUserMsgDO.setId(id);
            if (map.get("type")!=null){
                baseUserMsgDO.setType(Integer.valueOf(map.get("type").toString()));
            }
            String reciveDoctor=null==map.get("receiver")?"":map.get("receiver").toString();
            List<BaseDoctorHospitalDO> baseDoctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(reciveDoctor);
            if (baseDoctorHospitalDOS!=null&&baseDoctorHospitalDOS.size()>0){
                returnMap.put("deptName",baseDoctorHospitalDOS.get(0).getDeptName());
            }
            BaseDoctorDO baseDoctorDO=baseDoctorDao.findById(reciveDoctor);
            if (baseDoctorDO!=null){
                returnMap.put("doctorName",baseDoctorDO.getName());
                returnMap.put("doctorPhoto",baseDoctorDO.getPhoto());
                returnMap.put("jobtitleName",baseDoctorDO.getJobTitleName());
            }

            baseUserMsgDO.setReceiver(null==map.get("receiver")?"":map.get("receiver").toString());
            baseUserMsgDO.setReceiverName(null==map.get("receiver_name")?"":map.get("receiver_name").toString());
            baseUserMsgDO.setSender(null==map.get("sender")?"":map.get("sender").toString());
            List<BaseSensitiveDO> baseSensitiveDOS = baseSensitiveDao.getSensitiveWords();
            String content = map.get("content")==null?"":map.get("content").toString();
            for (BaseSensitiveDO sensitiveDO:baseSensitiveDOS){
                if (StringUtils.isNotBlank(content)){
                    if (content.contains(sensitiveDO.getSensitiveWord())){
                        content = content.replace(sensitiveDO.getSensitiveWord(),"****");
                    }
                }

            }

            baseUserMsgDO.setContent(content);
            baseUserMsgDO.setRelationCode(null==map.get("relation_code")?"":map.get("relation_code").toString());
            baseUserMsgDO.setRelationType(null==map.get("relation_type")?0:Integer.valueOf(map.get("relation_type").toString()));
            baseUserMsgDO.setRelationName(null==map.get("relation_name")?"":map.get("relation_name").toString());
            baseUserMsgDO.setStatus(null==map.get("status")?0:Integer.valueOf(map.get("status").toString()));
            BasePatientDO patientDO = basePatientDao.findById(null==map.get("sender")?"":map.get("sender").toString());
            List<BaseBannerDoctorDO> ba =  baseBannerDoctorDao.getBanners(baseUserMsgDO.getReceiver(),baseUserMsgDO.getSender(),baseUserMsgDO.getRelationCode());
            if(ba.size()>0){
                List<BaseBannerDO> bannerLits= new ArrayList<>();
                for (BaseBannerDoctorDO bannerDoctorDO:ba){
                    BaseBannerDO bannerDO = bannerDao.findOne(bannerDoctorDO.getBannerId());
                    bannerLits.add(bannerDO);
                    baseUserMsgDO.setBaseBannerDOS(bannerLits);
                }
            }


                //baseUserMsgDO.setBannerList(ba);

            String icon = null;
            if (null!=patientDO){
                icon = patientDO.getPhoto();
            }
            List<BaseUserMsgContentDO> contentlist=baseUserMsgContentDao.getContentListByID(id);
            if(contentlist.size()>0){
                for (BaseUserMsgContentDO dealList :contentlist){
                    if (null!=baseUserMsgDO.getType()&&baseUserMsgDO.getType()==2){
                        dealList.setSenderName(patientID==dealList.getSender()?dealList.getSenderName().substring(0,1)+"**":dealList.getSenderName());
                        dealList.setReceiverName(patientID==dealList.getReceiver()?dealList.getReceiverName().substring(0,1)+"**":dealList.getReceiverName());
                    }
                    String respongseContent = dealList.getContent();
                    for (BaseSensitiveDO sensitiveDO:baseSensitiveDOS){
                        if (StringUtils.isNotBlank(content)){
                            if (respongseContent.contains(sensitiveDO.getSensitiveWord())){
                                respongseContent = respongseContent.replace(sensitiveDO.getSensitiveWord(),"****");
                                dealList.setContent(respongseContent);
                            }
                        }

                    }

                }
            }
            baseUserMsgDO.setMsgList(contentlist);
            String updateTime = map.get("update_time").toString();
            baseUserMsgDO.setUpdateTime(DateUtil.strToDateLong(updateTime));

            //map.put("update_time",DateUtil.dateToStrLong(DateUtil.strToDateLong(updateTime)));
            List<BaseEvaluateDO> baseEvaluateDO=baseEvaluateDao.findByRelationCode(relationCode);
            BaseEvaluateScoreDO scoreList =null;
            if (baseEvaluateDO.size()>0){
                String findRC=baseEvaluateDO.get(0).getRelationCode();
                scoreList= baseEvaluateScoreDao.findOne(relationCode);
                if(null!=scoreList){
                    returnMap.put("everangScore",scoreList);
                    returnMap.put("scoreList",baseEvaluateDO);
                }
            }
            if(scoreList!=null){
                baseUserMsgDO.setSenderName(scoreList.getType()==1?map.get("sender_name").toString():map.get("sender_name").toString().substring(0,1)+"**");

            }else {
                baseUserMsgDO.setSenderName(null==map.get("sender_name")?"":map.get("sender_name").toString());
            }if(null!=baseUserMsgDO.getType()&&baseUserMsgDO.getType()==2){
                baseUserMsgDO.setSenderName(null==map.get("sender_name")?"":map.get("sender_name").toString().substring(0,1)+"**");
            }
            returnMap.put("contentList",baseUserMsgDO);
            returnMap.put("patientIcon",icon);
            returnList.add(returnMap);
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, returnList, page, pageSize, count);
    }

    //获取单条评论详细信息
    public List<Map<String,Object>> getSingle(String id){
        BaseUserMessageDO baseUserMessageDO=baseUserMessageDao.findOne(id);
        String patientId= baseUserMessageDO.getSender();
        Integer type = baseUserMessageDO.getType();
        List<BaseUserMsgContentDO> contentlist=baseUserMsgContentDao.getContentListByID(id);
        if (null!=type&&type==2){
            for (BaseUserMsgContentDO baseUserMsgContentDO:contentlist){
                baseUserMsgContentDO.setSenderName(baseUserMsgContentDO.getSender()==patientId?baseUserMsgContentDO.getSenderName().substring(0,1)+"**":baseUserMsgContentDO.getSenderName());
                baseUserMsgContentDO.setReceiverName(baseUserMsgContentDO.getReceiver()==patientId?baseUserMsgContentDO.getReceiverName().substring(0,1)+"**":baseUserMsgContentDO.getReceiverName());
            }
        }
        String relationCode= baseUserMessageDO.getRelationCode();
        List<Map<String,Object>> returnResult = new ArrayList<>();
        //List<Map<String,Object>> scoreList = this.getListByRelationCode(relationCode);
        Map<String,Object> map = new HashMap<>();
        BaseEvaluateScoreDO scoreList = new BaseEvaluateScoreDO();
        List<BaseEvaluateDO> baseEvaluateDO=baseEvaluateDao.findByRelationCode(relationCode);
        if (baseEvaluateDO.size()>0){
            String findRC=baseEvaluateDO.get(0).getRelationCode();
            scoreList= baseEvaluateScoreDao.findOne(relationCode);
            if(null!=scoreList){
                map.put("everangScore",scoreList);
                map.put("scoreList",baseEvaluateDO);
            }
        }
        map.put("scoreList",scoreList);
        map.put("sender",baseUserMessageDO.getSender());
        if (null!=type&&type==2){
            map.put("senderName",baseUserMessageDO.getSenderName().substring(0,1)+"**");
        }else {
            map.put("senderName",baseUserMessageDO.getSenderName());
        }
        map.put("content",baseUserMessageDO.getContent());
        map.put("receiver",baseUserMessageDO.getReceiver());
        map.put("receiverName",baseUserMessageDO.getReceiverName());
        map.put("relationCode",baseUserMessageDO.getRelationCode());
        map.put("relationType",baseUserMessageDO.getRelationType());
        map.put("status",baseUserMessageDO.getStatus());
        map.put("updateTime",DateUtil.dateToStrLong(baseUserMessageDO.getUpdateTime()));
        map.put("relationName",baseUserMessageDO.getRelationName());
        map.put("contentlist",contentlist);
        returnResult.add(map);
        return returnResult;
    }
    //专家咨询留言
    public void expertMessage(String content, String reciverId, String reciverName, String senderId, String senderName, String relationCode) {

        BaseUserMessageDO baseUserMessageDO = new BaseUserMessageDO();
        baseUserMessageDO.setContent(content);
        baseUserMessageDO.setSender(senderId);
        baseUserMessageDO.setSenderName(senderName);
        baseUserMessageDO.setReceiver(reciverId);
        baseUserMessageDO.setReceiverName(reciverName);
        baseUserMessageDO.setRelationCode(relationCode);
        baseUserMessageDO.setRelationName("专家咨询");
        baseUserMessageDO.setRelationType(3);
        baseUserMessageDO.setStatus(1);
        baseUserMessageDO.setDel(1);
        baseUserMessageDao.save(baseUserMessageDO);


    }
    //在线复诊留言
    public void onlineVisitMessage(String content, String reciverId, String reciverName, String senderId, String senderName, String relationCode) {
        BaseUserMessageDO baseUserMessageDO = new BaseUserMessageDO();
        baseUserMessageDO.setContent(content);
        baseUserMessageDO.setSender(senderId);
        baseUserMessageDO.setSenderName(senderName);
        baseUserMessageDO.setReceiver(reciverId);
        baseUserMessageDO.setReceiverName(reciverName);
        baseUserMessageDO.setRelationCode(relationCode);
        baseUserMessageDO.setRelationName("在线复诊");
        baseUserMessageDO.setRelationType(4);
        baseUserMessageDO.setStatus(1);
        baseUserMessageDO.setDel(1);
        baseUserMessageDao.save(baseUserMessageDO);


    }
    //评论回复展示
    public Envelop showReply(String relationCode, Integer page, Integer pageSize){
        String sql = dealSql(relationCode,false);
        String sqlCount = dealSql(relationCode,true);
        Map<String,Object> params = new HashedMap();
        if (StringUtils.isNotEmpty(relationCode)){
            params.put("relationCode",relationCode);
        }
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlCount,params);
        if(total!=null){
            //mysql 与 Oracle 聚合函数返回类型不一致，需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,pageSize);
        for (Map<String,Object> map:list){
            String createTime= map.get("updateTime").toString();
            String updateTime = map.get("updateTime1").toString();
            map.put("updateTime",DateUtil.dateToStrLong(DateUtil.strToDateLong(createTime)));
            map.put("updateTime1",DateUtil.dateToStrLong(DateUtil.strToDateLong(updateTime)));
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, pageSize, count);
    }
    private String dealSql(String relationCode,Boolean isCount){
        StringBuffer sql = new StringBuffer();
        if (isCount) {
            sql.append("SELECT COUNT(1) AS \"total\" FROM (");
        }
        sql.append("select " +"b.id AS \"id\",b.content AS \"topContent\",b.sender_name AS \"topSenderName\" " +
                ",a.content AS \"content\",b.update_time  AS \"updateTime\", a.sender_name AS \"senderName\",a.receiver_name AS \"receiverName\",a.update_time  AS \"updateTime1\""+
                "from base_user_msg_content a left join base_user_message b" +
                "on on b.id = a.base_user_msg_id");
        sql.append(" where 1=1 ");
        if (StringUtils.isNotEmpty(relationCode)){
            sql.append(" and a.relation_code = :relationCode");
        }
        if (isCount) {
            sql.append(") t");
        }
        return sql.toString();
    }

    public boolean checkGiveTimeOut(String sender, String reciver) {
        List<BaseUserMessageDO> baseBannerDoctorDOS = this.baseUserMessageDao.getMessageByPatientAndDoctor(reciver, sender);
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = this.wlyyHospitalSysDictDao.findById("leave_message_timeout");
        if (null != baseBannerDoctorDOS&&baseBannerDoctorDOS.size()>=1)
        {
            BaseUserMessageDO lastOne = (BaseUserMessageDO)baseBannerDoctorDOS.get(0);
            Date lastDate = lastOne.getCreateTime();
            long timeOut = wlyyHospitalSysDictDO.getDictValue() != null ? Long.valueOf(wlyyHospitalSysDictDO.getDictValue()).longValue() : 5L;
            Date current = new Date();
            if (current.getTime() - lastDate.getTime() > timeOut * 1000L * 60L) {
                return true;
            }
            return false;
        }
        return true;
    }

    public boolean checkGiveTimes(String patientId, String doctorId)
    {
        boolean flag = false;
        StringBuffer sql = new StringBuffer();
        sql.append("select t.sender as \"sender\",t.receiver as \"receiver\" from base_user_message t");
        sql.append(" where 1=1 ");
        if (StringUtils.isNotBlank(patientId)) {
            sql.append(" and t.sender = '" + patientId + "'");
        }
        if (StringUtils.isNotBlank(doctorId)) {
            sql.append(" and t.receiver = '" + doctorId + "'");
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = format.format(date);
        System.out.println(wxId+flag);
        if("xm_ykyy_wx".equals(wxId)){
            if (flag){
                sql.append(" and t.create_time > '" + strDate + " 00:00:00' and t.create_time<'" + strDate + " 23:59:59'");
            }else {
                sql.append(" and t.create_time > to_date('" + strDate + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and t.create_time< to_date('" + strDate + " 23:59:59','yyyy-mm-dd hh24:mi:ss')");
            }
        }else{
            sql.append(" and t.create_time > '" + strDate + " 00:00:00' and t.create_time<'" + strDate + " 23:59:59'");
        }
        List<Map<String, Object>> list = this.hibenateUtils.createSQLQuery(sql.toString());
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = this.wlyyHospitalSysDictDao.findById("leave_message_times");
        long countTimes = 5L;
        if (wlyyHospitalSysDictDO != null) {
            countTimes = wlyyHospitalSysDictDO.getDictValue() == null ? countTimes : Long.valueOf(wlyyHospitalSysDictDO.getDictValue()).longValue();
        }
        if (list.size() > countTimes) {
            return false;
        }
        return true;
    }
    public void deleteMessageOrMessageContent(String msgId,String isDelParent){
        if ("1".equalsIgnoreCase(isDelParent)){
            BaseUserMessageDO baseUserMessageDO = baseUserMessageDao.findOne(msgId);
            if (baseUserMessageDO!=null){
                BaseOperateLogDO baseOperateLogDO = new BaseOperateLogDO();
                JSONObject jsonObject = new JSONObject();
                baseUserMessageDO.setDel(0);
                baseUserMessageDao.save(baseUserMessageDO);
                baseOperateLogDO.setOperator(baseUserMessageDO.getSender());
                baseOperateLogDO.setIsDel("0");
                List<BaseBannerDoctorDO> ba =  baseBannerDoctorDao.getBanners(baseUserMessageDO.getReceiver(),baseUserMessageDO.getSender(),baseUserMessageDO.getRelationCode());
                if(ba!=null&&ba.size()>0){
                    jsonObject.put("banners",ba);
                    baseBannerDoctorDao.delete(ba);
                }

                List<BaseEvaluateScoreDO> scoreList= baseEvaluateScoreDao.findByRelationCode(baseUserMessageDO.getRelationCode());
                if (scoreList!=null&&scoreList.size()>0){
                    for (BaseEvaluateScoreDO baseEvaluateScoreDO:scoreList){
                        List<BaseEvaluateDO> baseEvaluateDO=baseEvaluateDao.findByRelationCode(baseEvaluateScoreDO.getId());
                        jsonObject.put(baseEvaluateScoreDO.getId(),baseEvaluateDO);
                        if (baseEvaluateDO!=null&&baseEvaluateDO.size()>0){
                            baseEvaluateDao.delete(baseEvaluateDO);
                        }
                    }
                    jsonObject.put("scoreList",scoreList);
                    baseEvaluateScoreDao.delete(scoreList);

                }
                baseOperateLogDO.setRelationCode(baseUserMessageDO.getId());
                baseOperateLogDO.setName("删除留言评价");
                baseOperateLogDO.setRelationType(jsonObject.toString());
                try {
                    baseOperateLogDao.save(baseOperateLogDO);
                }catch (Exception e){
                    e.printStackTrace();
                }
                List<BaseUserMsgContentDO> contentlist=baseUserMsgContentDao.getContentListByID(msgId);
                for (BaseUserMsgContentDO baseUserMsgContentDO:contentlist){
                    baseUserMsgContentDO.setDel(0);
                    baseUserMsgContentDao.save(baseUserMsgContentDO);
                }

            }
        }
    }
}