package com.yihu.wlyy.web.patient.consult;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.DoctorCommentService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.statistics.DoctorStatisticsService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.DoctorStatisticsTask;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 患者端：三师咨询控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-患者咨询")
public class ConsultController extends WeixinBaseController {

    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private DoctorCommentService doctorCommentService;
    @Autowired
    private DoctorStatisticsService doctorStatisticsService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private TalkGroupService talkGroupService;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    PatientDao patientDao;

    /**
     * 患者咨询记录查询
     *
     * @param title    咨询标题
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    @RequestMapping(value = "records")
    @ResponseBody
    public String consultRecords(
            @RequestParam(required = false) String title,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Object> data = consultTeamService.findConsultRecordByPatient(getRepUID(), id, pagesize, title);
            if (data != null) {
                for (Object consult : data.getContent()) {
                    if (consult == null) {
                        continue;
                    }
                    Object[] result = (Object[]) consult;
                    JSONObject json = new JSONObject();
                    json.put("id", result[0]);
                    // 设置咨询类型：1三师咨询，2视频咨询，3图文咨询，4公共咨询，5病友圈
                    json.put("type", result[1]);
                    // 设置咨询标识
                    json.put("code", result[2]);
                    // 设置显示标题
                    json.put("title", result[3]);
                    // 设置主诉
                    json.put("symptoms", result[4]);
                    // 咨询状态
                    json.put("status", result[6]);
                    // 设置咨询日期
                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
                    // 咨询状态
                    json.put("doctorCode", result[7]);

                    json.put("teamCode", result[8]);

                    json.put("evaluate", result[9]);

                    //签约code
                    json.put("signCode", result[10]);

                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 获取医生的排班时间
     *
     * @param doctor
     * @param week
     * @return
     */
    @RequestMapping(value = "/doctor_worktime/week")
    @ResponseBody
    public String getDoctorWeekWorkTime(String doctor, String week) {
        try {
            JSONObject result = doctorWorkTimeService.findDoctorWeekWorkTime(doctor, week);

            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 获取医生某天的排班时间
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor_worktime")
    @ResponseBody
    public String getDoctorWorkTime(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.findDoctorWorkTime(doctor);

            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 医生是否在工作
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "is_doctor_working")
    @ResponseBody
    public String isDoctorAtWorking(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.isDoctorWorking(doctor);
            return write(200, result.getString("msg"), "data", result.getString("status"));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 名医是否在工作
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "is_famous_doctor_working")
    @ResponseBody
    public String isFamousDoctorAtWorking(String doctor) {
        try {
            JSONObject result = doctorWorkTimeService.isFamousDoctorWorking(doctor);
            return write(200, result.getString("msg"), "data", result.getString("status"));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 名医咨询剩余次数查询
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/consult_times_remain")
    @ResponseBody
    public String famousDoctorTimesRemain(String doctor) {
        try {
            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取未完成咨询
     *
     * @return
     */
    @RequestMapping(value = "/unfinished")
    @ResponseBody
    public String getUnFinishedConsult() {
        try {
//            List<ConsultTeam> unfinishedConsult = consultTeamService.getUnfinishedConsult(getUID());
            List<ConsultTeam> unfinishedConsult = consultTeamService.getUnfinishedConsult(getRepUID());
            JSONArray result = new JSONArray(unfinishedConsult);
            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 查询居民与某个医生是否存在未结束的咨询
     *
     * @param doctor 医生
     * @return
     */
    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isExistsUnfinishedConsult(@RequestParam(required = true) String doctor) {
        try {
            JSONObject result = new JSONObject();
            List<ConsultTeam> consults = consultTeamService.getUnfinishedConsult(getRepUID(), doctor);

            if (consults != null && consults.size() > 0) {
                return write(200, "查询成功", "data", consults.get(0).getConsult());
            } else {
                return write(200, "查询成功", "data", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 三师咨询添加接口
     *
     * @param type     咨询类型：1三师咨询，2家庭医生咨询
     * @param when     发病时间
     * @param symptoms 主要症状
     * @param images   图片URL地址，多图以逗号分隔
     * @param voice    语音URL地址
     * @return
     */
    @RequestMapping(value = "add")
    @ResponseBody
    public String add(@RequestParam(required = false) Integer type,
                      @RequestParam(required = false) String when,
                      @RequestParam String symptoms,
                      @RequestParam(required = false) String images,
                      @RequestParam(required = false) String voice,
                      @RequestParam(required = false) Long guidance) {
        try {
            System.out.println("guidance1="+guidance);
            System.out.println("symptoms="+symptoms);
            if (type == null) {
                type = 1;
            }
            if (type != 1 && type != 2) {
                return error(-1, "无效请求！");
            }
            try {
                if (consultTeamService.exist(getRepUID(), type)) {
                    return error(-1, "还有咨询未结束，不允许再次提交咨询！");
                }
            } catch (Exception e) {
                error(e);
                return error(-1, e.getMessage());
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
            }
            // 将临时图片拷贝到正式存储路径下
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
            if (StringUtils.isEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型：1三师咨询，2家庭医生咨询  6.名医咨询
            consult.setType(type);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            // 设置关联咨询
            if (guidance != null && guidance > 0) {
                consult.setGuidance(guidance);
            }

            System.out.println("guidance2="+guidance);
            // 保存到数据库
            int res = consultTeamService.addTeamConsult(consult, getRepUID(),getUID());
            if (res == -1) {
                return error(-1, "家庭签约信息不存在或已过期，无法进行家庭医生咨询！");
            } else if (res == -2) {
                return error(-1, "家庭签约信息不存在或已过期，无法进行三师医生咨询！");
            }

            Doctor doctor = doctorService.findDoctorByCode(consult.getDoctor());
            //创建咨询讨论组
            // JSONObject jo= talkGroupService.createConsultTalkGroup(consult.getDoctor(), doctor.getName(), doctor.getHospital(), doctor.getHospitalName(),
            //        consult.getPatient(), consult.getName(), consult.getConsult());
            // consult.setGroupCode(jo.getString("groupCode"));
            //更新讨论组
            //consultTeamService.save(consult);
            // 添加到统计队列
            if (consult.getType() == 2) {
                DoctorStatisticsTask.getInstance(doctorStatisticsService).put(consult.getDoctor(), 1, 1, 0);
            }

            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.D_CT_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM.您有新的指定咨询.name(), consult.getConsult());
            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
            return write(200, "提交成功", "data", consult);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败！");
        }
    }

    @RequestMapping(value = "intoTopic",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("进入咨询")
    public String intoTopic(@RequestParam(required = true) String consult){
        try{
            int result = consultTeamService.intoTopic(consult,getRepUID(),getUID());
            if(result==-1){
                return error(-1,"该咨询不是进行中");
            }
            JSONObject json = new JSONObject();
            json.put("consult",consult);
            json.put("content","进入咨询");
            BusinessLogs.info(BusinessLogs.BusinessType.consult, getUID(), getRepUID(), json);
            return success("进入成功");
        }catch (Exception e){
            error(e);
            return error(-1,"请求失败");
        }
    }

    /**
     * 名医咨询添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param images     图片URL地址，多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "famousAdd")
    @ResponseBody
    public String famousAdd(
            @RequestParam(required = false) String when,
            String symptoms,
            @RequestParam(required = false) String doctorCode,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String voice) {
        try {
            //判断医生是否是在工作时间
            JSONObject jo = doctorWorkTimeService.isFamousDoctorWorking(doctorCode);
            if (!jo.get("status").equals("1")) {
                return error(-1, jo.get("msg").toString());
            }
            //判断医生是否剩下咨询次数
            int result = doctorWorkTimeService.getDoctorConsultTimesRemain(doctorCode);
            if (result == 0) {
                return error(-1, "没有次数");
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
            }
            // 将临时图片拷贝到正式存储路径下
            if (StringUtils.isNotEmpty(images)) {
                images = CommonUtil.copyTempImage(images);
            }
            if (StringUtils.isEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            //判断是否已经存在还没有关闭的咨询
            if (consultTeamService.isExistConsult(getRepUID(), doctorCode)) {
                return error(-1, "还有咨询未结束，不允许再次提交咨询！");
            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型：1三师咨询，2家庭医生咨询 6.名医咨询
            consult.setType(6);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            JSONObject object  = consultTeamService.famousConsult(consult, getRepUID(), "1",getUID());
            JSONObject resultConsult =  new JSONObject(consult);
            resultConsult.put("session_id",object.getString("session_id"));
            //名医咨询次数减一
            doctorWorkTimeService.setDoctorCurrentConsultTimesRemain(doctorCode);
            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.D_CT_03.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM.您有新的名医咨询.name(), consult.getConsult());
            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
            return write(200, "提交成功", "data", resultConsult);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败！");
        }
    }

    /**
     * 名医列表
     *
     * @return
     */
    @RequestMapping(value = "famousDoctorList")
    @ResponseBody
    public String famousDoctorList(
            @RequestParam(required = false) String name) {
        try {
            JSONArray array = new JSONArray();
            List<Doctor> list = doctorService.famousDoctorList(name);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }

                    // 判断名医是否在工作
                    JSONObject isWorking = doctorWorkTimeService.isDoctorWorking(doctor.getCode());

                    if (isWorking == null || !isWorking.getString("status").equals("1")) {
                        continue;
                    }

                    int num = doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode());

                    if (num < 1) {
                        continue;
                    }

                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生性别
                    json.put("sex", doctor.getSex());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital", doctor.getHospital());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHospitalName());
                    // 科室名称
                    json.put("dept_name", (doctor.getDeptName() == null ||
                            StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", (doctor.getJobName() == null ||
                            StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    // 剩余咨询次数
                    json.put("num", num);
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败！");
        }
    }

    @RequestMapping(value = "status")
    @ResponseBody
    public String status(String consult) {
        try {
            ConsultTeam ct = consultTeamService.findByCode(consult);
            if (ct == null) {
                return error(-1, "获取状态失败！");
            } else {
                return write(200, "获取状态成功！", "data", ct.getStatus());
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "获取状态失败！");
        }
    }

    /**
     * 查询患者三师咨询咨询列表
     *
     * @param status   咨询状态（0未结束，1已结束，-1 已取消）
     * @param pagesize 页数
     * @return 查询结果
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(int status, long id, int pagesize) {
        try {
            Page<ConsultTeam> consults = consultTeamService.findByPatient(getRepUID(), status, id, pagesize);
            JSONArray jsonArray = new JSONArray();
            if (consults != null) {
                for (ConsultTeam consult : consults) {
                    if (consult == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", consult.getId());
                    // 设置咨询标志
                    json.put("code", consult.getConsult());
                    // 设置咨询类型：0公共咨询，1指定医生，2三师咨询
                    json.put("type", consult.getType());
                    // 设置标题
                    json.put("title", consult.getSymptoms());
                    // 设置发病时间
                    json.put("when", consult.getWhen());
                    // 设置患者未读数量
                    json.put("patientRead", consult.getPatientRead());
                    // 设置状态
                    json.put("status", consult.getStatus());
                    // 设置患者评价标识
                    json.put("comment", consult.getComment());
                    // 设置关联指导
                    json.put("guidance", consult.getGuidance());
                    // 设置咨询或回复时间
                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jsonArray.put(json);
                }
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败！");
        }
    }

    /**
     * 患者取消三师咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "cancel")
    @ResponseBody
    public String cancel(String consult) {
        try {
            int row = consultTeamService.cancel(consult);
            if (row > 0) {
                return success("咨询已取消！");
            } else {
                return error(-1, "咨询不能取消！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 修改状态为1的咨询记录为结束
     *
     * @param code 咨询标识
     * @return
     */
    @RequestMapping(value = "finish")
    @ResponseBody
    public String finish(@RequestParam(required = true) String code) {
        try {
            int row = consultTeamService.finishConsult(code, getRepUID(), 1);
            if (row > 0) {
                return success("操作成功！");
            } else {
                return error(-1, "操作失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }


    /**
     * 三师咨询追问接口
     *
     * @param consult 咨询标识
     * @param content 追问内容
     * @param type    追问内容类型：1文字，2图片，3语音
     * @return
     */
    @RequestMapping(value = "append")
    @ResponseBody
    public String append(@RequestParam String consult, @RequestParam String content, @RequestParam int type, @RequestParam(required = false, defaultValue = "0") Integer times) {
        try {
            List<ConsultTeamLog> logs = new ArrayList<ConsultTeamLog>();
            ConsultTeam consultModel = consultTeamService.findByCode(consult);

            if (consultModel == null) {
                return error(-1, "咨询记录不存在！");
            }

            if (consultModel.getEndMsgId() != null) {
                return error(-1, "咨询已结束");
            }

            String[] arr = null;
            if (type == 3) {
                String path = fetchWxVoices();
                JSONObject obj = new JSONObject();
                // 将临时语音拷贝到正式存储路径下
                if (StringUtils.isNotEmpty(path)) {
                    content = CommonUtil.copyTempVoice(path);
                    obj.put("path", content);
                    obj.put("times", times);
                    content = obj.toString();
                }
                ConsultTeamLog log = new ConsultTeamLog();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);
            } else if (type == 2) {
                // 图片消息
                content = fetchWxImages();
                // 将临时图片拷贝到正式存储路径下
                if (StringUtils.isNotEmpty(content)) {
                    content = CommonUtil.copyTempImage(content);
                }
                if (StringUtils.isEmpty(content)) {
                    return error(-1, "图片上传失败！");
                }
                String[] images = content.split(",");
                for (String image : images) {
                    ConsultTeamLog log = new ConsultTeamLog();
                    log.setConsult(consult);
                    log.setContent(image);
                    log.setDel("1");
                    log.setChatType(type);
                    log.setType(type);
                    logs.add(log);
                }
            } else {
                ConsultTeamLog log = new ConsultTeamLog();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(type);
                logs.add(log);

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

            String agent = getUID()==getRepUID()?null:getUID();
            for (ConsultTeamLog log : logs) {
//                String response = ImUtill.sendTopicIM(getUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent());
                String response = ImUtill.sendTopicIM(getRepUID(), patient.getName(), consult, String.valueOf(log.getType()), log.getContent(),agent);
                if (StringUtils.isNotEmpty(response)) {
                    JSONObject resObj = new JSONObject(response);
                    if (resObj.getInt("status") == -1) {
                        return invalidUserException(new RuntimeException(resObj.getString("message")), -1, "追问失败！" + resObj.getString("message"));
                    }
                    failed.add(String.valueOf(resObj.get("data")));
                }
            }
            return write(200, "追问成功！", "data", failed);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "追问失败！");
        }
    }


    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    @RequestMapping(value = "loglist")
    @ResponseBody
    public String loglist(@RequestParam String consult, @RequestParam int page, @RequestParam int pagesize) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在！");
            }
            JSONObject messageObj = ImUtill.getTopicMessage(consultModel.getConsult(), consultModel.getStartMsgId(), consultModel.getEndMsgId(), page, pagesize, getRepUID());

            //过滤续签
            consultTeamService.removeRenewPerson(messageObj,getRepUID());

            return write(200, "查询成功", "list", messageObj);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 网络咨询咨询日志查询
     *
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    @RequestMapping(value = "logs")
    @ResponseBody
    public String logs(@RequestParam String sessionId,@RequestParam(required = false) String startMsgId,@RequestParam(required = false) String endMsgId, @RequestParam int page, @RequestParam int pagesize) {
        try {
            JSONArray messageArray = ImUtill.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getRepUID());
            return write(200, "查询成功", "list", messageArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    @RequestMapping(value = "participants")
    @ResponseBody
    public String participants(@RequestParam String sessionId) {
        try {
            JSONArray participants = ImUtill.getSessions(sessionId);

            //过滤续签
            consultTeamService.removeRenewPerson(participants,getRepUID());

            return write(200, "查询成功", "list", participants);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 查找单个咨询记录
     *
     * @param consult 咨询标识
     * @param logId   记录标识
     * @return
     */
    @RequestMapping(value = "oneLog")
    @ResponseBody
    public String oneLog(@RequestParam String consult, @RequestParam Long logId, @RequestParam int msgType) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);
            if (consultModel == null) {
                return error(-1, "咨询记录不存在！");
            }

            String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                    + "api/v1/chats/message";
            String reG = HttpUtil.sendGet(url, "id=" + logId + "&type=" + msgType);
            JSONObject obj = null;
            if (!org.springframework.util.StringUtils.isEmpty(reG)) {
                obj = new JSONObject(new String(reG.getBytes(), "utf-8"));
            } else {
                return error(-1, "查询失败");
            }

            if (obj == null) {
                return error(-1, "查询失败");
            }

            JSONObject json = new JSONObject();

            json.put("id", obj.getInt("id"));
            if (!obj.getString("from").equals(getRepUID())) {
                Doctor doc = doctorService.findDoctorByCode(obj.getString("from"));
                // 设置回复医生姓名
                json.put("doctorName", doc.getName());
                json.put("photo", doc.getPhoto());
            } else {
                Patient p = patientDao.findByCode(obj.getString("from"));
                // 设置回复医生姓名
                json.put("doctorName", p.getName());
                json.put("photo", p.getPhoto());
            }

            // 设置回复内容
            json.put("content", obj.getString("content"));
            // 设置咨询或回复时间
            json.put("time", DateUtil.dateToStr(new Date(obj.getLong("timestamp")), DateUtil.YYYY_MM_DD_HH_MM_SS));
            // 设置记录类型：1文字，2图片，3语音
            json.put("msgType", obj.getInt("contentType"));
            // 设置类型：0患者问，1医生回复，2患者追问，3患者评价
            if (!obj.getString("from").equals(getRepUID())) {
                json.put("type", 1);
            } else {
                json.put("type", obj.getInt("contentType") == 6 ? 0 : 2);
            }

            // 返回结果
            return write(200, "查询成功", "consult", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 三师咨询评论
     *
     * @param consult 咨询标识
     * @param content 评价内容
     * @param star    星级
     * @return 操作结果
     */
    @RequestMapping(value = "comment")
    @ResponseBody
    public String comment(String consult, String content, int star) {
        try {
            // 保存评价
            JSONArray array = doctorCommentService.consultComment(getRepUID(), consult, content, star, 2);
            // 添加到统计队列
            if (array != null) {
                DoctorStatisticsTask.getInstance(doctorStatisticsService).put(array);
            }
            // 添加评价记录
            ConsultTeamLog log = new ConsultTeamLog();
            log.setConsult(consult);
            log.setContent(content);
            log.setChatType(1);
            log.setDel("1");
            log.setType(3);
            log = consultTeamService.reply(log, getRepUID(), null, log.getType());
            return success("感谢您的评价！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "评价失败！");
        }

    }

    @RequestMapping(value = "getTopic")
    @ResponseBody
    public String getTopic(String consult){
        try{
            return success(ImUtill.getTopic(consult).get("data").toString());
        }catch (Exception e){
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "getConsult")
    @ResponseBody
    public String getConsult(String consult){
        try{
            ConsultTeam consultTeam = consultTeamService.findByConsultCode(consult);
            return write(200, "查询成功", "data", consultTeam);
        }catch (Exception e){
            return error(-1,e.getMessage());
        }
    }
}
