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

import com.yihu.wlyy.aop.ObserverRequired;
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.discussion.WlyyTalkGroupMember;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
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 io.swagger.annotations.ApiParam;
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.List;
import java.util.Map;

/**
 * 医生端：三师咨询控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "三师咨询")
public class DoctorConsultController extends WeixinBaseController {

    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private PatientInfoService patientService;
    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private PatientHealthGuidanceService patientHealthGuidanceService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DoctorWorkTimeService doctorWorkTimeService;
    @Autowired
    private ConsultService consultService;
    @Autowired
    private TalkGroupService talkGroupService;
    /**
     * 三师咨询列表查询
     *
     * @param type     咨询类型：0、全部，1、咨询我的，2、公共的， 3、参与过的，4、已结束的  5 名医咨询 全部
     *                 6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医   10查询我咨询的
     * @param id
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public String list(int type,
                       int id,
                       int pagesize,
                       @RequestParam(required = false) String patient,
                       @RequestParam(required = false) String title) {
        try {
            Page<ConsultTeam> list = consultTeamService.findByDoctor(getUID(), type, id, pagesize, patient, title);
            JSONArray jsonArray = new JSONArray();
            if (list != null) {
                for (ConsultTeam consult : list) {
                    if (consult == null) {
                        continue;
                    }

                    if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
                        continue;
                    }

                    JSONObject json = new JSONObject();
                    json.put("id", consult.getId());
                    // 设置咨询标识
                    json.put("consult", consult.getConsult());
                    // 设置患者标识
                    json.put("patient", consult.getPatient());
                    // 设置患者姓名
                    json.put("name", consult.getName());
                    // 设置醫生标识
                    json.put("doctor", consult.getDoctor());
                    Doctor doctor = doctorService.findDoctorByCode(consult.getDoctor());
                    // 设置醫生标识
                    json.put("doctorName", doctor.getName());
                    // 设置医生photo
                    json.put("doctorPhoto", doctor.getPhoto());
                    // 设置医生sex
                    json.put("doctorSex", doctor.getSex());
                    if (consult.getType() == 7) {
                        Doctor d = doctorInfoService.findDoctorByCode(consult.getPatient());
                        // 设置患者头像
                        json.put("photo", d.getPhoto());
                        // 设置患者年龄
                        json.put("age", IdCardUtil.getAgeForIdcard(d.getIdcard()));
                        // 设置性别
                        json.put("sex", d.getSex());
                    } else {
                        Patient p = patientService.findByCode(consult.getPatient());
                        // 设置患者头像
                        json.put("photo", p.getPhoto());
                        // 设置患者年龄
                        json.put("age", IdCardUtil.getAgeForIdcard(p.getIdcard()));
                        // 设置性别
                        json.put("sex", p.getSex());
                    }
                    // 设置咨询标识
                    json.put("title", consult.getSymptoms());
                    // 设置评价内容
                    json.put("comment", consult.getCommentContent());
                    // 设置评价星级
                    json.put("star", consult.getCommentStar());
                    // 设置咨询类型：1三师咨询，2家庭医生咨询 6名医咨询
                    json.put("type", consult.getType());
                    // 设置咨询时间
                    json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    // 咨询状态
                    json.put("status", consult.getStatus());
                    // 未读消息
                    json.put("doctorRead", consult.getDoctorRead());
                    // 设置关联指导
                    json.put("guidance", consult.getGuidance());
                    json.put("startId", consult.getStartMsgId());
                    json.put("endId", consult.getEndMsgId());
                    List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
                    if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
                        for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
                            json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
                            json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
                        }
                    }
                    jsonArray.put(json);
                }
            }
            return write(200, "查询成功", "list", list, jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    @RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "居民咨询列表查询")
    public String listByTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
                             @RequestParam @ApiParam(value = "团队Code") Long teamCode,
                             @RequestParam @ApiParam(value = "第几页") int page,
                             @RequestParam @ApiParam(value = "页大小") int pagesize) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "请输入需查询的居民的团队");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray jsonArray = consultTeamService.findByPatientAndTeam(patient, teamCode, page, pagesize);
            return write(200, "查询成功", "data", jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 获取三师家庭咨询
     *
     * @param status   0未处理或未回复 1已回复 2已结束
     * @param id
     * @param pagesize
     * @param patient
     * @return
     */
    @RequestMapping(value = "/list_by_status")
    @ResponseBody
    public String listByStatus(int status, int id, int pagesize,
                               @RequestParam(required = false) String patient) {
        try {
            Page<ConsultTeam> list = consultTeamService.findConsultByDoctor(getUID(), status, id, pagesize);
            JSONArray jsonArray = new JSONArray();
            for (ConsultTeam consult : list) {
                if (consult == null) {
                    continue;
                }

                if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
                    continue;
                }

                Patient p = patientService.findByCode(consult.getPatient());

                JSONObject json = new JSONObject();
                json.put("id", consult.getId());
                // 设置咨询标识
                json.put("consult", consult.getConsult());
                // 设置患者标识
                json.put("patient", consult.getPatient());
                // 设置患者头像
                json.put("photo", p.getPhoto());
                // 设置咨询标识
                json.put("title", consult.getSymptoms());
                // 设置患者姓名
                json.put("name", consult.getName());
                // 设置患者年龄
                json.put("age", IdCardUtil.getAgeForIdcard(p.getIdcard()));
                // 设置评价内容
                json.put("comment", consult.getCommentContent());
                // 设置评价星级
                json.put("star", consult.getCommentStar());
                // 设置咨询类型：1三师咨询，2家庭医生咨询 6名医咨询
                json.put("type", consult.getType());
                // 设置咨询时间
                json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                // 咨询状态
                json.put("status", consult.getStatus());
                json.put("doctor", consult.getDoctor());
                json.put("doctorName", consult.getDoctorName());
                // 设置性别
                json.put("sex", p.getSex());
                // 未读消息
                json.put("doctorRead", consult.getDoctorRead());
                // 设置关联指导
                json.put("guidance", consult.getGuidance());
                json.put("startId", consult.getStartMsgId());
                json.put("endId", consult.getEndMsgId());
                List<WlyyTalkGroup> wlyyTalkGroups = talkGroupService.findAllConsultTalkGroup(consult.getConsult());
                if (wlyyTalkGroups != null && wlyyTalkGroups.size() > 0) {
                    for (WlyyTalkGroup wlyyTalkGroup : wlyyTalkGroups) {
                        json.put("group" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCode());
                        json.put("groupName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getName());
                    }
                }
                jsonArray.put(json);
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    @RequestMapping(value = "/hasTnvite")
    @ResponseBody
    public String hasTnvite(String groupCode) {
        try {
            JSONObject jo = new JSONObject();
            List<WlyyTalkGroupMember> wlyyTalkGroupMembers = talkGroupService.findTalkGroupMembers(groupCode);
            if (wlyyTalkGroupMembers.size() > 2) {
                jo.put("hasTnvite", 1);//有邀请
            } else {
                jo.put("hasTnvite", 0);//没邀请
            }
            return write(200, "查询成功", "list", jo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

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

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

                    if (isWorking == null || !isWorking.getString("status").equals("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("level", doctor.getLevel());
                    // 所在医院名称
                    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());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败！");
        }
    }

    /**
     * 获取咨询全科医生签约量
     *
     * @param consults
     * @return
     */
    @RequestMapping(value = "/consult_sign")
    @ResponseBody
    public String consultSign(String consults) {
        try {
            List<Map<String, Object>> list = consultTeamService.getConsultSign(consults.split(","));
            return write(200, "查询成功", "data", new JSONArray(list));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 结束三师咨询接口
     *
     * @param consult 三师咨询标识
     * @return
     */
    @RequestMapping(value = "finish")
    @ResponseBody
    @ObserverRequired
    public String finish(String consult) {
        try {
            int flag = consultTeamService.finish(consult, getUID(), 2);
            if (flag > 0) {
                return success("咨询已关闭");
            } else {
                return error(-1, "关闭失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "关闭失败！");
        }
    }

    /**
     * 设置消息已读
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/readed")
    @ResponseBody
    @ObserverRequired
    public String readMessage(String consult) {
        try {
            int result = consultTeamService.readMessage(consult);
            return write(200, "设置成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "设置失败");
        }
    }

    /**
     * 医生咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param patient  患者标识
     * @param pagesize 每页显示数，默认为10
     * @return
     */
    @RequestMapping(value = "record")
    @ResponseBody
    public String record(String consult, String patient, long id, int pagesize) {
        try {
            Patient patientTemp = null;
            if (id <= 0) {
                // 只有第一页才会查询患者信息
                patientTemp = patientService.findByCode(patient);
                // 更新医生未读数量为0
                consultTeamService.clearDoctorRead(consult);
            }
            // 查询日志列表
            JSONArray jsonArray = new JSONArray();
            Page<ConsultTeamLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
            if (list != null) {
                for (ConsultTeamLog log : list) {
                    if (consult == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", log.getId());
                    // 设置回复内容
                    json.put("content", log.getContent());
                    // 设置回复医生姓名
                    json.put("doctorName", log.getDoctorName());
                    // 设置回复人头像
                    json.put("photo", log.getPhoto());
                    // 设置日志类型
                    json.put("type", log.getType());
                    // 设置记录类型
                    json.put("chatType", log.getChatType());
                    // 设置咨询或回复时间
                    json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jsonArray.put(json);
                }
            }
            // 设置返回结果
            JSONObject values = new JSONObject();
            if (patientTemp != null) {
                JSONObject patientJson = new JSONObject();
                // 设置患者标识
                patientJson.put("patient", patientTemp.getCode());
                // 设置姓名
                patientJson.put("name", patientTemp.getName());
                // 设置头像
                patientJson.put("photo", patientTemp.getPhoto());
                values.put("patient", patientJson);
            }
            values.put("list", jsonArray);
            // 返回结果
            return write(200, "查询成功", "data", values);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 医生回复网络咨询
     *
     * @param patient 患者标识
     * @param consult 咨询标识
     * @param content 回复内容
     * @param type    回复类型，1文字，2图片，3语音
     * @return
     */
    @RequestMapping(value = "reply")
    @ResponseBody
    public String reply(String patient, String consult, String content, int type) {
        try {
            // 查询医生基本信息
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (doctor == null) {
                return error(-1, "回复失败！");
            } else {
                ConsultTeamLog log = new ConsultTeamLog();
                // 设置咨询标识
                log.setConsult(consult);
                // 拷贝图片
                if (StringUtils.isNotEmpty(content)) {
                    if (type == 3) {
                        // 语音
                        content = CommonUtil.copyTempVoice(content);
                    } else if (type == 2) {
                        // 图片
                        content = CommonUtil.copyTempImage(content);
                    }
                }
                // 设置回复内容
                log.setContent(content);
                log.setDel("1");
                // 设置回复医生标识
                log.setDoctor(doctor.getCode());
                // 设置医生姓名
                log.setDoctorName(doctor.getName());
                // 设置医生头像
                log.setPhoto(doctor.getPhoto());
                // 设置咨询类型为医生回复
                log.setType(1);
                // 设置记录类型
                log.setChatType(type);
                // 保存医生回复内容
                log = consultTeamService.reply(log, patient, getUID(), log.getType());
                if (log == null) {
                    return error(-1, "回复失败！");
                } else {
                    // 推送消息给患者
                    // PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.P_CT_01.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.三师咨询.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.医生回复了您.name(), consult);
                    // 推送消息给微信端
                    ConsultTeam ct = consultTeamService.findByCode(consult);
                    Patient p = patientService.findByCode(patient);
                    if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
                        JSONObject json = new JSONObject();
                        json.put("first", p.getName() + "，您好！\n您的健康咨询有新的回复");
                        json.put("toUser", p.getCode());
                        String symp = ct.getSymptoms();
                        json.put("consultcontent", StringUtils.isNotEmpty(symp) && symp.length() > 50 ? (symp.substring(0, 50) + "...")  : content);
                        String replycontent = content.length() > 50 ? content.substring(0, 50) + "..." : content;
                        if (type == 2) {
                            replycontent = "[图片]";
                        } else if (type == 3) {
                            replycontent = "[语音]";
                        }
                        json.put("consult", consult);
                        json.put("replycontent", replycontent);
                        json.put("doctorName", doctor.getName());
                        json.put("remark", "医生已为您提供问诊方案");
                        // PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
                    }
                    if (type == 2) {
                        return write(200, "回复成功！", "data", content);
                    }
                    return success("回复成功！");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "回复失败！");
        }
    }

    /**
     * 查询医生的总咨询次数和今日咨询次数
     *
     * @param doctorCode
     * @return
     */
    @RequestMapping(value = "getConsultCount")
    @ResponseBody
    public String getAllCount(@RequestParam(required = true) String doctorCode) {
        try {
            JSONObject json = new JSONObject();
            Map<String, Long> counts = consultTeamService.getAllCount(doctorCode);

            json.put("all", counts.get("all"));
            json.put("today", counts.get("today"));
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "回复失败！");
        }
    }

    /**
     * 查询患者的服务数目
     *
     * @return
     */
    @RequestMapping(value = "getPatientServicNum")
    @ResponseBody
    public String getPatientServicNum(String patientCode) {
        try {
            JSONObject json = new JSONObject();
            //统计咨询数目
            Integer allSize1 = consultTeamService.findByDoctorSize(patientCode, getUID());
            //查询健康指导
            Integer allSize2 = patientHealthGuidanceService.findGuidanceByPatient(patientCode, getUID());
            json.put("consult", allSize1);
            json.put("guide", allSize2);
            //json.put("today", counts.get("today"));
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "回复失败！");
        }
    }

    /**
     * 根据医生code和和患者code判断是否有存在进行中的咨询
     *
     * @param patientCode 多个患者 逗号分隔
     * @param doctor
     * @return 只返回存在咨询的患者的code
     */
    @RequestMapping(value = "getConsultByPatientAndDoctor")
    @ResponseBody
    public String getConsultByPatientAndDoctor(String patientCode, String doctor) {
        try {
            JSONArray json = new JSONArray();
            String[] patients = patientCode.split(",");
            for (int i = 0; i < patients.length; i++) {
                ConsultTeam consultTeam = consultTeamService.getConsultByPatientAndDoctor(patients[i], doctor);
                if (consultTeam != null) {
                    json.put(patients[i]);
                }
            }
            return json.toString();
        } 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
    @ObserverRequired
    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());
            }
            if (StringUtils.isEmpty(images)) {
                images = fetchWxImages();
                // 将临时图片拷贝到正式存储路径下
                if (StringUtils.isNotEmpty(images)) {
                    images = CommonUtil.copyTempImage(images);
                }
            }

            if (StringUtils.isNotEmpty(voice)) {
                voice = fetchWxVoices();
            }
            if (StringUtils.isNotEmpty(voice)) {
                voice = CommonUtil.copyTempVoice(voice);
            }
            //判断是否已经存在还没有关闭的名医咨询
//            if(consultTeamService.isExistFamousConsult(getUID())){
//                return error(-1, "已经存在名医咨询！");
//            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型：1三师咨询，2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询
            consult.setType(7);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);
            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            JSONObject result = consultTeamService.famousConsult(consult, getUID(), "2",null);
            // 推送消息给医生
            PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
            if (StringUtils.isNotEmpty(images)) {
                String[] arr = images.split(",");
                for (String img : arr) {
                    PushMsgTask.getInstance().put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
                }
            }
            return write(200,"创建成功！","data",result);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败！");
        }
    }

    /**
     * 查询与某个医生是否存在未结束的咨询
     *
     * @param doctor 医生
     * @return
     */
    @RequestMapping(value = "/is_consult_unfinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isExistsUnfinishedConsult(@RequestParam(required = false) String patient,
                                            @RequestParam(required = true) String doctor) {
        try {
            JSONObject result = new JSONObject();
            List<ConsultTeam> consults = consultTeamService.getUnfinishedConsult(StringUtils.isEmpty(patient) ? getUID() : patient, 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 consult 咨询code
     * @return
     */
    @RequestMapping(value = "/consultTeam", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String consult(@RequestParam(required = false) String consult) {
        try {
            ConsultTeam consultTeam = consultTeamService.findByCode(consult);
            return write(200, "查询成功", "data", consultTeam);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }


    /**
     * 三师咨询转接接口
     *
     * @param consult 图咨询标识
     * @param doctor  转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
     * @param type    转接对象类型，1三师团队，2指定医生，3工作组团队
     * @return
     */
    @RequestMapping(value = "transfer")
    @ResponseBody
    @ObserverRequired
    public String transfer(
            String consult,
            String doctor,
            @RequestParam(required = false) int type) {
        try {
            consultTeamService.transfers(getUID(), doctor, consult);
            return success("转接成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "转接失败！");
        }
    }

    /**
     * 根据咨询code获取咨询的log
     *
     * @param consultCode
     * @return
     */
    @RequestMapping(value = "getConsultLog")
    @ResponseBody
    public String getConsultLog(
            String consultCode) {
        try {
            List<ConsultTeamLog> consultTeamLogs = consultTeamService.getConsultLog(consultCode);
            JSONArray ja = new JSONArray();
            for (ConsultTeamLog log : consultTeamLogs) {
                JSONObject json = new JSONObject();
                json.put("id", log.getId());
                // 设置回复内容
                json.put("content", log.getContent());
                // 设置回复医生姓名
                json.put("doctorName", log.getDoctorName());
                // 设置回复人头像
                json.put("photo", log.getPhoto());
                // 设置日志类型
                json.put("type", log.getType());
                // 设置记录类型
                json.put("chatType", log.getChatType());
                // 设置咨询或回复时间
                json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                ja.put(json);
            }
            return write(200, "查询成功", "data", ja);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 医生求助添加接口
     *
     * @param when       发病时间
     * @param symptoms   主要症状
     * @param groupCode  从哪个讨论组发起的求助
     * @param images     图片URL地址，多图以逗号分隔
     * @param voice      语音URL地址
     * @param doctorCode 名医的code
     * @return
     */
    @RequestMapping(value = "forHelpAdd")
    @ResponseBody
    @ObserverRequired
    public String forHelpAdd(
            @RequestParam(required = false) String when,
            String symptoms,
            @RequestParam(required = false) String oldConsultCode,
            @RequestParam(required = false) String groupCode,
            @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());
            }*/
            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.isExistFamousConsult(getUID())){
//                return error(-1, "已经存在名医咨询！");
//            }
            ConsultTeam consult = new ConsultTeam();
            // 设置咨询类型：1三师咨询，2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
            consult.setType(10);
            // 设置来源（从哪个讨论组发起的求助）
            consult.setTeam(groupCode);
            // 设置发病时间
            consult.setWhen(when);
            // 设置主要症状
            consult.setSymptoms(symptoms);
            // 设置咨询图片URL
            consult.setImages(images);
            // 设置咨询语音URL
            consult.setVoice(voice);

            consult.setDoctor(doctorCode);//设置专科医生
            // 保存到数据库
            if(consultTeamService.isCommonTeam( doctorCode, getUID() ))
                consultTeamService.sendForHelpMsg( consult, getUID(), oldConsultCode );
            else
                consultTeamService.addForHelpTeamConsult( consult, getUID(), oldConsultCode );

            // 推送消息给医生
            /*PushMsgTask.getInstance().put(consult.getDoctor(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.D_CT_04.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), consult.getConsult());
            if (StringUtils.isNotEmpty(images)) {
                String[] arr = images.split(",");
                for (String img : arr) {
                    PushMsgTask.getInstance().put(consult.getDoctor(), "2", MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.名医咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_FAMOUS_CONSULT_TEAM_DOCTOR.您有新的名医咨询.name(), img);
                }
            }*/
            return success("提交成功");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "提交失败！");
        }
    }

    @RequestMapping(value = "hasUnfinished")
    @ResponseBody
    public String hasUnfinished(String doctorCode) {
        try {
            String curDoc =  getUID();
            JSONObject json = new JSONObject();
            if(consultTeamService.isCommonTeam(doctorCode, curDoc)){
                json.put("isCommonTeam", 1);
                return write(200, "查询成功", "data", json);
            }
            List<ConsultTeam>  ls = consultTeamService.hasUnfinished(doctorCode, curDoc);
            if(ls!=null && ls.size() > 0){
                ConsultTeam ct =  ls.get(0);
                json.put("consult", ct.getConsult());
                //是否是医生求助医生
                if(ct.getType()==10){
                    //取出原有咨询求助返回原咨询的患者
                    ConsultTeam consultTeam = consultTeamService.findByConsultCode(ct.getTeam());
                    Patient patient = patientService.findByCode(consultTeam.getPatient());
                    json.put("zxGroupCode",consultTeam.getPatient()+"_"+consultTeam.getTeam()+"_"+consultTeam.getType());
                    json.put("from", ct.getPatient());
                    json.put("patient_name", patient.getName());
                }
            }
            return write(200, "查询成功", "data", json);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败！");
        }
    }

    /**
     * 该咨询求助过的医生列表
     * @param consult 关联的上一个咨询
     * @return
     */
    @RequestMapping(value = "forHelpDocs")
    @ResponseBody
    public String forHelpDocs(String consult) {
        try {
            List<String> ls = consultTeamService.findByTeam(consult);
            JSONObject json = new JSONObject();
            if(ls!=null){
                for(String o : ls){
                    json.put(o, 1);
                }
            }
            return write(200, "查询成功", "data", json);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败！");
        }
    }

    @RequestMapping(value = "/isConsultFinished", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String isConsultFinished(@RequestParam String consult) {
        try {
            ConsultTeam ct = consultTeamService.findByConsultCode(consult);
            return write(200, "查询咨询状态成功", "data", ct.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询咨询状态失败");
        }
    }

    @RequestMapping(value = "seekHelp")
    @ResponseBody
    @ObserverRequired
    public String seekHelp(
            @RequestParam(required = true) String symptoms,
            @RequestParam(required = false) String oldConsultCode,
            @RequestParam(required = false) String doctorCode,
            @RequestParam(required = false) String images,
            @RequestParam(required = true) Integer isSend){
        try {
                if (StringUtils.isEmpty(images)) {
                    images = fetchWxImages();
                    // 将临时图片拷贝到正式存储路径下
                    if (StringUtils.isNotEmpty(images)) {
                        images = CommonUtil.copyTempImage(images);
                    }
                }
                ConsultTeam consult = new ConsultTeam();
                // 设置咨询类型：1三师咨询，2家庭医生咨询 6.患者发起名医咨询 7医生发起的名医咨询 10医生发起的求助
                consult.setType(10);
                // 设置主要症状
                consult.setSymptoms(symptoms);
                // 设置咨询图片URL
                consult.setImages(images);

                consult.setDoctor(doctorCode);//设置专科医生
                // 保存到数据库
                if(consultTeamService.isCommonTeam(doctorCode, getUID())){
                    consultTeamService.addSeekHelpTeam(consult, getUID(), oldConsultCode,isSend);
                }else{
                    consultTeamService.addSeekHelpOtherTeam(consult, getUID(), oldConsultCode,isSend);
                }
                return success("提交成功");
            } catch (Exception ex) {
                error(ex);
                return invalidUserException(ex, -1, "提交失败！");
            }
    }


    /**
     * 结束咨询接口
     * @param consult 咨询标识
     * @return
     */
    @RequestMapping(value = "finish_consult")
    @ResponseBody
    @ObserverRequired
    public String finishConsult(@RequestParam(required = false) String consult) {
        try {
            int flag = consultTeamService.finishConsult(consult, getUID(), 2);
            //int flag = consultTeamService.finishConsult(consult, "test00000000005", 2);
            if (flag > 0) {
                return success("咨询已关闭");
            } else if(flag == -1) {
                return error(-1, "该咨询已经关闭，不需重复关闭！");
            } else {
                return error(-1, "关闭失败！");
            }
        } 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, getUID());
            return write(200, "查询成功", "list", messageObj);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }
}
