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

import java.util.*;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
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.schedule.WlyyDoctorWorkTime;
import com.yihu.wlyy.entity.doctor.schedule.WlyyDoctorWorkWeek;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.util.*;
import io.swagger.annotations.Api;
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.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 com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.DoctorCommentService;
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.web.WeixinBaseController;

/**
 * 患者端：三师咨询控制类
 *
 * @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(getUID(), 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]));
                    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) {
            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) {
            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) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取未完成咨询
     *
     * @return
     */
    @RequestMapping(value = "/unfinished")
    @ResponseBody
    public String getUnFinishedConsult() {
        try {
            List<ConsultTeam> unfinishedConsult = consultTeamService.getUnfinishedConsult(getUID());
            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(getUID(), doctor);

            if (consults != null && consults.size() > 0) {
                return write(200, "查询成功", "data", consults.get(0).getConsult());
            } else {
                return write(200, "查询成功", "data", "");
            }
        } catch (Exception e) {
            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 {
            if (type == null) {
                type = 1;
            }
            if (type != 1 && type != 2) {
                return error(-1, "无效请求！");
            }
            try {
                if (consultTeamService.exist(getUID(), type)) {
                    return error(-1, "还有咨询未结束，不允许再次提交咨询！");
                }
            } catch (Exception 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);
            }
            // 保存到数据库
            int res = consultTeamService.addTeamConsult(consult, 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());

            return write(200, "提交成功", "data", consult);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -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(getUID(), 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);//设置专科医生
            // 保存到数据库
            consultTeamService.addFamousTeamConsult(consult, getUID(), "1");
            //名医咨询次数减一
            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());
            return write(200, "提交成功", "data", consult);
        } 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(getUID(), 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.finish(code, getUID(), 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) {
        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 == 2) {
                // 图片消息
                if (StringUtils.isEmpty(content)) {
                    String images = request.getParameter("mediaIds");

                    if (!StringUtils.isEmpty(images)) {
                        arr = images.split(",");
                    }

                    content = fetchWxImages();
                } else {
                    arr = content.split(",");
                }

                // 将临时图片拷贝到正式存储路径下
                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(2);
                    logs.add(log);
                }
            } else {
                ConsultTeamLog log = new ConsultTeamLog();
                log.setConsult(consult);
                log.setContent(content);
                log.setDel("1");
                log.setChatType(type);
                log.setType(1);
                logs.add(log);

                arr = new String[]{content};
            }

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

            int i = 0;
            List<String> failed = new ArrayList<>();

            for (ConsultTeamLog log : logs) {
                String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                        + (group != null ? "api/v1/chats/gm" : "api/v1/chats/pm");
                List<NameValuePair> params = new ArrayList<>();
                if (group == null) {
                    params.add(new BasicNameValuePair("from", getUID()));
                    params.add(new BasicNameValuePair("to", consultModel.getDoctor()));
                    params.add(new BasicNameValuePair("content", log.getContent()));
                    params.add(new BasicNameValuePair("contentType", String.valueOf(log.getType())));
                } else {
                    params.add(new BasicNameValuePair("from", getUID()));
                    params.add(new BasicNameValuePair("at", ""));
                    params.add(new BasicNameValuePair("group", group.getString("code")));
                    params.add(new BasicNameValuePair("groupType", "2"));
                    params.add(new BasicNameValuePair("content", log.getContent()));
                    params.add(new BasicNameValuePair("contentType", String.valueOf(log.getType())));
                }

                String response = HttpClientUtil.post(url, params, "UTF-8");

                if (StringUtils.isEmpty(response)) {
                    failed.add(arr[i]);
                }
            }

            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 long id, @RequestParam int pagesize) {
        try {
            ConsultTeam consultModel = consultTeamService.findByCode(consult);

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

            Patient p = patientDao.findByCode(getUID());
            Map<String, Doctor> map = new HashMap<>();

            List<JSONObject> jsonArray = new ArrayList<>();
            JSONObject group = talkGroupService.findConsultTalkGroup(consultModel.getConsult());

            if (group != null) {
                String urlG = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                        + "api/v1/chats/gm";
                String reG = HttpUtil.sendGet(urlG, "user_id=" + getUID() + "&group_id=" + group.getString("code"));
                JSONObject resultG = null;
                if (!org.springframework.util.StringUtils.isEmpty(reG)) {
                    resultG = new JSONObject(new String(reG.getBytes(), "utf-8"));
                }

                if (resultG != null && resultG.getInt("count") > 0) {
                    JSONArray list = resultG.getJSONArray("records");

                    for (int i = 0; i < list.length(); i++) {
                        JSONObject obj = list.getJSONObject(i);

                        if (obj.getInt("contentType") == 5 || obj.getInt("contentType") == 6) {
                            continue;
                        }

                        JSONObject json = new JSONObject();
                        json.put("id", obj.getInt("id"));
                        if (!obj.getString("from").equals(getUID())) {
                            Doctor doc = null;

                            if (map.containsKey(obj.getString("from"))) {
                                doc = map.get(obj.getString("from"));
                            } else {
                                doc = doctorService.findDoctorByCode(obj.getString("from"));
                            }

                            // 设置回复医生姓名
                            json.put("doctorName", doc.getName());
                            json.put("photo", doc.getPhoto());
                        } else {
                            // 设置回复医生姓名
                            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语音 4 文章
                        json.put("msgType", obj.getInt("contentType"));
                        // 设置类型：0患者问，1医生回复，2患者追问，3患者评价
                        if (!obj.getString("from").equals(getUID())) {
                            json.put("type", 1);
                        } else {
                            json.put("type", obj.getInt("contentType") == 6 ? 0 : 2);
                        }
                        jsonArray.add(json);
                    }
                }
            }

            JSONObject result = null;
            String url = SystemConf.getInstance().getSystemProperties().getProperty("im_list_get")
                    + "api/v1/chats/pm";
            String re = HttpUtil.sendGet(url, "closed_interval=true&user_id=" + getUID() + "&peer_id=" + consultModel.getDoctor()
                    + "&message_end_id=" + consultModel.getStartMsgId() + (consultModel.getEndMsgId() != null ? ("&message_start_id=" + consultModel.getEndMsgId()) : ""));

            if (!org.springframework.util.StringUtils.isEmpty(re)) {
                result = new JSONObject(new String(re.getBytes(), "utf-8"));
            }

            if (result != null && result.getInt("count") > 0) {
                JSONArray list = result.getJSONArray("records");

                for (int i = 0; i < list.length(); i++) {
                    JSONObject obj = list.getJSONObject(i);

                    if (obj.getInt("contentType") == 5) {
                        continue;
                    }

                    JSONObject json = new JSONObject();
                    json.put("id", obj.getInt("id"));
                    if (!obj.getString("from").equals(getUID())) {
                        Doctor doc = null;

                        if (map.containsKey(obj.getString("from"))) {
                            doc = map.get(obj.getString("from"));
                        } else {
                            doc = doctorService.findDoctorByCode(obj.getString("from"));
                        }

                        // 设置回复医生姓名
                        json.put("doctorName", doc.getName());
                        json.put("photo", doc.getPhoto());
                    } else {
                        // 设置回复医生姓名
                        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(getUID())) {
                        json.put("type", 1);
                    } else {
                        json.put("type", obj.getInt("contentType") == 6 ? 0 : 2);
                    }
                    jsonArray.add(json);
                }
            }

            jsonArray.sort(new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    if (o1.getString("time").compareTo(o2.getString("time")) > 0) {
                        return -1;
                    } else if (o1.getString("time").compareTo(o2.getString("time")) < 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });

            // 返回结果
            return write(200, "查询成功", "list", new JSONArray(jsonArray));
        } 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(getUID())) {
                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(getUID())) {
                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(getUID(), 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, getUID(), null, log.getType());
            return success("感谢您的评价！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "评价失败！");
        }

    }
}
