/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.service.app.consult;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamDoctor;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.discussion.WlyyTalkGroup;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientFamilyMember;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.repository.consult.ConsultTeamLogDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.patient.PatientFamilyMemberDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import org.springside.modules.utils.Clock;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 網絡諮詢类.
 * test
 *
 * @author George
 */
// Spring Service Bean的标识.
@Component
@Transactional(rollbackFor = Exception.class)
public class ConsultTeamService extends ConsultService {

    private Clock clock = Clock.DEFAULT;

    // 咨询详细记录
    @Autowired
    private ConsultTeamLogDao consultTeamLogDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorPatientDao doctorPatientDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private DoctorTeamMemberDao doctorTeamDoctor;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientHealthGuidanceService guidanceService;
    @Autowired
    private PatientFamilyMemberDao familyMemberDao;
    @Autowired
    private HealthEduArticleService healthEduArticleService;
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private TalkGroupService talkGroupService;
    @Autowired
    private com.yihu.wlyy.service.common.account.DoctorService doctorService;

    @Autowired
    WeiXinAccessTokenUtils accessTokenUtils;

    Map<Integer, String> relations = new HashMap<>();

    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
    }

    /**
     * 查询患者是否还有未结束的三师咨询
     *
     * @param patient
     * @return
     */
    public boolean exist(String patient, Integer type) throws Exception {
        DoctorTeamMember member = null;
        // 咨询三师
        if (type == 1) {
            // 查询三师签约信息
            SignFamily sc = signFamilyDao.findBySanshiPatientYes(patient);
            if (sc == null) {
                throw new Exception("不存在三师签约");
            }
            // 设置健康管理师，三师咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findBySanshiParientCode(patient);
            //得到团队的健康管理师
            member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 3);

            if (member == null) {
                member = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 2);
            }
        } else if (type == 2) {
            // 咨询家庭医生
            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
            if (sf == null) {
                throw new Exception("不存在家庭签约");
            }
            // 设置健康管理师，家庭医生咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(patient);
            //得到团队的健康管理师
            member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 3);

            if (member == null) {
                member = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 2);
            }
        }
        if (member == null) {
            throw new Exception("找不到签约服务团队医生");
        }
        int count = consultTeamDao.countByPatient(patient, member.getMemberCode());
        return count > 0;
    }

    /**
     * 查詢醫生網絡諮詢列表
     *
     * @param type     咨询类型：1、咨询我的，2、公共的， 3、参与过的，4、已结束的 5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
     * @param id
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    public Page<ConsultTeam> findByDoctor(String uid, int type, long id, int pagesize, String patient, String title) {
        if (id < 0) {
            id = 0;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        switch (type) {
            case 0:
                // 全部
                return findByDoctorType0(uid, id, patient, pagesize);
            case 1:
                // 咨询我的
                return findByDoctorType1(uid, type, id, pagesize);
            case 2:
                // 我感兴趣的
                return findByDoctorType2(uid, type, id, pagesize);
            case 3:
                // 我回复的
                return findByDoctorType3(uid, id, pagesize);
            case 4:
                // 已完成的
                return findByDoctorType4(uid, id, pagesize);
            case 5:
                // 5 名医咨询 全部
                return findByDoctorType5(uid, id, pagesize, title);
            case 6:
                //6 名医咨询 进行中
                return findByDoctorType6(uid, 0, id, pagesize, title);
            case 7:
                //7 名医咨询 已结束
                return findByDoctorType6(uid, 1, id, pagesize, title);
            case 8:
                return findByDoctorType8(uid, id, pagesize, title);
            case 9:
                return findByDoctorType9(uid, id, pagesize);
            case 10:
                //我咨询的
                return findByDoctorType10(uid, id, pagesize, title);
            case 11:
                //我咨询的 进行中
                return findByDoctorType11(uid, 0, id, pagesize, title);
            case 12:
                //我咨询的 已结束中
                return findByDoctorType11(uid, 1, id, pagesize, title);
        }
        return null;
    }

    private Page<ConsultTeam> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
            }
        }
    }

    private Page<ConsultTeam> findByDoctorType10(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorAllList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorAllList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findMyFamousDoctorAllList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findMyFamousDoctorAllList(uid, pageRequest);
            }
        }
    }

    private Page<ConsultTeam> findByDoctorTypeSix(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorIngList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorIngList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorIngNoTitleList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorIngNoTitleList(uid, pageRequest);
            }
        }
    }

    private Page<ConsultTeam> findByDoctorType8(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        sort.and(new Sort(Direction.DESC, "czrq"));
        sort.and(new Sort(Direction.DESC, "doctorRead"));
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, pageRequest);
            }
        }
    }

    private Page<ConsultTeam> findByDoctorType5(String uid, long id, int pagesize, String title) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorAllList(uid, id, title, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorAllList(uid, title, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorAllList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorAllList(uid, pageRequest);
            }
        }
    }

    private Page<ConsultTeam> findByDoctorType6(String uid, int type, long id, int pagesize, String title) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isNoneEmpty(title)) {
            title = "%" + title + "%";
            if (id > 0) {
                return consultTeamDao.findFamousDoctorDoingList(uid, id, title, type, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorDoingList(uid, title, type, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findFamousDoctorDoingList(uid, id, type, pageRequest);
            } else {
                return consultTeamDao.findFamousDoctorDoingList(uid, type, pageRequest);
            }
        }
    }

    /**
     * 根据状态获取三师家庭咨询
     *
     * @param doctor
     * @param status   0未处理或未回复 1已回复 2已结束
     * @param id
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findConsultByDoctor(String doctor, int status, long id, int pagesize) {
        if (id < 0) {
            id = 0;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }

        if (status == 0) {
            return findConsultByDoctorWcl(doctor, id, pagesize);
        } else if (status == 1) {
            return findConsultByDoctorIng(doctor, id, pagesize);
        } else {
            return findByDoctorType4(doctor, id, pagesize);
        }
    }

    /**
     * 获取三师家庭未处理咨询
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    private Page<ConsultTeam> findConsultByDoctorWcl(String uid, long id, int pagesize) {
        Sort sort = new Sort(Direction.DESC, "id");
        sort.and(new Sort(Direction.DESC, "czrq"));
        sort.and(new Sort(Direction.DESC, "doctorRead"));
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);

        if (id > 0) {
            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, pageRequest);
        }
    }

    /**
     * 获取三师家庭已回复咨询
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    private Page<ConsultTeam> findConsultByDoctorIng(String uid, long id, int pagesize) {
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);

        if (id > 0) {
            return consultTeamDao.findDoctorIngNoTitleList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorIngNoTitleList(uid, pageRequest);
        }
    }

    /**
     * 查询全部咨询记录
     *
     * @param uid
     * @param id
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType0(String uid, long id, String patient, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (StringUtils.isEmpty(patient)) {
            if (id > 0) {
                return consultTeamDao.findDoctorList(uid, id, pageRequest);
            } else {
                return consultTeamDao.findDoctorList(uid, pageRequest);
            }
        } else {
            if (id > 0) {
                return consultTeamDao.findDoctorPatientList(uid, patient, id, pageRequest);
            } else {
                return consultTeamDao.findDoctorPatientList(uid, patient, pageRequest);
            }
        }
    }

    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid      医生标识
     * @param type     咨询类型：1、咨询我的，2、公共的， 3、参与过的，4、已结束的
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType1(String uid, int type, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorPointList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorPointList(uid, pageRequest);
        }
    }

    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid      医生标识
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType9(String uid, long id, int pagesize) {
        return null;
    }

    /**
     * 公共三师咨询列表查询
     *
     * @param uid      医生标识
     * @param type     咨询类型：1、咨询我的，2、公共的， 3、参与过的，4、已结束的
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType2(String uid, int type, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);

        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 未指定医生
        filters.put("type", new SearchFilter("type", Operator.EQ, 0));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 未回复
        filters.put("status", new SearchFilter("status", Operator.EQ, 0));
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<ConsultTeam> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeam.class);

        return consultTeamDao.findAll(spec, pageRequest);
    }

    /**
     * 医生参与过的未结束的三师咨询列表查询
     *
     * @param uid
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType3(String uid, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorJoinList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorJoinList(uid, pageRequest);
        }
    }

    /**
     * 医生参与过的已结束的三师咨询列表查询
     *
     * @param uid
     * @param pagesize
     * @return
     */
    public Page<ConsultTeam> findByDoctorType4(String uid, long id, int pagesize) {
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        if (id > 0) {
            return consultTeamDao.findDoctorFinishList(uid, id, pageRequest);
        } else {
            return consultTeamDao.findDoctorFinishList(uid, pageRequest);
        }
    }

    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    public Page<ConsultTeamLog> findLogByConsult(String consult, long id, int pagesize) {
        if (id < 0) {
            id = 0;
        }

        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("consult", new SearchFilter("consult", Operator.EQ, consult));

        if (id > 0) {
            if (pagesize > 0)
                filters.put("id", new SearchFilter("id", Operator.LT, id));
            else
                filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<ConsultTeamLog> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeamLog.class);

        if (pagesize <= 0) {
            Page<ConsultTeamLog> p = new PageImpl<>(consultTeamLogDao.findAll(spec));
            return p;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        return consultTeamLogDao.findAll(spec, pageRequest);
    }

    /**
     * 批量回复
     *
     * @param logs
     * @return
     */
    public void reply(List<ConsultTeamLog> logs, String patient) throws Exception {
        ConsultTeam consultTeam = consultTeamDao.findByConsult(logs.get(0).getConsult());
        WlyyTalkGroup wlyyTalkGroup = talkGroupService.findConsultTalkGroupByType(logs.get(0).getConsult(), 2);
        for (ConsultTeamLog log : logs) {
            reply(log, patient, null, log.getType());
            //判断当前咨询是否创建讨论租
            if (wlyyTalkGroup != null) {
                sendGroupIM(patient, wlyyTalkGroup.getCode(), log.getChatType() + "", log.getContent());
            } else {
                //推送给IM
                sendIM(patient, consultTeam.getDoctor(), log.getChatType() + "", log.getContent());
            }
        }
    }

    /**
     * 查询居民咨询记录
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pageSize
     * @return
     */
    public JSONArray findByPatientAndTeam(String patient, Long teamCode, int page, int pageSize) {
        PageRequest pageRequest = new PageRequest(page, pageSize);
        Patient p = patientDao.findByCode(patient);
        Page<Object> result = consultDao.findByPatientAndTeam(patient, teamCode, pageRequest);
        JSONArray array = new JSONArray();

        for (Object obj : result) {
            JSONObject consult = new JSONObject();
            Object[] objArr = (Object[]) obj;
            consult.put("id", objArr[0]);
            consult.put("code", objArr[2]);
            consult.put("type", objArr[1]);
            consult.put("title", objArr[3]);
            consult.put("symptoms", objArr[4]);
            consult.put("czrq", objArr[5]);
            consult.put("status", objArr[6]);
            consult.put("adminTeamCode", objArr[7]);
            consult.put("team", objArr[8]);
            consult.put("patient", patient);
            consult.put("patientName", p.getName());
            consult.put("patientPhoto", p.getPhoto());
            array.put(consult);
        }

        return array;
    }

    /**
     * 添加咨询记录
     *
     * @param log  日志对象
     * @param type 类型，0问，1回复，2追问，3评价
     * @return
     */
    public ConsultTeamLog reply(ConsultTeamLog log, String patient, String teamOrDoctor, int type) {
        log.setCzrq(clock.getCurrentDate());
        // 保存咨询记录
        ConsultTeamLog temp = consultTeamLogDao.save(log);
        if (temp != null) {
            // 发送消息
            if (type == 1) {
                // 医生回复，给患者发消息
                // sendMessage(patient, teamOrDoctor, "三师咨询", log.getDoctorName() + "回复了您的咨询", log.getConsult(), 214, 1, 0, 0);
                // 患者未读数量+1
                consultTeamDao.increasePatientRead(log.getConsult());
                // 医生有回复
                consultTeamDoctorDao.updateReply(log.getConsult(), teamOrDoctor);

                //shenzaixin v1.2.0 推送消息给患者
                //HttpUtil.sendWeixinWebsocketMsg(patient, "{busiType:'qianyuezixun',msgid:'" + log.getId() + "'}");
            } else if (type == 0 || type == 2) {
                // 查询相关联的医生
                Iterable<ConsultTeamDoctor> iterable = consultTeamDoctorDao.findByConsult(log.getConsult());
                if (iterable != null && iterable.iterator() != null && iterable.iterator().hasNext()) {
                    Iterator<ConsultTeamDoctor> iterator = iterable.iterator();
                    while (iterator.hasNext()) {
                        // 患者提问或追问，给医生发消息
                        ConsultTeamDoctor ctd = iterator.next();
                        if (ctd == null) {
                            continue;
                        }
                        // 推送消息给医生
                        PushMsgTask.getInstance().put(ctd.getTo(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.D_CT_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.您有新的消息.name(), temp.getConsult());
                    }
                }
                // 医生未读数量+1
                consultTeamDao.increaseDoctorRead(log.getConsult());
            }
        }
        return temp;
    }

    /**
     * 患者端
     * 添加三师咨询
     *
     * @param ct      三师咨询对象
     * @param patient 患者标识
     * @return
     * @throws Exception
     */
    public int addTeamConsult(ConsultTeam ct, String patient,String agent) throws Exception {
        JSONObject users = new JSONObject();

        if(patient.equals(agent)){
            agent = null;
        }

        // 咨询三师
        if (ct.getType() == 1) {
            // 查询三师签约信息
            SignFamily sc = signFamilyDao.findBySanshiPatientYes(patient);
            if (sc == null) {
                // 不存在三师签约
                return -2;
            }
            ct.setTeam(sc.getTeamCode());
            // 设置健康管理师，三师咨询默认给健康管理师处理
            //查找病人所在的团队
            DoctorTeam doctorTeam = doctorTeamDao.findBySanshiParientCode(patient);
            //得到团队的健康管理师
            DoctorTeamMember doctorTeamMemberHealthy = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 3);
            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctorSanshi2ByTeam(doctorTeam.getCode(), 2);
            if (doctorTeamMemberHealthy == null) {
                ct.setDoctor(doctorTeamMember.getMemberCode());
                users.put(doctorTeamMember.getMemberCode(), 0);
            } else {
                users.put(doctorTeamMemberHealthy.getMemberCode(), 0);
                if (doctorTeamMember != null) {
                    if (users.isNull(doctorTeamMember.getMemberCode())) {
                        users.put(doctorTeamMember.getMemberCode(), 1);
                    }
                }
                ct.setDoctor(doctorTeamMemberHealthy.getMemberCode());
            }
            // 设置家庭医生

            ct.setAdminTeamId(sc.getAdminTeamId());
        } else if (ct.getType() == 2) {
            // 咨询家庭医生
            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);

            if (sf == null) {
                // 不存在家庭签约
                return -1;
            }
            ct.setTeam(sf.getTeamCode());
            // 设置健康管理师，家庭医生咨询默认给健康管理师处理
            //查找病人所在的团队
            //1.3.3.2 更改从签约记录判断团队成员,分配建管师
            if(StringUtils.isNotBlank(sf.getDoctorHealth())) {
                users.put(sf.getDoctorHealth(), 0);
                ct.setDoctor(sf.getDoctorHealth());
                if (StringUtils.isNotBlank(sf.getDoctor())) {
                    if (users.isNull(sf.getDoctor())) {
                        users.put(sf.getDoctor(), 1);
                   }
                }
            } else {
                ct.setDoctor(sf.getDoctor());
                users.put(sf.getDoctor(), 0);
            }

//            DoctorTeam doctorTeam = doctorTeamDao.findByParientCode(patient);
//            //得到团队的健康管理师
//            DoctorTeamMember doctorTeamMemberHealthy = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 3);
//            DoctorTeamMember doctorTeamMember = doctorTeamDoctor.findDoctorJiating2ByTeam(doctorTeam.getCode(), 2);
//            if (doctorTeamMemberHealthy == null) {
//                ct.setDoctor(doctorTeamMember.getMemberCode());
//                users.put(doctorTeamMember.getMemberCode(), 0);
//            } else {
//                users.put(doctorTeamMemberHealthy.getMemberCode(), 0);
//                if (doctorTeamMember != null) {
//                    //全健同一个人导致会话成员状态问题处理
//                    if (users.isNull(doctorTeamMember.getMemberCode())) {
//                        users.put(doctorTeamMember.getMemberCode(), 1);
//                    }
//                }
//                ct.setDoctor(doctorTeamMemberHealthy.getMemberCode());
//            }

            // 设置家庭医生
            ct.setAdminTeamId(sf.getAdminTeamId());
        }
        // 设置患者信息
        ct.setPatient(patient);
        // 查询患者信息
        Patient tempPatient = patientDao.findByCode(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);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 添加咨询记录
        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
        // 设置关联指导
        consult.setGuidance(ct.getGuidance());
        // 设置咨询标识
        ct.setConsult(consult.getCode());

        //推送给IM去创建议题，取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), "咨询问题："+consult.getSymptoms(), consult.getImages());
        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(),agent);
        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
        JSONObject obj = ImUtill.createTopics(patient + "_" + ct.getTeam() + "_" + ct.getType(), consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_MUC);
        if (obj == null) {
            throw new RuntimeException("IM消息发送异常！");
        }
        ct.setStartMsgId(obj.get("start_msg_id").toString());
        consultTeamDao.save(ct);
        consultDao.save(consult);
        for (String key : users.keySet()) {
            if (patient.equals(key)) {
                continue;
            }
            //记录咨询的医生详情误删
            ConsultTeamDoctor cd = new ConsultTeamDoctor();
            cd.setConsult(consult.getCode());
            cd.setDel("1");
            cd.setCzrq(new Date());
            cd.setTo(key);
            consultTeamDoctorDao.save(cd);
        }

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

        return 1;
    }

    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param to
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendIM(String from, String to, String contentType, String content) {
        String imAddr = SystemConf.getInstance().getImListGet() + "api/v1/chats/pm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = HttpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }

    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param groupCode
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendGroupIM(String from, String groupCode, String contentType, String content) {
        String imAddr = SystemConf.getInstance().getImListGet() + "api/v1/chats/gm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("group", groupCode));
        params.add(new BasicNameValuePair("groupType", "1"));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = HttpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }

    /**
     * 添加三师咨询日志
     *
     * @param ct
     * @throws Exception
     */
    private String addLogs(ConsultTeam ct) throws Exception {
        List<ConsultTeamLog> logs = new ArrayList<ConsultTeamLog>();
        // 添加问题咨询日志
        String content = "";

        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
            //先判断从健康指导转咨询是否存在指导。
            JSONObject json = guidanceService.findById(ct.getGuidance());

            if (json == null) {
                //再判断从健康教育文章转咨询是否存在文章 20170602
                HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
                if (article != null) {
                    String result = verdictAddLogs(ct);
                    return result;
                }
                throw new Exception("guidance not exist");
            } else {
                //  健康指导转咨询的指导内容
                content += "医生" + (json.get("doctorName") != null ? json.get("doctorName").toString() : "")
                        + "发出的指导:" + (json.getString("content") != null ? json.getString("content").toString() : "") + "<br/>";
            }

        }

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

        // 生成提问日志，并推送相关消息
        ConsultTeamLog infoLog = new ConsultTeamLog();
        infoLog.setConsult(ct.getConsult());
        infoLog.setContent(content);
        infoLog.setDel("1");
        infoLog.setType(0);
        infoLog.setChatType(1);
        infoLog.setCzrq(new Date());
        logs.add(infoLog);
        // 图片日志
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    ConsultTeamLog imgLog = new ConsultTeamLog();
                    // 设置咨询标识
                    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 (StringUtils.isNotEmpty(ct.getVoice())) {
            ConsultTeamLog voiceLog = new ConsultTeamLog();
            // 设置咨询标识
            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<ConsultTeamLog> 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 ct
     * @throws Exception
     */
    private String verdictAddLogs(ConsultTeam ct) throws Exception {
        List<ConsultTeamLog> logs = new ArrayList<ConsultTeamLog>();
        // 添加问题咨询日志
        String content = "";

        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
            //再判断从健康教育文章转咨询是否存在文章 20170602
            HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
            if (article == null) {
                throw new Exception("guidance not exist");
            } else {
                //  健康指导转咨询的指导内容
                JSONObject jsonArticle = new JSONObject();

                jsonArticle.put("doctorName", ct.getDoctorName()!=null?ct.getDoctorName():"");
                jsonArticle.put("content", article.getSummary()!=null?article.getSummary():"");
                jsonArticle.put("czrq", article.getCzrq() != null ? DateUtil.dateToStr(article.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM) : "");

                content += "医生" + (jsonArticle.get("doctorName") != null ? jsonArticle.get("doctorName").toString() : "")
                        + "发出的文章:" + (jsonArticle.getString("content") != null ? jsonArticle.getString("content").toString() : "") + "<br/>";
            }

        }

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

        // 生成提问日志，并推送相关消息
        ConsultTeamLog infoLog = new ConsultTeamLog();
        infoLog.setConsult(ct.getConsult());
        infoLog.setContent(content);
        infoLog.setDel("1");
        infoLog.setType(0);
        infoLog.setChatType(1);
        infoLog.setCzrq(new Date());
        logs.add(infoLog);
        // 图片日志
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    ConsultTeamLog imgLog = new ConsultTeamLog();
                    // 设置咨询标识
                    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 (StringUtils.isNotEmpty(ct.getVoice())) {
            ConsultTeamLog voiceLog = new ConsultTeamLog();
            // 设置咨询标识
            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<ConsultTeamLog> 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 patientCode 患者标志
     * @param status      咨询状态（0未结束，1已结束，-1 已取消）
     * @param pageSize    页数
     * @return
     */
    public Page<ConsultTeam> findByPatient(String patientCode, int status, long id, int pageSize) {
        if (id < 0) {
            id = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);

        Page<ConsultTeam> list = null;
        switch (status) {
            case 0:
                // 未结束
                if (id > 0) {
                    list = consultTeamDao.findNotFinishedBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findNotFinishedBypatient(patientCode, pageRequest);
                }
                break;
            case 1:
                // 已结束
                if (id > 0) {
                    list = consultTeamDao.findFinishedBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findFinishedBypatient(patientCode, pageRequest);
                }
                break;
            case -1:
                // 已取消
                if (id > 0) {
                    list = consultTeamDao.findCancelBypatient(patientCode, id, pageRequest);
                } else {
                    list = consultTeamDao.findCancelBypatient(patientCode, pageRequest);
                }
                break;
        }
        return list;
    }

    /**
     * 医生关闭三师咨询
     *
     * @param consult 三师咨询标识
     * @return
     */
    public int finish(String consult, String endOperator, int endType) throws Exception {

        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
        String name = "";
        String returnJson = "";
        //推送给IM文字消息
        if (endType == 1) {
            Patient p = patientDao.findByCode(endOperator);
            name = p.getName();
            returnJson = sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
        } else {
            Doctor d = doctorDao.findByCode(endOperator);
            name = d.getName();
            returnJson = sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
        }

        if (StringUtils.isEmpty(returnJson)) {
            throw new Exception("send consult finished IM message failed");
        } else {
            JSONObject jo = new JSONObject(returnJson);            //设置消息ID
            consultTeam.setEndMsgId(jo.getInt("startId") + "");
            consultTeam.setEndOperator(endOperator);
            consultTeam.setEndType(endType);
        }

        JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());

        if (group != null) {
            String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");

            if (StringUtils.isEmpty(json)) {
                throw new Exception("send consult finished IM message failed");
            }
        }

        return consultTeamDao.updateStatusByConsult(consult);
    }

    /**
     * 设置咨询已读
     *
     * @param consult
     * @return
     */
    @Transactional
    public int readMessage(String consult) {
        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
        consultTeam.setDoctorRead(0);
        return 1;
    }

    /**
     * 取消三师咨询
     *
     * @param consult
     * @return
     */
    public int cancel(String consult) {
        return consultTeamDao.cancel(consult);
    }

    public ConsultTeam findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }

    /**
     * 三师咨询转接医生
     *
     * @param from    转出医生标识
     * @param to      转入医生标识
     * @param consult 三师咨询标识
     * @return
     */
    public void transfer(String from, String to, String consult) {
        // 检查是否存在
        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
            ConsultTeam ct = consultTeamDao.findByConsult(consult);
            int count = consultTeamLogDao.countByConsult(consult);
            // 设置未读消息数
            ct.setDoctorRead(count);
            consultTeamDao.save(ct);
            // 查询医生信息
            Doctor d = doctorDao.findByCode(from);
            // 再保存
            ConsultTeamDoctor cd = new ConsultTeamDoctor();
            cd.setConsult(consult);
            cd.setDel("1");
            cd.setCzrq(new Date());
            cd.setFrom(d.getCode());
            cd.setFromName(d.getName());
            cd.setTo(to);
            consultTeamDoctorDao.save(cd);
        }
    }

    /**
     * 查询患者视频和三师咨询记录
     *
     * @param patient  患者标识
     * @param id
     * @param pagesize
     * @return
     */
    public Page<Consult> findConsultRecordByPatientType(String patient, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
        filters.put("type", new SearchFilter("type", Operator.LT, 3));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<Consult> spec = DynamicSpecifications.bySearchFilter(filters.values(), Consult.class);
        return consultDao.findAll(spec, pageRequest);
    }

    /**
     * 清空医生未读数量
     *
     * @param consult
     */
    public void clearDoctorRead(String consult) {
        consultTeamDao.clearDoctorRead(consult);
    }

    /**
     * 清空患者未读数量
     *
     * @param consult
     */
    public void clearPatientRead(String consult) {
        consultTeamDao.clearPatientRead(consult);
    }

    /**
     * 查询医生的咨询统计
     *
     * @param doctorCode
     * @return
     */
    public Map<String, Long> getAllCount(String doctorCode) {
        Map<String, Long> result = new HashMap<>();

        //根据医生code查询总咨询数
        long allCount = consultTeamDoctorDao.getAllCountByDoctorCode(doctorCode);

        //根据医生code查询今日咨询数
        long todayCount = consultTeamDoctorDao.getTodayCountByDoctorCode(doctorCode);

        result.put("all", allCount);
        result.put("today", todayCount);

        return result;
    }

    /**
     * 查找未完成咨询
     *
     * @param patient
     * @return
     */
    public List<ConsultTeam> getUnfinishedConsult(String patient) {
        return consultTeamDao.findUnfinishedConsult(patient);
    }

    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     * @return
     */
    public List<ConsultTeam> getUnfinishedConsult(String patient, String doctor) {
        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
    }


    /**
     * 查询患者全部的咨询数目
     *
     * @param patientCode
     * @return
     */
    public Integer findByDoctorSize(String patientCode, String doctorCode) {

        return consultDao.findByPatient(patientCode, doctorCode);
    }

    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();

        for (int i = 0; i < consults.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(consults));
        paramList.addAll(Arrays.asList(consults));

        String sqlgp = "select DISTINCT consult,to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlgpm = "select DISTINCT to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.consult,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.to_doctor = b.qkdoctor_code group by a.consult ";

        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }

    public ConsultTeamLog oneLog(Long logId) {
        return consultTeamLogDao.findOne(logId);
    }

    public boolean isExistConsult(String uid, String doctor) {
        int consultTeam = consultTeamDao.countByPatient(uid, doctor);
        if (consultTeam > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 进入咨询
     * @param consult
     * @param patient
     * @param agent
     * @return
     */
    public int intoTopic(String consult,String patient,String agent) throws Exception{
        ConsultTeam ct = consultTeamDao.findByConsult(consult);
        if(ct.getStatus()!=0){
            return -1;
        }

        String content = "进入了咨询";
        Patient p = patientDao.findByCode(patient);
        String intoUserName = p.getName();
        if(patient.equals(agent)){
            content = intoUserName+content;
        }else {
            PatientFamilyMember familyMember = familyMemberDao.findByPatientAndFamilyMember(patient,agent);
            Patient member = patientDao.findByCode(agent);
            content = member.getName() + "("+relations.get(familyMember.getFamilyRelation())+")"+content;
        }

        ImUtill.sendIntoTopicIM(ct.getPatient(),ct.getPatient(),ct.getConsult(),content,agent,intoUserName);

        return 0;
    }

    /**
     * @param ct
     * @param uid
     * @param type 1患者 2医生
     * @throws Exception
     */
    public void addFamousTeamConsult(ConsultTeam ct, String uid, String type) throws Exception {
        // 设置患者信息
        ct.setPatient(uid);
        if ("1".equals(type)) {
            // 查询患者信息
            Patient tempPatient = patientDao.findByCode(uid);
            // 设置患者姓名
            ct.setName(tempPatient.getName());
            // 设置患者生日
            ct.setBirthday(tempPatient.getBirthday());
            //新增性别
            ct.setSex(tempPatient.getSex());
            // 设置患者头像
            ct.setPhoto(tempPatient.getPhoto());
        } else if ("2".equals(type)) {
            Doctor doctorTemp = doctorDao.findByCode(uid);
            // 设置医生姓名
            ct.setName(doctorTemp.getName());
            // 设置医生生日
            ct.setBirthday(doctorTemp.getBirthday());
            //新增性别
            ct.setSex(doctorTemp.getSex());
            // 设置医生头像
            ct.setPhoto(doctorTemp.getPhoto());
        }
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 患者未读数量为0
        ct.setPatientRead(0);
        // 添加咨询记录
        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
        // 设置咨询标识
        ct.setConsult(consult.getCode());
        // 添加咨询转发记录
        ConsultTeamDoctor cd = new ConsultTeamDoctor();
        cd.setConsult(consult.getCode());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(ct.getDoctor());
        // 添加医生咨询日志
        String content = addLogs(ct);
        //推送给IM文字消息
        String returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
        ;
        JSONObject jo = new JSONObject(returnJson);
        //设置消息ID
        ct.setStartMsgId(jo.getInt("startId") + "");
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                }
            }
        }
        consultTeamDao.save(ct);  // 保存医生咨询信息
        consultTeamDoctorDao.save(cd);
        consultDao.save(consult);
    }

    /**
     * 根据健康管理师和患者 找到正在进行中的咨询
     *
     * @param patientCode
     * @param doctor
     */
    public ConsultTeam getConsultByPatientAndDoctor(String patientCode, String doctor) {
        ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patientCode, doctor, 2);
        return consultTeam;
    }

    public void transfers(String uid, String doctor, String consult) {
        String[] doctors = doctor.split(",");
        for (int i = 0; i < doctors.length; i++) {
            transfer(uid, doctors[i], consult);
        }
    }

    public String produceConsultAdminTeamCode() {
        StringBuffer sf = new StringBuffer();
        StringBuffer sf1 = new StringBuffer();
        Long size = 0L;
        //找出家庭签约中团队code是空的
        List<ConsultTeam> consultTeams = consultTeamDao.findByTypeAndAdminTeamIdIsNull(2);
        sf.append("家庭签约咨询中团队code是空的数据数:" + consultTeams.size());
        for (ConsultTeam consultTeam : consultTeams) {
            //得到签约中的全科医生的团队
            SignFamily signfamily = signFamilyDao.findByjiatingPatient(consultTeam.getPatient());
            if (signfamily != null) {
                if (signfamily.getAdminTeamId() != null && signfamily.getAdminTeamId() > 0) {
                    consultTeam.setAdminTeamId(signfamily.getAdminTeamId());
                    size++;
                }
            } else {
                sf1.append(",找不到医生所属的团队,家庭签约咨询的Id:" + consultTeam.getId());
            }
        }
        sf.append(",填充团队的签约数据数:" + size);
        sf.append(sf1);
        return sf.toString();
    }

    public void save(ConsultTeam consult) {
        consultTeamDao.save(consult);
    }

    public ConsultTeam findByConsultCode(String consultCode) {
        return consultTeamDao.findByConsult(consultCode);
    }

    /**
     * @param consultCode
     * @return
     */
    public List<ConsultTeamLog> getConsultLog(String consultCode) {
        return consultTeamLogDao.getConsultLogByConsultLog(consultCode);
    }

    /**
     * @param ct
     * @param uid
     * @throws Exception
     */
    public void addForHelpTeamConsult(ConsultTeam ct, String uid, String oldConsultCode) throws Exception {
        // 设置患者信息
        ct.setPatient(uid);
        Doctor doctorTemp = doctorDao.findByCode(uid);
        // 设置医生姓名
        ct.setName(doctorTemp.getName());
        // 设置医生生日
        ct.setBirthday(doctorTemp.getBirthday());
        //新增性别
        ct.setSex(doctorTemp.getSex());
        // 设置医生头像
        ct.setPhoto(doctorTemp.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 患者未读数量为0
        ct.setPatientRead(0);
        // 添加咨询记录
        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
        // 设置咨询标识
        ct.setConsult(consult.getCode());
        // 添加咨询转发记录
        ConsultTeamDoctor cd = new ConsultTeamDoctor();
        cd.setConsult(consult.getCode());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(ct.getDoctor());
        // 添加医生咨询日志
        String content = addLogs(ct);
        //推送给IM文字消息
        String returnJson = null;
        JSONObject jo;
        if (StringUtils.isNotEmpty(oldConsultCode)) {
            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
            if (oldConsult != null) {
                returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题：" + oldConsult.getSymptoms());
                //推送给IM图片
                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
                    String[] images = oldConsult.getImages().split(",");
                    for (String image : images) {
                        if (StringUtils.isNoneEmpty(image)) {
                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                        }
                    }
                }
            }
        }
        if (StringUtils.isEmpty(returnJson))
            returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
        else
            sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
        jo = new JSONObject(returnJson);
        //设置消息ID
        ct.setStartMsgId(jo.getInt("startId") + "");
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                }
            }
        }
        consultTeamDao.save(ct);  // 保存医生咨询信息
        consultTeamDoctorDao.save(cd);
        consultDao.save(consult);
    }

    /**
     * @param ct
     * @param uid
     * @throws Exception
     */
    public void sendForHelpMsg(ConsultTeam ct, String uid, String oldConsultCode) throws Exception {
        ct.setPatient(uid);
        //推送给IM文字消息
        if (StringUtils.isNotEmpty(oldConsultCode)) {
            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
            if (oldConsult != null) {
                sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题：" + oldConsult.getSymptoms());
                //推送给IM图片
                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
                    String[] images = oldConsult.getImages().split(",");
                    for (String image : images) {
                        if (StringUtils.isNoneEmpty(image)) {
                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                        }
                    }
                }
            }
        }
        sendIM(ct.getPatient(), ct.getDoctor(), "6", "咨询问题：" + ct.getSymptoms());
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
                }
            }
        }
    }

    /**
     * @param uid
     * @throws Exception
     */
    public List<ConsultTeam> hasUnfinished(String doctorCode, String uid) throws Exception {
        return consultTeamDao.findUnfinishedConsult(uid, doctorCode);
    }

    /**
     * 判断两医生是否在同一团队内
     *
     * @param docCode1
     * @param docCode2
     * @return
     */
    public boolean isCommonTeam(String docCode1, String docCode2) {
        String sqlQuSum =
                "SELECT c.team_id FROM " +
                        "(SELECT a.* FROM wlyy_admin_team_member a where a.doctor_code='" + docCode1 + "' ) c " +
                        "LEFT JOIN " +
                        "(SELECT b.* FROM wlyy_admin_team_member b where b.doctor_code='" + docCode2 + "' ) d " +
                        "on c.team_id=d.team_id " +
                        "WHERE d.team_id IS NOT NULL";
        List ls = jdbcTemplate.queryForList(sqlQuSum);
        return ls != null && ls.size() > 0;
    }

    /**
     * 通过team获取医生code
     *
     * @param consult 关联的上一个咨询
     * @return
     */
    public List findByTeam(String consult) {
        return consultTeamDao.findByTeamAndType(consult, 10);
    }

    /**
     * 全科医生求助专科医生(同团队)
     *
     * @param ct
     * @param uid
     * @param oldConsultCode
     * @param isSend         是否转发患者咨询内容
     */
    public void addSeekHelpTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) {
        ct.setPatient(uid);
        //推送给IM文字消息
        JSONObject participants = new JSONObject();
        participants.put(ct.getPatient(), 0);
        participants.put(ct.getDoctor(), 0);
        Doctor doctor = doctorService.findDoctorByCode(uid);
        JSONObject sessionJson = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, doctor.getName() + "发起求助！", "");
        if (sessionJson.getInt("status") == -1) {
            throw new RuntimeException(sessionJson.getString("message"));
        }
        JSONObject session = sessionJson.getJSONObject("data");
        if (StringUtils.isNotEmpty(oldConsultCode)) {
            ct.setTeam(oldConsultCode);
            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
            if (oldConsult != null && isSend == 1) {
                ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "居民问题：" + oldConsult.getSymptoms(), "1");
                //推送给IM图片
                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
                    String[] images = oldConsult.getImages().split(",");
                    for (String image : images) {
                        if (StringUtils.isNoneEmpty(image)) {
                            ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
                        }
                    }
                }
            }
            Doctor doctorTemp = doctorDao.findByCode(ct.getDoctor());
            JSONObject qiuzuObj = new JSONObject();
            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
            qiuzuObj.put("patient", ct.getPatient());
            qiuzuObj.put("old_consult_code", oldConsultCode);
            qiuzuObj.put("doctor", ct.getDoctor());
            qiuzuObj.put("doctor_name", doctorTemp.getName());
            ImUtill.sendTopicIM(doctor.getCode(), doctor.getName(), oldConsultCode, "5", qiuzuObj.toString(),null);
        }


        ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "咨询问题：" + ct.getSymptoms(), "1");
        //推送给IM图片
        if (StringUtils.isNotEmpty(ct.getImages())) {
            String[] images = ct.getImages().split(",");
            for (String image : images) {
                if (StringUtils.isNoneEmpty(image)) {
                    ImUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
                }
            }
        }
    }

    /**
     * 全科医生求助专科医生(不同团队)
     *
     * @param ct
     * @param uid
     * @param oldConsultCode
     */
    public void addSeekHelpOtherTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) throws Exception {
        // 设置患者信息
        ct.setPatient(uid);
        Doctor doctorTemp = doctorDao.findByCode(uid);
        Doctor doctor = doctorDao.findByCode(ct.getDoctor());
        // 设置医生姓名
        ct.setName(doctorTemp.getName());
        // 设置医生生日
        ct.setBirthday(doctorTemp.getBirthday());
        //新增性别
        ct.setSex(doctorTemp.getSex());
        // 设置医生头像
        ct.setPhoto(doctorTemp.getPhoto());
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 患者未读数量为0
        ct.setPatientRead(0);
        // 添加咨询记录
        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
        // 设置咨询标识
        ct.setConsult(consult.getCode());
        // 添加咨询转发记录
        ConsultTeamDoctor cd = new ConsultTeamDoctor();
        cd.setConsult(consult.getCode());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(ct.getDoctor());
        // 添加医生咨询日志
        String content = addLogs(ct);
        if (StringUtils.isBlank(oldConsultCode)) {
            JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, consult.getImages(),null);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ct.getPatient(), 0);
            jsonObject.put(ct.getDoctor(), 0);
            //设置消息ID
            JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
            if (obj == null || obj.getInt("status") == -1) {
                throw new RuntimeException("im消息创建异常！" + obj == null ? "" : obj.getString("message"));
            }
            ct.setStartMsgId(obj.get("start_msg_id").toString());
        } else {
            //转发咨询问题
            Consult oldConsult = consultDao.findByCode(oldConsultCode);
            ConsultTeam consultTeam = consultTeamDao.findByConsult(oldConsultCode);
            ct.setTeam(oldConsultCode);
            if (oldConsult != null && isSend == 1) {
                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), "居民问题:" + oldConsult.getSymptoms(), oldConsult.getImages(),null);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(ct.getPatient(), 0);
                jsonObject.put(ct.getDoctor(), 0);
                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
                if (obj == null || obj.getInt("status") == -1) {
                    throw new RuntimeException("im消息创建异常！" + obj == null ? "" : obj.getString("message"));
                }
                ct.setStartMsgId(obj.get("start_msg_id").toString());
                Thread.sleep(100);//消息发送顺序问题处理
                ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "6", content, null);
                if (StringUtils.isNotBlank(consult.getImages())) {
                    String imgs[] = consult.getImages().split(",");
                    for (String url : imgs)
                        ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "2", url, null);
                }
            } else if (oldConsult != null && isSend == 0) {
                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, oldConsult.getImages(),null);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(ct.getPatient(), 0);
                jsonObject.put(ct.getDoctor(), 0);
                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
                if (obj == null || obj.getInt("status") == -1) {
                    throw new RuntimeException("im消息创建异常！" + obj == null ? "" : obj.getString("message"));
                }
            }
            JSONObject qiuzuObj = new JSONObject();
            qiuzuObj.put("session_id", oldConsult.getPatient() + consultTeam.getTeam() + consult.getType());
            qiuzuObj.put("patient", ct.getPatient());
            qiuzuObj.put("old_consult_code", oldConsultCode);
            qiuzuObj.put("doctor", ct.getDoctor());
            qiuzuObj.put("doctor_name", doctor.getName());
            ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
        }
        consultTeamDao.save(ct);  // 保存医生咨询信息
        consultTeamDoctorDao.save(cd);
        consultDao.save(consult);
    }

    public int finishConsult(String consult, String endOperator, int endType) throws Exception{
        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
        Consult cons = consultDao.findByCode(consult);

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

        String endName = "";
        String endId = "";
        //推送给IM文字消息
        if (endType == 1) {
            Patient p = patientDao.findByCode(endOperator);
            endName = p.getName();
            endId = p.getCode();
            if (consultTeam.getType() == 2) {
                String openId = p.getOpenid();
                JSONObject json = new JSONObject();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                json.put("keyword1", "满意度评价");
                json.put("keyword2", sdf.format(new Date()));
                json.put("toUser", p.getCode());
                json.put("represented",p.getCode());//被代理人
                json.put("remark", "");
                json.put("consult", consult);
                String first = endName + "，您好！您有1条咨询已结束，请及时对咨询医生进行满意度评价。";
                json.put("first", first);
                if(StringUtils.isNotBlank(p.getOpenid())){
                    PushMsgTask.getInstance().putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
                }

                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                if(jsonArray!=null&&jsonArray.length()>0){
                    for (int i = 0;i<jsonArray.length();i++){
                        JSONObject j  = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser",member.getCode());
                        data.remove("first");
                        data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName())+first);
                        PushMsgTask.getInstance().putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                    }
                }
            }
        } else {
            if (endOperator.equals("admin")) {
                endId = "system";
                endName = "咨询超时未回复，系统自动";
            } else {
                Doctor d = doctorDao.findByCode(endOperator);
                endId = d.getCode();
                endName = d.getName();
            }
            if (consultTeam.getType() == 2) {
                Patient p = patientDao.findByCode(consultTeam.getPatient());
                String name = p.getName();
                String openId = p.getOpenid();
                JSONObject json = new JSONObject();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                json.put("keyword1", "满意度评价");
                json.put("keyword2", sdf.format(new Date()));
                json.put("toUser", p.getCode());
                json.put("represented",p.getCode());//被代理人
                json.put("remark", "");
                json.put("consult", consult);
                String first = name + "，您好！您有1条咨询已结束，请及时对咨询医生进行满意度评价。";
                json.put("first", first);
                if(StringUtils.isNotBlank(p.getOpenid())){
                    PushMsgTask.getInstance().putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
                }

                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                if(jsonArray!=null&&jsonArray.length()>0){
                    for (int i = 0;i<jsonArray.length();i++){
                        JSONObject j  = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser",member.getCode());
                        data.remove("first");
                        data.put("first",weiXinOpenIdUtils.getTitleMes(p,j.getInt("relation"),p.getName())+first);
                        PushMsgTask.getInstance().putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
                    }
                }

            }
        }
        JSONObject obj = ImUtill.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
        if (obj == null) {
            throw new RuntimeException("IM消息结束异常！");
        }
        if (obj.getInt("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);
        return 1;
    }


    /**
     * 新增名医咨询
     *
     * @param ct
     * @param uid
     * @param type 1患者 2医生
     * @param agent 代理人
     * @throws Exception
     */
    public JSONObject famousConsult(ConsultTeam ct, String uid, String type,String agent) throws Exception {
        // 设置患者信息
        agent = uid.equals(agent)?null:agent;
        ct.setPatient(uid);
        String senderId = "";
        String senderName = "";
        if ("1".equals(type)) {
            // 查询患者信息
            Patient tempPatient = patientDao.findByCode(uid);
            // 设置患者姓名
            ct.setName(tempPatient.getName());
            // 设置患者生日
            ct.setBirthday(tempPatient.getBirthday());
            //新增性别
            ct.setSex(tempPatient.getSex());
            // 设置患者头像
            ct.setPhoto(tempPatient.getPhoto());

            senderId = tempPatient.getCode();

            senderName = tempPatient.getName();

        } else if ("2".equals(type)) {
            Doctor doctorTemp = doctorDao.findByCode(uid);
            // 设置医生姓名
            ct.setName(doctorTemp.getName());
            // 设置医生生日
            ct.setBirthday(doctorTemp.getBirthday());
            //新增性别
            ct.setSex(doctorTemp.getSex());
            // 设置医生头像
            ct.setPhoto(doctorTemp.getPhoto());

            senderId = doctorTemp.getCode();

            senderName = doctorTemp.getName();
        }
        // 设置操作日期
        ct.setCzrq(new Date());
        ct.setDel("1");
        ct.setStatus(0);
        // 医生未读数量为1
        ct.setDoctorRead(1);
        // 患者未读数量为0
        ct.setPatientRead(0);
        // 添加咨询记录
        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
        // 设置咨询标识
        ct.setConsult(consult.getCode());
        // 添加咨询转发记录
        ConsultTeamDoctor cd = new ConsultTeamDoctor();
        cd.setConsult(consult.getCode());
        cd.setDel("1");
        cd.setCzrq(new Date());
        cd.setTo(ct.getDoctor());
        // 添加医生咨询日志
        String content = addLogs(ct);
        //推送给IM文字消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(ct.getPatient(), 0);
        jsonObject.put(ct.getDoctor(), 0);

        JSONObject messages = ImUtill.getCreateTopicMessage(senderId, senderName, senderName + "发起咨询", content, ct.getImages(),agent);

        JSONObject obj = ImUtill.createTopics(null, consult.getCode(), consult.getSymptoms(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
        if (obj == null) {
            throw new RuntimeException("im消息创建异常！");
        }
        if (obj.getInt("status") == -1) {
            throw new RuntimeException(obj.getString("message"));
        }
        //设置消息ID
        ct.setStartMsgId(obj.getString("start_msg_id"));
        JSONObject object = ImUtill.getTopic(ct.getConsult());
        JSONArray array = new JSONArray(object.get("data").toString());
        consultTeamDao.save(ct);  // 保存医生咨询信息
        consultTeamDoctorDao.save(cd);
        consultDao.save(consult);
        if (array == null || array.length() == 0) {
            //由于IM是异步操作，会话生成后，可能还未生成到数据库导致无法
            //获取会话ID。休眠1秒后继续获取相应信息
            // PS:可以通过前端请求两次去解决，由于离职，就不挖坑了，后来者可以改善、
            Thread.sleep(1000);
            object = ImUtill.getTopic(ct.getConsult());
            array = new JSONArray(object.get("data").toString());
        }
        return array.getJSONObject(0);
    }


    @Override
    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
        super.sendMucMessageBySingnType(doctor, doctorName, patient, content, contentType, title);
    }

    public void removeRenewPerson(JSONObject jsonObject,String uid){
        JSONArray j = jsonObject.getJSONArray("users");
        List<Integer> indexs =new ArrayList<>();
        if(j!=null&&j.length()>0){
            for(int i=0;i<j.length();i++){
                JSONObject doctor = (JSONObject) j.get(i);
                String code = (String)doctor.get("id");
                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+DateUtil.getSignYear()+"' AND t.patient ='"+uid+"' ";

                String SQL2 ="SELECT t.id FROM wlyy_sign_family t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+(DateUtil.getSignYear()-1)+"' AND t.patient ='"+uid+"' AND t.status>0 AND t.expenses_status ='1' ";
                List<Map<String,Object>> isExits = jdbcTemplate.queryForList(SQL);
                List<Map<String,Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
                if(isExitsSign==null){
                    if(isExits!=null&&isExits.size()>0){
                        indexs.add(i);
                    }
                }
            }
            if(indexs!=null&&indexs.size()>0){
                for(Integer index : indexs){
                    j.remove(index);
                }
            }
        }
    }

    public void removeRenewPerson(JSONArray j,String uid){
        List<Integer> indexs =new ArrayList<>();
        if(j!=null&&j.length()>0){
            for(int i=0;i<j.length();i++){
                JSONObject doctor = (JSONObject) j.get(i);
                String code = (String)doctor.get("id");
                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+DateUtil.getSignYear()+"' AND t.patient ='"+uid+"' ";

                String SQL2 ="SELECT t.id FROM wlyy_sign_family t " +
                        " WHERE (t.doctor ='"+code+"' OR t.doctor_health ='"+code+"' ) " +
                        " AND t.sign_year ='"+(DateUtil.getSignYear()-1)+"' AND t.patient ='"+uid+"' AND t.status>0 AND t.expenses_status ='1' ";
                List<Map<String,Object>> isExits = jdbcTemplate.queryForList(SQL);
                List<Map<String,Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
                if(isExitsSign==null){
                    if(isExits!=null&&isExits.size()>0){
                        indexs.add(i);
                    }
                }
            }
            if(indexs!=null&&indexs.size()>0){
                for(Integer index : indexs){
                    j.remove(index);
                }
            }
        }
    }
}
