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

import java.util.*;

import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.consult.ConsultTeam;
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.repository.doctor.DoctorDao;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.DateUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
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.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.BaseController;

@Controller
@RequestMapping(value = "/doctor/talkgroup", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-讨论组")
public class DoctorDiscussionGroupController extends BaseController {
    // 医生服务类
    @Autowired
    private DoctorService doctorService;
    @Autowired
    // 讨论组服务类
    private TalkGroupService talkGroupService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private ConsultTeamService consultTeamService;


    /**
     * 医生创建讨论组
     *
     * @param name           讨论组名称
     * @param type           讨论组类型 1咨询 2求组
     * @param talkDoctor     讨论组医生
     * @param talkDoctorName 讨论组医生名称
     * @param doctorType     成员医生类型
     * @param patient        病人标识
     * @param patientName    病人姓名
     * @param patientInclude 病人是否加入讨论组 不传默认不加入患者
     * @return
     */
    @RequestMapping(value = "/create", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String createTalkGroup(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) int type,
            @RequestParam(required = true) String talkDoctor,
            @RequestParam(required = true) String talkDoctorName,
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = false) String consult,
            @RequestParam(required = false) String patient,
            @RequestParam(required = false) String patientName,
            @RequestParam(required = false) String patientInclude) {
        try {
            Doctor doctor = doctorService.findDoctorByCode(getUID());
            List<WlyyTalkGroupMember> members = new ArrayList<WlyyTalkGroupMember>();

            if (doctor != null) {
                //讨论组建立
                WlyyTalkGroup talkGroup = new WlyyTalkGroup();

                if (StringUtils.isEmpty(name)) {
                    return error(-1, "请输入讨论组名称");
                }
                if (StringUtils.isEmpty(talkDoctor)) {
                    return error(-1, "请输入讨论组成员医生");
                }
                if (StringUtils.isEmpty(talkDoctorName)) {
                    return error(-1, "请输入讨论组成员医生姓名");
                }
                // 讨论组针对某一病人时
                if (type == 1) {
                    if (StringUtils.isEmpty(patient)) {
                        return error(-1, "请输入患者标识");
                    }
                    if (StringUtils.isEmpty(patientName)) {
                        return error(-1, "请输入患者姓名");
                    }
                    if (StringUtils.isEmpty(patientInclude)) {
                        return error(-1, "请输入患者是否加入讨论组");
                    }
                }

                talkGroup.setCode(talkGroupService.getCode());
                talkGroup.setName(name);
                talkGroup.setType(type);
                talkGroup.setCreator(doctor.getCode());
                talkGroup.setCreatorName(doctor.getName());
                talkGroup.setHospitalCode(doctor.getHospital());
                talkGroup.setHospitalName(doctor.getHospitalName());
                if (StringUtils.isNotEmpty(consult)) {
                    if (type == 1) {
                        JSONObject consultTalkQk = talkGroupService.findConsultTalkGroup(consult);
                        if (consultTalkQk != null) {
                            return error(-1, "该咨询已求助过全科医生");
                        }
                    } else if (type == 2) {
                        JSONObject consultTalkQz = talkGroupService.getConsultGroup(consult);
                        if (consultTalkQz != null) {
                            return error(-1, "该咨询已有求助讨论组");
                        }
                    }
                    talkGroup.setConsultCode(consult);
                }
                talkGroup.setPatient(patient);
                talkGroup.setPatientName(patientName);
                talkGroup.setCzrq(new Date());

                //病人加入讨论组
                if (!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")) {
                    WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();

                    patientMember.setMemberCode(patient);
                    patientMember.setMemberName(patientName);
                    patientMember.setGroupCode(talkGroup.getCode());
                    patientMember.setGroupName(name);
                    patientMember.setType(4);
                    patientMember.setStatus(1);
                    patientMember.setCzrq(new Date());

                    members.add(patientMember);
                }

                //当前医生加入讨论组
                WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();

                doctorMember.setMemberCode(doctor.getCode());
                doctorMember.setMemberName(doctor.getName());
                doctorMember.setGroupCode(talkGroup.getCode());
                doctorMember.setGroupName(name);
                doctorMember.setType(doctor.getLevel());
                doctorMember.setStatus(1);
                doctorMember.setCzrq(new Date());
                members.add(doctorMember);

                //指定的讨论组另一医生成员
                WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();

                doctorTalkMember.setMemberCode(talkDoctor);
                doctorTalkMember.setMemberName(talkDoctorName);
                doctorTalkMember.setGroupCode(talkGroup.getCode());
                doctorTalkMember.setGroupName(name);
                doctorTalkMember.setType(doctorType);
                doctorTalkMember.setStatus(1);
                doctorTalkMember.setCzrq(new Date());
                members.add(doctorTalkMember);

                talkGroupService.saveTalkGroup(talkGroup, members);

                if (type == 1) {
                    consultTeamService.transfer(getUID(), talkDoctor, consult);
                }

                JSONObject jsonObject = new JSONObject(talkGroup);
                JSONArray membersJson = new JSONArray();

                for (WlyyTalkGroupMember member : members) {
                    JSONObject memberJson = new JSONObject(member);
                    if (member.getType() == 4) {
                        Patient p = patientService.findByCode(member.getMemberCode());

                        if (p != null) {
                            memberJson.put("photo", p.getPhoto());
                            memberJson.put("sex", p.getSex());
                        }
                    } else {
                        Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

                        if (d != null) {
                            memberJson.put("photo", d.getPhoto());
                            memberJson.put("sex", d.getSex());
                        }
                    }
                    membersJson.put(memberJson);
                }

                jsonObject.put("members", membersJson);

                return write(200, "创建讨论组成功!", "data", jsonObject);
            } else {
                return error(-1, "创建讨论组失败!");
            }

        } catch (Exception e) {
            return error(-1, "创建讨论组失败!");
        }
    }

    /**
     * 创建讨论组
     *
     * @param name           讨论组名称
     * @param type           讨论组类型
     * @param members        讨论组成员 [{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
     * @param consult        咨询code
     * @param patient        患者
     * @param patientName    患者姓名
     * @param patientInclude 患者是否加入
     * @return
     */
    @RequestMapping(value = "/create/members", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String createTalkGroupMany(@RequestParam(required = true) String name,
                                      @RequestParam(required = true) int type,
                                      @RequestParam(required = true) String members,
                                      @RequestParam(required = false) String consult,
                                      @RequestParam(required = false) String patient,
                                      @RequestParam(required = false) String patientName,
                                      @RequestParam(required = false) String patientInclude) {
        try {
            Doctor doctor = doctorService.findDoctorByCode(getUID());
            List<WlyyTalkGroupMember> talkMembers = new ArrayList<WlyyTalkGroupMember>();

            if (doctor != null) {
                //讨论组建立
                WlyyTalkGroup talkGroup = new WlyyTalkGroup();

                if (StringUtils.isEmpty(name)) {
                    return error(-1, "请输入讨论组名称");
                }
                if (StringUtils.isEmpty(members)) {
                    return error(-1, "讨论组成员不能为空");
                }
                // 讨论组针对某一病人时
                if (type == 1) {
                    if (StringUtils.isEmpty(patient)) {
                        return error(-1, "请输入患者标识");
                    }
                    if (StringUtils.isEmpty(patientName)) {
                        return error(-1, "请输入患者姓名");
                    }
                    if (StringUtils.isEmpty(patientInclude)) {
                        return error(-1, "请输入患者是否加入讨论组");
                    }
                }

                talkGroup.setCode(talkGroupService.getCode());
                talkGroup.setName(name);
                talkGroup.setType(type);
                talkGroup.setCreator(doctor.getCode());
                talkGroup.setCreatorName(doctor.getName());
                talkGroup.setHospitalCode(doctor.getHospital());
                talkGroup.setHospitalName(doctor.getHospitalName());
                if (StringUtils.isNotEmpty(consult)) {
                    if (type == 1) {
                        JSONObject consultTalkQk = talkGroupService.findConsultTalkGroup(consult);
                        if (consultTalkQk != null) {
                            return error(-1, "该咨询已求助过全科医生");
                        }
                    } else if (type == 2) {
                        JSONObject consultTalkQz = talkGroupService.getConsultGroup(consult);
                        if (consultTalkQz != null) {
                            return error(-1, "该咨询已有求助讨论组");
                        }
                    }
                    talkGroup.setConsultCode(consult);
                }
                talkGroup.setPatient(patient);
                talkGroup.setPatientName(patientName);
                talkGroup.setCzrq(new Date());

                //病人加入讨论组
                if (!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")) {
                    WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();

                    patientMember.setMemberCode(patient);
                    patientMember.setMemberName(patientName);
                    patientMember.setGroupCode(talkGroup.getCode());
                    patientMember.setGroupName(name);
                    patientMember.setType(4);
                    patientMember.setStatus(1);
                    patientMember.setCzrq(new Date());

                    talkMembers.add(patientMember);
                }

                //当前医生加入讨论组
                WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();

                doctorMember.setMemberCode(doctor.getCode());
                doctorMember.setMemberName(doctor.getName());
                doctorMember.setGroupCode(talkGroup.getCode());
                doctorMember.setGroupName(name);
                doctorMember.setType(doctor.getLevel());
                doctorMember.setStatus(1);
                doctorMember.setCzrq(new Date());
                talkMembers.add(doctorMember);

                JSONArray membersJArray = new JSONArray(members);

                if (membersJArray != null) {
                    for (int i = 0; i < membersJArray.length(); i++) {
                        JSONObject object = membersJArray.getJSONObject(i);
                        //指定的讨论组另一医生成员
                        WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();

                        doctorTalkMember.setMemberCode(object.getString("doctor"));
                        doctorTalkMember.setMemberName(object.getString("doctorName"));
                        doctorTalkMember.setGroupCode(talkGroup.getCode());
                        doctorTalkMember.setGroupName(name);
                        doctorTalkMember.setType(object.getInt("doctorType"));
                        doctorTalkMember.setStatus(1);
                        doctorTalkMember.setCzrq(new Date());

                        talkMembers.add(doctorTalkMember);

                        if (type == 1 && object.getInt("doctorType") == 2) {
                            if (type == 1) {
                                consultTeamService.transfer(getUID(), object.getString("doctor"), consult);
                            }
                        }
                    }
                }

                talkGroupService.saveTalkGroup(talkGroup, talkMembers);

                JSONObject jsonObject = new JSONObject(talkGroup);
                JSONArray membersJson = new JSONArray();

                for (WlyyTalkGroupMember member : talkMembers) {
                    JSONObject memberJson = new JSONObject(member);
                    if (member.getType() == 4) {
                        Patient p = patientService.findByCode(member.getMemberCode());

                        if (p != null) {
                            memberJson.put("photo", p.getPhoto());
                            memberJson.put("sex", p.getSex());
                        }
                    } else {
                        Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

                        if (d != null) {
                            memberJson.put("photo", d.getPhoto());
                            memberJson.put("sex", d.getSex());
                        }
                    }
                    membersJson.put(memberJson);
                }

                jsonObject.put("members", membersJson);

                return write(200, "创建讨论组成功!", "data", jsonObject);
            } else {
                return error(-1, "创建讨论组失败!");
            }
        } catch (Exception e) {
            return error(-1, "创建讨论组失败");
        }
    }

    /**
     * 获取查询对应的求助
     *
     * @param cosnult
     * @return
     */
    @RequestMapping(value = "/group/consult", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getConsultTalkGroup(@RequestParam(required = true) String cosnult) {
        try {
            JSONObject group = talkGroupService.getConsultGroup(cosnult);

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

    /**
     * 获取查询对应的求助
     *
     * @param cosnult
     * @return
     */
    @RequestMapping(value = "/group/patient_consult", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getPatientConsultTalkGroup(@RequestParam(required = true) String cosnult) {
        try {
            JSONObject group = talkGroupService.findConsultTalkGroup(cosnult);

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

    /**
     * 获取常用医生
     *
     * @return
     */
    @RequestMapping(value = "/common_doctors", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getCommonDoctors() {
        try {
            JSONArray result = talkGroupService.getCommonDoctors(getUID());
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 添加讨论组成员
     *
     * @param groupCode  讨论组标识
     * @param groupName  讨论组名称
     * @param doctor     添加医生
     * @param doctorName 添加医生姓名
     * @param doctorType 医生类型
     * @return
     */
    @RequestMapping(value = "addmember", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String addTalkMember(
            @RequestParam(required = true) String groupCode,
            @RequestParam(required = false) String groupName,
            @RequestParam(required = true) String doctor,
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false, defaultValue = "0") int doctorType) {
        try {
            WlyyTalkGroup group = talkGroupService.findTalkGroup(groupCode);
            if (group == null) {
                return error(-1, "讨论组不存在");
            }
            if (talkGroupService.isMemberExists(groupCode, groupName)) {
                return error(-2, "成员已在该讨论组");
            }
            WlyyTalkGroupMember member = new WlyyTalkGroupMember();
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc == null) {
                return error(-1, "添加的医生的信息查询失败");
            }

            member.setGroupCode(groupCode);
            member.setGroupName(group.getName());
            member.setMemberCode(doctor);
            member.setMemberName(doc.getName());
            member.setStatus(1);
            member.setCzrq(new Date());
            member.setType(doc.getLevel());

            talkGroupService.saveTalkMember(member);

            JSONObject memberJson = new JSONObject(member);

            if (member.getType() == 4) {
                Patient p = patientService.findByCode(member.getMemberCode());

                if (p != null) {
                    memberJson.put("photo", p.getPhoto());
                    memberJson.put("sex", p.getSex());
                }
            } else {
                Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

                if (d != null) {
                    memberJson.put("photo", d.getPhoto());
                    memberJson.put("sex", d.getSex());
                }
            }

            return write(200, "添加讨论组成员成功!", "data", memberJson);
        } catch (Exception e) {
            return error(-1, "添加讨论组成员失败!");
        }
    }


    /**
     * 添加成员
     *
     * @param groupCode 分组code
     * @param members   讨论组成员[{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
     * @return
     */
    @RequestMapping(value = "/addmembers", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String addMembers(@RequestParam(required = true) String groupCode,
                             @RequestParam(required = false) String groupName,
                             @RequestParam(required = true) String members) {
        try {
            List<WlyyTalkGroupMember> talkMembers = new ArrayList<>();
            JSONArray membersJArray = new JSONArray(members);
            WlyyTalkGroup talkGroup = talkGroupService.findTalkGroup(groupCode);

            if (talkGroup == null) {
                throw new Exception("讨论组不存在");
            }

            if (membersJArray != null) {
                for (int i = 0; i < membersJArray.length(); i++) {
                    JSONObject object = membersJArray.getJSONObject(i);
                    if (talkGroupService.isMemberExists(groupCode, object.getString("doctor"))) {
                        return error(-2, "添加失败，有成员已在该讨论组");
                    }
                    //指定的讨论组另一医生成员
                    WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();

                    doctorTalkMember.setMemberCode(object.getString("doctor"));
                    doctorTalkMember.setMemberName(object.getString("doctorName"));
                    doctorTalkMember.setGroupCode(groupCode);
                    doctorTalkMember.setGroupName(talkGroup.getName());
                    doctorTalkMember.setType(object.getInt("doctorType"));
                    doctorTalkMember.setStatus(1);
                    doctorTalkMember.setCzrq(new Date());

                    talkMembers.add(doctorTalkMember);
                }
            }

            talkGroupService.saveMembers(talkMembers);

            JSONObject jsonObject = new JSONObject(talkGroup);
            JSONArray membersJson = new JSONArray();

            for (WlyyTalkGroupMember member : talkMembers) {
                JSONObject memberJson = new JSONObject(member);
                if (member.getType() == 4) {
                    Patient p = patientService.findByCode(member.getMemberCode());

                    if (p != null) {
                        memberJson.put("photo", p.getPhoto());
                        memberJson.put("sex", p.getSex());
                    }
                } else {
                    Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

                    if (d != null) {
                        memberJson.put("photo", d.getPhoto());
                        memberJson.put("sex", d.getSex());
                    }
                }
                membersJson.put(memberJson);
            }

            jsonObject.put("members", membersJson);

            return write(200, "添加成员成功");
        } catch (Exception e) {
            return error(-1, "添加成员失败!");
        }
    }


    /**
     * 移除讨论组成员
     *
     * @param groupCode  讨论组标识
     * @param memberCode 讨论组成员标识
     * @return
     */
    @RequestMapping(value = "removemember", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String removeTalkMember(
            @RequestParam(required = true) String groupCode,
            @RequestParam(required = true) String memberCode) {
        try {
            talkGroupService.deleteTalkMember(groupCode, memberCode);
            return write(200, "移除成员成功!");
        } catch (Exception e) {
            return error(-1, "移除讨论组成员失败!");
        }
    }

    /**
     * 移除成员
     *
     * @param groupCode
     * @param members
     * @return
     */
    @RequestMapping(value = "/removemembers", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String removeMembers(String groupCode, String members) {
        try {
            String[] memberArray = members.split(",");
            for (String member : memberArray) {
                talkGroupService.deleteTalkMember(groupCode, member);
            }
            return write(200, "移除成员成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "移除成员失败!");
        }
    }

    /**
     * 获取医生讨论组
     *
     * @return
     */
    @RequestMapping(value = "mytalkgroups", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroup(
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false) String groupType) {
        try {
            JSONArray jsonArray = new JSONArray();
            Set<String> typeSet = new HashSet<>();

            if (!StringUtils.isEmpty(groupType)) {
                for (String type : groupType.split(",")) {
                    typeSet.add(type);
                }
            }

            List<WlyyTalkGroup> groups = new ArrayList<>();

            if (!StringUtils.isEmpty(doctorName)) {
                groups = talkGroupService.searchTalkGroupsByDoctorName(getUID(), doctorName);
            } else {
                groups = talkGroupService.findDoctorTalkGroups(getUID());
            }

            if (typeSet.size() > 0 && groups != null) {
                for (WlyyTalkGroup talk : groups) {
                    if (!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))) {
                        jsonArray.put(new JSONObject(talk));
                    }
                }
            } else if (groups != null) {
                jsonArray = new JSONArray(groups);
            }

            return write(200, "获取医生讨论组成功!", "data", jsonArray);
        } catch (Exception ex) {
            return error(-1, "获取医生讨论组列表失败!");
        }
    }


    /**
     * 查询讨论组签约量
     *
     * @param groups
     * @return
     */
    @RequestMapping(value = "/group_sign", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroupSign(String groups) {
        try {
            List<Map<String, Object>> data = talkGroupService.getTalkGroupsSing(groups.split(","));

            return write(200, "查询成功", "data", new JSONArray(data));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 根据讨论组查找咨询code
     *
     * @param groupCode
     * @return
     */
    @RequestMapping(value = "/getConsultByGroupCode", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getConsultByGroupCode(@RequestParam(required = false) String groupCode, @RequestParam(required = false) String consultCode) {
        try {
            ConsultTeam consult = null;
            if (!org.springframework.util.StringUtils.isEmpty(groupCode)) {
                consult = talkGroupService.findConsultByGroup(groupCode);
            }
            if (!org.springframework.util.StringUtils.isEmpty(consultCode)) {
                consult = consultTeamService.findByConsultCode(consultCode);
            }
            if (org.springframework.util.StringUtils.isEmpty(consultCode) && org.springframework.util.StringUtils.isEmpty(groupCode)) {
                return error(-1, "查询失败");
            }
            JSONObject json = new JSONObject();
            json.put("id", consult.getId());
            // 设置咨询标识
            json.put("consult", consult.getConsult());
            // 设置患者标识
            json.put("patient", consult.getPatient());
            // 设置患者头像
            json.put("photo", consult.getPhoto());
            // 设置咨询标识
            json.put("title", consult.getSymptoms());
            // 设置患者姓名
            json.put("name", consult.getName());
            // 设置患者年龄
            json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
            // 设置评价内容
            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("sex", consult.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());
                    json.put("groupCreator" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCreator());
                    json.put("groupCreatorName" + wlyyTalkGroup.getType(), wlyyTalkGroup.getCreatorName());
                    json.put("groupType" + wlyyTalkGroup.getType(), wlyyTalkGroup.getType());
                }
            }
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }

    /**
     * 获取讨论组成员列表
     *
     * @return
     */
    @RequestMapping(value = "groupmembers", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupMembers(@RequestParam(required = true) String groupCode) {
        try {
            JSONArray result = new JSONArray();
            List<WlyyTalkGroupMember> groupMembers = talkGroupService.findTalkGroupMembers(groupCode);

            if (groupMembers == null) {
                groupMembers = new ArrayList<>();
            }

            for (WlyyTalkGroupMember member : groupMembers) {
                JSONObject memberJson = new JSONObject(member);
                if (member.getType() == 4) {
                    Patient p = patientService.findByCode(member.getMemberCode());

                    if (p != null) {
                        memberJson.put("photo", p.getPhoto());
                        memberJson.put("sex", p.getSex());
                    }
                } else {
                    Doctor doctor = doctorService.findDoctorByCode(member.getMemberCode());

                    if (doctor != null) {
                        memberJson.put("photo", doctor.getPhoto());
                        memberJson.put("sex", doctor.getSex());
                    }
                }
                result.put(memberJson);
            }

            return write(200, "获取讨论组成员列表成功!", "data", result);
        } catch (Exception ex) {
            return error(-1, "获取讨论组成员列表失败!");
        }
    }

    /**
     * 获取医生针对某个患者讨论组历史记录
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "histories", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupHistory(@RequestParam(required = true) String patient) {
        try {
            JSONArray groups = talkGroupService.getTalkGroupHistories(getUID(), patient);
            return write(200, "获取讨论组历史记录成功!", "data", groups);
        } catch (Exception e) {
            return error(-1, "获取讨论组历史记录失败!");
        }
    }

    /**
     * 查找与当前医生相关成员的讨论组
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "related", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getTalkGroupRelated(@RequestParam(required = true) String member, @RequestParam(required = false) String groupType) {
        try {
            JSONArray jsonArray = new JSONArray();
            Set<String> typeSet = new HashSet<>();

            if (!StringUtils.isEmpty(groupType)) {
                for (String type : groupType.split(",")) {
                    typeSet.add(type);
                }
            }

            List<WlyyTalkGroup> groups = talkGroupService.getTalkGroupRelated(getUID(), member);

            if (typeSet.size() > 0 && groups != null) {
                for (WlyyTalkGroup talk : groups) {
                    if (!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))) {
                        jsonArray.put(new JSONObject(talk));
                    }
                }
            } else if (groups != null) {
                jsonArray.put(new JSONArray(groups));
            }

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

    /**
     * 查询医生讨论组数量
     *
     * @return
     */
    @RequestMapping(value = "count", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getMyTalkGroupCount() {
        try {
            long count = talkGroupService.getDoctorTalkGroupCount(getUID());

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

}
