LAPTOP-KB9HII50\70708 před 1 rokem
rodič
revize
5d73e338e7

+ 3 - 1118
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/controller/DoctorConsultController.java

@ -1,27 +1,13 @@
package com.yihu.jw.hospital.module.consult.controller;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.hospital.message.service.SystemMessageService;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.DoctorAssistantUtil;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@ -33,62 +19,13 @@ import org.springframework.web.bind.annotation.RestController;
 * @author George
 */
@RestController
@RequestMapping(value = "/doctor/consult", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "/doctor/consult")
@Api(description = "三师咨询")
public class DoctorConsultController extends EnvelopRestEndpoint {
//    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
//    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private BasePatientService patientService;
    @Autowired
    private BaseDoctorInfoService doctorInfoService;
    @Autowired
    private com.yihu.jw.util.common.CommonUtil CommonUtil;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private SystemMessageService messageService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAssistantUtil doctorAssistantUtil;
    //    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private HospitalInviteSpecialistDao inviteSpecialistDao;
//    @Autowired
//    private PrescriptionDiagnosisService prescriptionDiagnosisService;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private HttpClientUtil httpClientUtil;
    private ConsultTeamService consultTeamService;
    @RequestMapping(value = "queryByConsultCode", method = RequestMethod.GET)
@ -114,22 +51,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
        }
    }
    @ApiOperation("咨询是否结束")
    @RequestMapping(value = "/getConsultStatusByPrescription", method = RequestMethod.GET)
    public String getConsultStatusByPrescription(@ApiParam(name = "prescriptionCode", value = "续方code")
                                                 @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            ConsultTeamDo consultTeam = consultTeamService.getConsultStatus(prescriptionCode);
            if (consultTeam != null) {
                return write(200, "查询成功", "data", consultTeam.getStatus());
            } else {
                return error(-1, "咨询不存在");
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
//
//    /**
@ -220,56 +141,7 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//            return error(-1, "发送失败");
//        }
//    }
//
//    @ApiOperation("医生拒绝视频")
//    @RequestMapping(value = "refuseVideo", method = RequestMethod.POST)
//    public String refuseVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "doctor", value = "医生code")
//                              @RequestParam(value = "doctor", required = true) String doctor) {
//        try {
//            Doctor d = doctorDao.findByCode(doctor);
//            d.setVideoStauts(0);
//            doctorDao.save(d);
//            imUtill.sendTopicIM(doctor, d.getName(), consult, "43", "医生在忙,建议提现预约视频通讯", null);
//            return success("拒绝成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生接通视频")
//    @RequestMapping(value = "connectVideo", method = RequestMethod.POST)
//    public String connectVideo() {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(1);
//            doctorDao.save(doctor);
//            return success("接通成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    @ApiOperation("医生挂断视频")
//    @RequestMapping(value = "handUpVideo", method = RequestMethod.POST)
//    public String handUpVideo(@ApiParam(name = "consult", value = "咨询code")
//                              @RequestParam(value = "consult", required = true) String consult,
//                              @ApiParam(name = "time", value = "视频接通时长")
//                              @RequestParam(value = "time", required = true) String time) {
//        try {
//            Doctor doctor = doctorDao.findByCode(getUID());
//            doctor.setVideoStauts(0);
//            doctorDao.save(doctor);
//            imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consult, "41", time, null);
//            return success("挂断成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//
//    }
//
//    /**
//     * 三师咨询列表查询
@ -369,26 +241,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//    }
//
//
//    @RequestMapping(value = "list_by_team", method = RequestMethod.POST)
//    @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) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 获取三师家庭咨询
@ -466,645 +318,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "/hasTnvite", method = RequestMethod.POST)
//    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) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 名医列表
//     *
//     * @return
//     */
//    @ApiOperation("名医列表")
//    @RequestMapping(value = "famousDoctorList", method = RequestMethod.POST)
//    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) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 获取咨询全科医生签约量
//     *
//     * @param consults
//     * @return
//     */
//    @ApiOperation("获取咨询全科医生签约量")
//    @RequestMapping(value = "/consult_sign", method = RequestMethod.POST)
//    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) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 结束三师咨询接口
//     *
//     * @param consult 三师咨询标识
//     * @return
//     */
//    @ApiOperation("结束三师咨询接口")
//    @RequestMapping(value = "finish", method = RequestMethod.POST)
//
//    public String finish(String consult) {
//        try {
//            int flag = consultTeamService.finish(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
//     * 医生咨询咨询日志查询
//     *
//     * @param consult  咨询标识
//     * @param patient  患者标识
//     * @param pagesize 每页显示数,默认为10
//     * @return
//     */
//    @ApiOperation("医生咨询咨询日志查询")
//    @RequestMapping(value = "record", method = RequestMethod.POST)
//    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<ConsultTeamDoLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
//            if (list != null) {
//                for (ConsultTeamDoLog 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) {
//            return invalidUserException(e, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 医生回复网络咨询
//     *
//     * @param patient 患者标识
//     * @param consult 咨询标识
//     * @param content 回复内容
//     * @param type    回复类型,1文字,2图片,3语音
//     * @return
//     */
//    @ApiOperation("医生回复网络咨询")
//    @RequestMapping(value = "reply", method = RequestMethod.POST)
//    public String reply(String patient, String consult, String content, int type) {
//        try {
//            // 查询医生基本信息
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "回复失败!");
//            } else {
//                ConsultTeamDoLog log = new ConsultTeamDoLog();
//                // 设置咨询标识
//                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 {
//                    // 推送消息给患者
//                    // 推送消息给微信端
//                    ConsultTeamDo 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) {
//            return invalidUserException(e, -1, "回复失败!");
//        }
//    }
//
//    /**
//     * 查询医生的总咨询次数和今日咨询次数
//     *
//     * @param doctorCode
//     * @return
//     */
//    @ApiOperation("查询医生的总咨询次数和今日咨询次数")
//    @RequestMapping(value = "getConsultCount", method = RequestMethod.POST)
//    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) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 查询患者的服务数目
//     *
//     * @return
//     */
//    @ApiOperation("查询患者的服务数目")
//    @RequestMapping(value = "getPatientServicNum", method = RequestMethod.POST)
//    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) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据医生code和和患者code判断是否有存在进行中的咨询
//     *
//     * @param patientCode 多个患者 逗号分隔
//     * @param doctor
//     * @return 只返回存在咨询的患者的code
//     */
//    @ApiOperation("根据医生code和和患者code判断是否有存在进行中的咨询")
//    @RequestMapping(value = "getConsultByPatientAndDoctor", method = RequestMethod.POST)
//    public String getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        try {
//            JSONArray json = new JSONArray();
//            String[] patients = patientCode.split(",");
//            //查询医生未结束居民列表
//            List<String> list = consultTeamService.getConsultListByPatientAndDoctor(doctor);
//            for (int i = 0; i < patients.length; i++) {
//                if (list.contains(patients[i])) {
//                    json.put(patients[i]);
//                }
//            }
//            return json.toString();
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 名医咨询添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("名医咨询添加接口")
//    @RequestMapping(value = "famousAdd", method = RequestMethod.POST)
//
//    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);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型: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.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.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 (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param doctor 医生
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/is_consult_unfinished", method = RequestMethod.POST)
//    public String isExistsUnfinishedConsult(@RequestParam(required = false) String patient,
//                                            @RequestParam(required = false) String type,
//                                            @RequestParam(required = true) String doctor) {
//        try {
//            if ("1".equals(type)) {
//                //专科
//                List<ConsultHelp> helps = consultTeamService.findUnfinishedByPatientAndSpecialist(patient, doctor);
//                if (helps.size() > 0) {
//                    return write(200, "查询成功", "data", helps.get(0).getConsult());
//                } else {
//                    return write(200, "查询成功", "data", "");
//                }
//            }
//            List<ConsultTeamDo> 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) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 查询与某个医生是否存在未结束的咨询
//     *
//     * @param consult 咨询code
//     * @return
//     */
//    @ApiOperation("查询与某个医生是否存在未结束的咨询")
//    @RequestMapping(value = "/consultTeam", method = RequestMethod.POST)
//    public String consult(@RequestParam(required = false) String consult) {
//        try {
//            ConsultTeamDo consultTeam = consultTeamService.findByCode(consult);
//            return write(200, "查询成功", "data", consultTeam);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//
//    /**
//     * 三师咨询转接接口
//     *
//     * @param consult 图咨询标识
//     * @param doctor  转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
//     * @param type    转接对象类型,1三师团队,2指定医生,3工作组团队
//     * @return
//     */
//    @ApiOperation("三师咨询转接接口")
//    @RequestMapping(value = "transfer", method = RequestMethod.POST)
//
//    public String transfer(
//            String consult,
//            String doctor,
//            @RequestParam(required = false) int type) {
//        try {
//            consultTeamService.transfers(getUID(), doctor, consult);
//            return success("转接成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 根据咨询code获取咨询的log
//     *
//     * @param consultCode
//     * @return
//     */
//    @ApiOperation("根据咨询code获取咨询的log")
//    @RequestMapping(value = "getConsultLog", method = RequestMethod.POST)
//    public String getConsultLog(
//            String consultCode) {
//        try {
//            List<ConsultTeamDoLog> consultTeamLogs = consultTeamService.getConsultLog(consultCode);
//            JSONArray ja = new JSONArray();
//            for (ConsultTeamDoLog 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) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 医生求助添加接口
//     *
//     * @param when       发病时间
//     * @param symptoms   主要症状
//     * @param groupCode  从哪个讨论组发起的求助
//     * @param images     图片URL地址,多图以逗号分隔
//     * @param voice      语音URL地址
//     * @param doctorCode 名医的code
//     * @return
//     */
//    @ApiOperation("医生求助添加接口")
//    @RequestMapping(value = "forHelpAdd", method = RequestMethod.POST)
//
//    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 {
//            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);
//            }
//
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型: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);
//            }
//            return success("提交成功");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//    @RequestMapping(value = "hasUnfinished", method = RequestMethod.POST)
//    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<ConsultTeamDo> ls = consultTeamService.hasUnfinished(doctorCode, curDoc);
//            if (ls != null && ls.size() > 0) {
//                ConsultTeamDo ct = ls.get(0);
//                json.put("consult", ct.getConsult());
//                //是否是医生求助医生
//                if (ct.getType() == 10) {
//                    //取出原有咨询求助返回原咨询的患者
//                    ConsultTeamDo 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) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 该咨询求助过的医生列表
//     *
//     * @param consult 关联的上一个咨询
//     * @return
//     */
//    @ApiOperation("该咨询求助过的医生列表")
//    @RequestMapping(value = "forHelpDocs", method = RequestMethod.POST)
//    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) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    @RequestMapping(value = "getConsult")
//    public String getConsult(String consult) {
@ -1126,73 +339,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "seekHelp", method = RequestMethod.POST)
//
//    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);
//                }
//            }
//            ConsultTeamDo consult = new ConsultTeamDo();
//            // 设置咨询类型: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 (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "提交失败!");
//        }
//    }
//
//
//    /**
//     * 结束咨询接口
//     *
//     * @param consult 咨询标识
//     * @return
//     */
//    @ApiOperation("结束咨询接口")
//    @RequestMapping(value = "finish_consult", method = {RequestMethod.GET, RequestMethod.POST})
//
//    public String finishConsult(@RequestParam(required = false) String consult) {
//        try {
//            int flag = consultTeamService.finishConsult(consult, getUID(), 2);
//            if (flag > 0) {
//                return success("咨询已关闭");
//            } else if (flag == -1) {
//                return error(-1, "该咨询已经关闭,不需重复关闭!");
//            } else if (flag == -2) {
//                return error(-1, "续方未审核,不能结束续方咨询!");
//            } else {
//                return error(-1, "关闭失败!");
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "关闭失败!");
//        }
//    }
//
//
//    /**
@ -1219,156 +365,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    /*********************************************续方咨询**************************************************************/
//
//    @RequestMapping(value = "prescriptionDetail", method = RequestMethod.GET)
//    @ApiOperation("获取续方信息")
//    public String prescriptionDetail(@ApiParam(name = "consult", value = "咨询code", defaultValue = "1")
//                                     @RequestParam(value = "consult", required = true) String consult) {
//        try {
//            JSONObject json = new JSONObject();
//
//            Consult consult1 = consultDao.findByCode(consult);
//            String prescriptionCode = consult1.getRelationCode();
//            Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//            json.put("status", prescription.getStatus());//状态 (-1 审核不通过 , 0 审核中, 10 审核通过/待支付 ,21支付失败  20 配药中/支付成功, 21 等待领药 ,30 配送中 ,100配送成功/已完成)
//            json.put("prescriptionDt", prescriptionDiagnosisService.getPrescriptionDiagnosis(prescriptionCode));//续方疾病类型
//            json.put("prescriptionInfo", prescriptionDiagnosisService.getPrescriptionInfo(prescriptionCode));//续方药品信息
//            json.put("followup", followUpService.getFollowupByPrescriptionCode(prescriptionCode));//续方关联的随访记录
//
//            //服务类型
//            List<SignFamilyServer> list = signFamilyServerDao.findBySignCodeAndType(consult1.getSignCode());
//            JSONArray jsonArray = new JSONArray();
//            if (list != null && list.size() > 0) {
//                for (SignFamilyServer server : list) {
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("serverType", server.getServerType());
//                    jsonObject.put("serverTypeName", server.getServerTypeName());
//                    jsonArray.put(jsonObject);
//                }
//            }
//            json.put("signFamilyServer", jsonArray);
//            json.put("symptoms", consult1.getSymptoms());//咨询类型--- 1高血压,2糖尿病
//            json.put("jwCode", prescription.getJwCode());//基位处方code
//            json.put("code", prescription.getCode());//续方code
//            json.put("viewJiancha", prescription.getViewJiancha());//检查
//            json.put("viewTizhen", prescription.getViewTizhen());//体征
//            json.put("viewChufang", prescription.getViewChufang());//处方
//            json.put("viewXufang", prescription.getViewXufang());//续方
//            json.put("viewWenjuan", prescription.getViewWenjuan());//问卷
//            json.put("viewSuifang", prescription.getViewSuifang());//随访
//
//            return write(200, "查询成功!", "data", json);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionBloodStatusConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送血糖血压快捷回复咨询")
//    public String addPrescriptionBloodStatusConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1血压,2血糖)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionBloodStatusConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "addPrescriptionFollowupContentConsult", method = RequestMethod.POST)
//
//    @ApiOperation("续方咨询-医生发送问卷快捷回复咨询")
//    public String addPrescriptionFollowupContentConsult(
//            @ApiParam(name = "prescriptionCode", value = "处方code", defaultValue = "")
//            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
//            @ApiParam(name = "type", value = "类型(1症状,2体征及生活方式)", defaultValue = "")
//            @RequestParam(value = "type", required = true) String type,
//            @ApiParam(name = "followupid", value = "随访记录ID", defaultValue = "")
//            @RequestParam(value = "followupid", required = true) String followupid) {
//        try {
//            consultTeamService.addPrescriptionFollowupContentConsult(prescriptionCode, type, followupid);
//            return write(200, "添加成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "getSessionId", method = RequestMethod.GET)
//    @ApiOperation("pcim-获取居民的sessionId")
//    public String getSessionId(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                               @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            com.alibaba.fastjson.JSONObject re = consultTeamService.getSessionId(patient);
//            return write(200, "获取成功!", "data", re);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "sendBusinessCard", method = RequestMethod.POST)
//    @ApiOperation("发送居民的名片")
//
//    public String sendBusinessCard(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
//                                   @RequestParam(value = "patient", required = true) String patient,
//                                   @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                   @RequestParam(value = "sessionId", required = true) String sessionId,
//                                   @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                   @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String doctorCode = getUID();
//            Doctor doctor = doctorService.findDoctorByCode(doctorCode);
//
//            Patient p = patientService.findByCode(patient);
//            com.alibaba.fastjson.JSONObject content = new com.alibaba.fastjson.JSONObject();
//            content.put("name", p.getName());
//            content.put("patient", patient);
//            content.put("photo", p.getPhoto());
//            content.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(), p.getBirthday()));
//            content.put("sex", IdCardUtil.getSexForIdcard_new(p.getIdcard()));
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily != null) {
//                content.put("hospitalName", signFamily.getHospitalName());
//            }
//            imUtill.sendImMsg(doctorCode, doctor.getName(), sessionId, ImUtill.ContentType.personalCard.getValue(), content.toString(), businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "messageForward", method = RequestMethod.POST)
//    @ApiOperation("请求转发消息")
//    public String messageForward(@ApiParam(name = "senderId", value = "发送者id", defaultValue = "")
//                                 @RequestParam(value = "senderId", required = true) String senderId,
//                                 @ApiParam(name = "senderName", value = "发送者姓名", defaultValue = "")
//                                 @RequestParam(value = "senderName", required = true) String senderName,
//                                 @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
//                                 @RequestParam(value = "sessionId", required = true) String sessionId,
//                                 @ApiParam(name = "content", value = "会话内容", defaultValue = "")
//                                 @RequestParam(value = "content", required = true) String content,
//                                 @ApiParam(name = "title", value = "会话标题", defaultValue = "")
//                                 @RequestParam(value = "title", required = true) String title,
//                                 @ApiParam(name = "sessionType", value = "原会话的会话类型", defaultValue = "")
//                                 @RequestParam(value = "sessionType", required = true) String sessionType,
//                                 @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
//                                 @RequestParam(value = "businessType", required = true) String businessType) {
//        try {
//            String message = consultTeamService.getMessageById(sessionType, content, title);
//            imUtill.sendImMsg(senderId, senderName, sessionId, ImUtill.ContentType.messageForward.getValue(), message, businessType);
//            return success("发送成功");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "examinationDetail", method = RequestMethod.GET)
//    @ApiOperation("获取在线复诊信息")
@ -1410,53 +406,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "inviteDoctor", method = RequestMethod.POST)
//    @ApiOperation("邀请医生回复居民问题")
//
//    public String inviteDoctor(@ApiParam(name = "sessionid", value = "会话ID")
//                               @RequestParam(value = "sessionid", required = true) String sessionid,
//                               @ApiParam(name = "doctor", value = "被邀请人")
//                               @RequestParam(value = "doctor", required = true) String doctor,
//                               @ApiParam(name = "topic", value = "咨询id")
//                               @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            String uid = getUID();
//            imUtill.updateParticipant(sessionid, doctor, null);
//            //设置邀请消息
//            Doctor from = doctorDao.findByCode(uid);
//            Doctor d = doctorDao.findByCode(doctor);
//            String content = "已邀请" + d.getName() + "医生为您服务,请耐心等待";
//            imUtill.sendTopicIM(from.getCode(), from.getName(), topic, "1", content, null);
//            //发送邀请医生提醒消息
////            if(StringUtils.isNotEmpty(d.getOpenid())){
////                String first = from.getName()+"医生邀请您,为";
////                doctorAssistantUtil.sendWXTemplate(1,d.getOpenid(),d.getCid(),"咨询邀请回复","","");
////            }
//            return write(200, "操作成功!");
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "askSpecialist", method = RequestMethod.POST)
//    @ApiOperation("邀请专科-回复居民咨询")
//
//    public String askSpecialist(@ApiParam(name = "sessionid", value = "会话ID")
//                                @RequestParam(value = "sessionid", required = true) String sessionid,
//                                @ApiParam(name = "doctor", value = "被邀请人")
//                                @RequestParam(value = "doctor", required = true) String doctor,
//                                @ApiParam(name = "topic", value = "咨询id")
//                                @RequestParam(value = "topic", required = true) String topic) {
//        try {
//            consultTeamService.askSpecialist(topic, sessionid, getUID(), doctor);
//            return write(200, "操作成功!");
//        } catch (ServiceException se) {
//            return error(-1, se.getMessage());
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 家庭医生发起康复咨询
//     *
@ -1529,27 +478,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//            } else if (res == -3) {
//                return error(-1, "还有咨询未结束,不允许再次提交咨询!");
//            }
//            Boolean flag = messageService.getMessageNoticeSettingByMessageType(doctorCode, "1", MessageNoticeSetting.MessageTypeEnum.imSwitch.getValue());
//            if (flag) {
//                pushMsgTask.put(specialDoctorCode, 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());
//                Doctor doctor = doctorDao.findByCode(specialDoctorCode);
//                if (doctor != null && StringUtils.isNotEmpty(doctor.getOpenid())) {
//                    String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                    List<NameValuePair> params = new ArrayList<>();
//                    params.add(new BasicNameValuePair("type", "4"));
//                    params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
//                    params.add(new BasicNameValuePair("url", targetUrl));
//                    params.add(new BasicNameValuePair("first", doctor.getName() + "医生您好,有患者向您发起咨询"));
//                    params.add(new BasicNameValuePair("remark", "【" + consult.getSymptoms() + "】\r\n请进入手机APP查看"));
//                    String sex = consult.getSex() == 1 ? "男" : "女";
//                    String keywords = consult.getName() + "," + sex;
//                    params.add(new BasicNameValuePair("keywords", keywords));
//
//                    httpClientUtil.post(url, params, "UTF-8");
//                }
//            }
////                }
////            }
//
//            BusinessLogs.info(BusinessLogs.BusinessType.consult, getRepUID(), getUID(), new JSONObject(consult));
//            return write(200, "提交成功", "data", consult);
@ -1560,49 +488,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
//        }
//    }
//
//    @RequestMapping(value = "getKangFuConsultList", method = RequestMethod.GET)
//    @ApiOperation("获取续方咨询列表")
//    public String getKangFuConsultList(@ApiParam(name = "title", value = "咨询标题") @RequestParam(required = false) String title,
//                                       @ApiParam(name = "patient", value = "居民CODE") @RequestParam(required = false) String patient,
//                                       @ApiParam(name = "id", value = "第几页") @RequestParam(required = true) long id,
//                                       @ApiParam(name = "pagesize", value = "页面大小") @RequestParam(required = true) int pagesize) {
//        try {
//            JSONArray array = new JSONArray();
//            Page<Object> data = consultTeamService.findConsultRecordByType(patient, id, pagesize, 18, title);//18表示康复咨询
//            Patient patientobj = patientService.findByCode(patient);
//            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病友圈,8 续方咨询  18康复咨询
//                    json.put("type", result[1]);
//                    // 设置咨询标识
//                    json.put("code", result[2]);
//                    // 设置显示标题
//                    json.put("title", result[3]);
//                    json.put("patientName", patientobj.getName());
//                    json.put("patientPhoto", patientobj.getPhoto());
//                    // 设置主诉
//                    json.put("symptoms", result[4]);
//                    // 咨询状态
//                    json.put("status", result[6]);
//                    // 设置咨询日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) result[5]));
//                    // 咨询状态
//                    json.put("doctorCode", result[7]);
//                    json.put("evaluate", result[8]);
//                    array.put(json);
//                }
//            }
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            return e.getMessage();
//        }
//    }
//
//    @RequestMapping(value = "/getDoctorConsultSessions", method = RequestMethod.GET)
//    @ApiOperation("获取医生咨询列表,带专家咨询")

+ 15 - 3040
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java

@ -1,8 +1,6 @@
package com.yihu.jw.hospital.module.consult.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
@ -12,32 +10,26 @@ import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.hospital.module.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.dao.ConsultTeamLogDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.order.dao.ConsultTeamOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
@ -52,128 +44,35 @@ public class ConsultTeamService extends ConsultService {
    private final Logger logger = LoggerFactory.getLogger(ConsultTeamService.class);
    private final Clock clock = Clock.DEFAULT;
    @Autowired
    private ConsultTeamOrderDao consultTeamDao;
    // 咨询详细记录
    @Autowired
    private ConsultTeamLogDao consultTeamLogDao;
    @Autowired
    private ConsultTeamDoctorDao consultTeamDoctorDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private BasePatientDao patientDao;
//    @Autowired
//    private PrescriptionLogService prescriptionLogService;
//    @Autowired
//    private PrescriptionInfoDao prescriptionInfoDao;
//    @Autowired
//    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
//    @Autowired
//    private WeiXinAccessTokenUtils accessTokenUtils;
    @Autowired
    private BasePatientService patientService;
//    @Autowired
//    private MessageService messageService;
//
//    @Autowired
//    private PrescriptionExpressageDao expressageDao;
//    @Autowired
//    private HospitalDao hospitalDao;
    @Autowired
    private WlyyDoorServiceOrderDao wlyyDoorServiceOrderDao;
    @Autowired
    private WlyyDoorServiceOrderService wlyyDoorServiceOrderService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private HttpClientUtil httpClientUtil;
    Map<Integer, String> relations = new HashMap<>();
    @Value("${im.im_list_get}")
    private String im_list_get;
    @Value("${im.data_base_name}")
    private String imdb;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private BaseDoctorInfoService doctorService;
//    @Autowired
//    private TalkGroupService talkGroupService;
//    @Autowired
//    private PatientDeviceDao patientDeviceDao;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private PatientHealthGuidanceService guidanceService;
//    @Autowired
//    private PatientFamilyMemberDao familyMemberDao;
//    @Autowired
//    private HealthEduArticleService healthEduArticleService;
//    @Autowired
//    private CsrfConstant csrfConstant;
//    @Autowired
//    private ConsultHelpDao consultHelpDao;
//    @Autowired
//    private DoctorHelpDao doctorHelpDao;
//    @Autowired
//    private DoctorAssistantUtil doctorAssistantUtil;
//    @Autowired
//    private PrescriptionExplainDao prescriptionExplainDao;
//    @Autowired
//    private ExaminationDao examinationDao;
//    @Autowired
//    private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;
//    @Autowired
//    private SpecialDiseaseMessagesDao specialDiseaseMessagesDao;
//    @Autowired
//    private PrescriptionFollowupContentService prescriptionFollowupContentService;
//    @Autowired
//    private SystemDictDao systemDictDao;
//    @Autowired
//    private FollowUpDao followupDao;
//    @Autowired
//    private PrescriptionReviewedDao prescriptionReviewedDao;
//    @Autowired
//    private JwPrescriptionService jwPrescriptionService;
//    @Autowired
//    private PrescriptionInfoService prescriptionInfoService;
//    @Autowired
//    private PresModeAdapter presModeAdapter;
//    @Autowired
//    private ZyDictService zyDictService;
//    @Autowired
//    private WeiXinOpenIdUtils weiXinOpenIdUtils;
//    @Autowired
//    private MessageDao messageDao;
    /**
     * 添加上门服务咨询
     */
@ -233,7 +132,6 @@ public class ConsultTeamService extends ConsultService {
         * 创建议题
         */
        JSONObject imResponseJson = imUtill.createTopics(sessionId, consult.getId(), content, participants, messages, ImUtil.SESSION_TYPE_ONDOOR_NURSING);
        System.out.println("创建议题成功了!!!!!!!!!!!!!!!!");
        if (imResponseJson == null || imResponseJson.getString("status").equals("-1")) {
            String failMsg = "发起服务咨询时:IM" + imResponseJson.getString("message");
            throw new Exception(failMsg);
@ -241,292 +139,14 @@ public class ConsultTeamService extends ConsultService {
        if (imResponseJson != null && imResponseJson.get("start_msg_id") != null) {
            consultTeam.setStartMsgId(imResponseJson.get("start_msg_id").toString());
        }
        System.out.println("准备保存consultTeam和consult");
        consultTeamDao.save(consultTeam);
        consultDao.save(consult);
        System.out.println("保存的consultTeam==>"+ JSON.toJSONString(consultTeam));
        System.out.println("保存的consult==>"+ JSON.toJSONString(consult));
        System.out.println("保存consultTeam和consult成功");
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, consultTeam);
        return result;
    }
//    @PostConstruct
//    public void init() {
//        relations.put(0, "其他");
//        relations.put(1, "父亲");
//        relations.put(2, "母亲");
//        relations.put(3, "老公");
//        relations.put(4, "老婆");
//        relations.put(5, "儿子");
//        relations.put(6, "女儿");
//        relations.put(7, "未知");
//        csrfConstant.init();
//    }
    /**
     * 查找邀请医生列表
     *
     * @param consultCode 咨询code
     * @param type        1家签医生 2社区邀约 3专病防治中心
     * @param hospital    医院code
     * @param deptName    科室名称
     * @param disease     专病类型
     * @param name        医生、机构、科室
     * @param sortBy      排序 不传默认综合
     *                    综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    1被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
     *                    2回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
     *                    3平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
     *                    4用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
     * @param size
     */
//    public PageEnvelop findHelpDoctorPage(String uid, String consultCode, String type, String hospital, String sortBy,
//                                          String deptName, String disease, String name, Integer page, Integer size) {
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor d = doctorDao.findByCode(uid);
//        boolean flag = true;
//        if (d != null) {
//            if (Constant.testHospital.equals(d.getHospital())) {
//                flag = false;
//            }
//        }
//        String patient = consult.getPatient();
//        String field = "";
//        if ("3".equals(type)) {
//            field = ",a.special_code specialCode,a.special_name specialName";
//        }
//        String sql = "SELECT DISTINCT d.code,d.name,d.photo,d.job_name jobName,d.dept_name deptName,d.hospital_name hospitalName " +
//                field + ",ifnull(h.reply_rate,'0%') replyRate " +
//                ",ifnull(h.average_response,0) averageResponse,ifnull(h.evaluate_score,80) evaluateScore " +
//                ",ifnull(h.invite_num,0) inviteNum,ifnull(h.invited_num,0) invitedNum " +
//                ",if(sf.id is null,0,1) 'signFlag',if(p.id is null,0,1) 'zbFlag' ";
//        String countSql = "select count(DISTINCT d.code) ";
//        String filter = "";
//        if ("3".equals(type)) {
//            filter = " from wlyy_admin_team a,wlyy_admin_team_member m,wlyy_doctor d " +
//                    " LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE a.accept_type = 0 and a.available =1 and a.special_code is not null " +
//                    " and a.id = m.team_id and m.available=1 and m.doctor_code=d.code and d.`status`=1 ";
//            if (StringUtils.isNotBlank(disease)) {
//                filter += " and a.special_code='" + disease + "' ";
//            }
//        } else {
//            filter = "from wlyy_hospital_invite_specialist s,wlyy_doctor d " +
//                    "LEFT JOIN wlyy_doctor_help h on d.code = h.doctor " +
//                    " LEFT JOIN wlyy_sign_family sf on sf.patient='" + patient + "' and sf.`status`>=0 and sf.specialist=d.code " +
//                    " LEFT JOIN wlyy_patient_rehabilitation_plan p on p.patient = '" + patient + "' and p.create_user=d.code " +
//                    " WHERE s.specialist=d.code and d.`status`=1 and s.type = '" + type + "' ";
//            if ("2".equals(type) && d != null) {
//                filter += " and s.hospital='" + d.getHospital() + "' ";
//            }
//        }
//        //排除医生自己
//        filter += " and d.code!='" + uid + "' ";
//        if (StringUtils.isNotBlank(hospital)) {
//            filter += " and d.hospital='" + hospital + "' ";
//        }
//        if (StringUtils.isNotBlank(deptName)) {
//            filter += " and d.dept_name='" + deptName + "' ";
//        }
//        if (StringUtils.isNotBlank(name)) {
//            filter += " and (d.name like '%" + name + "%' or d.dept_name like '%" + name + "%' or d.hospital_name like '%" + name + "%')";
//        }
//
//        if (flag) {
//            filter += " and d.hospital !='" + Constant.testHospital + "' ";
//        }
//        String orderBy = "";
//        if ("1".equals(sortBy)) {
//            //被邀请次数:被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        } else if ("2".equals(sortBy)) {
//            //回复率:回复率 > 被邀请次数>平均响应时长>用户评价;
//            orderBy = " order by replyRate desc,invitedNum desc,averageResponse desc,evaluateScore desc ";
//        } else if ("3".equals(sortBy)) {
//            //平均响应时长:平均响应时长>被邀请次数>回复率>用户评价 ;
//            orderBy = " order by averageResponse desc,invitedNum desc,replyRate desc,evaluateScore desc ";
//        } else if ("4".equals(sortBy)) {
//            //用户评价:用户评价>被邀请次数>回复率 > 平均响应时长;
//            orderBy = " order by evaluateScore desc,invitedNum desc,replyRate desc,averageResponse desc ";
//        } else {
//            //综合:专家标签>被邀请次数>回复率 > 平均响应时长>用户评价;
//            orderBy = " order by signFlag desc,zbFlag desc,invitedNum desc,replyRate desc,averageResponse desc,evaluateScore desc ";
//        }
//
//        orderBy += " limit " + (page - 1) * size + "," + size;
//
//        long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql + filter + orderBy);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//        Map<String, String> speMap = consultHelpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        for (Map<String, Object> map : list) {
//            String code = map.get("code") + "";
//            int askFlag = 0;
//            if (speMap.containsKey(code)) {
//                askFlag = 1;
//            }
//            map.put("askFlag", askFlag);
//        }
//        return PageEnvelop.getSuccessListWithPage("获取成功", list, page, size, count);
//    }
    //专科医生获取家庭医生咨询邀请
//    public Envelop findConsultHelpPage(String specialist, String status, String patientName, Integer page, Integer size) {
//        String sql = "select c.*,p.photo,d.dept_name deptName,d.photo doctorPhoto ";
//        String countSql = " select count(c.id) ";
//        String filter = " from wlyy_consult_help c " +
//                " left join wlyy_patient p on c.patient=p.code " +
//                " left join wlyy_doctor d on c.doctor=d.code " +
//                " where c.specialist='" + specialist + "' ";
//        String orderBy = " order by c.id desc limit " + (page - 1) * size + "," + size;
//        if (StringUtils.isNotBlank(status)) {
//            filter += " and c.status = '" + status + "' ";
//        }
//        if (StringUtils.isNotBlank(patientName)) {
//            filter += " and (c.patient_name like '%" + patientName + "%' or d.name like '%" + patientName + "%')";
//        }
//        Long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
//        List<ConsultHelp> helpList = jdbcTemplate.query(sql + filter + orderBy, new BeanPropertyRowMapper<>(ConsultHelp.class));
//
//        return PageEnvelop.getSuccessListWithPage("获取成功", helpList, page, size, count);
//    }
    //结束咨询修改 邀请的状态
//    public void endConsultHelp(String consultCode) {
//        try {
//            List<ConsultHelp> helps = consultHelpDao.findConsultAndStatus(consultCode);
//            if (helps.size() > 0) {
//                List<ConsultHelp> helpList = new ArrayList<>();
//                for (ConsultHelp help : helps) {
//                    String status = help.getStatus();
//                    String specialist = help.getSpecialist();
//                    if ("0".equals(status)) {
//                        help.setStatus("3");
//                        helpList.add(help);
//                    } else if ("1".equals(status)) {
//                        help.setStatus("2");
//                        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialist);
//                        doctorHelp.setInvitedNum(doctorHelp.getInvitedNum() + 1L);
//                        if (doctorHelp.getInviteNum() == null || doctorHelp.getInviteNum() == 0) {
//                            doctorHelp.setInviteNum(1L);
//                        }
//                        doctorHelp.setReplyRate(getRange(doctorHelp.getInvitedNum(), doctorHelp.getInviteNum()));
//                        doctorHelpDao.save(doctorHelp);
//                        helpList.add(help);
//                    }
//                }
//                if (helpList.size() > 0) {
//                    consultHelpDao.save(helpList);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    /**
     * 获取2个数的百分比
     *
     * @param first
     * @param second
     * @return
     */
    public String getRange(Long first, Long second) {
        if (second == 0 && first > 0) {
            return "100%";
        } else if (second == 0 && first == 0) {
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }
    //邀请专科-回复居民咨询
    @Transactional
//    public synchronized void askSpecialist(String consultCode, String sessionId, String doctorCode, String specialistCode) {
//        List<ConsultHelp> helps = consultHelpDao.findByConsultAndSpecialist(consultCode, specialistCode);
//        if (helps.size() > 0) {
//            throw new ServiceException("请勿重复邀请");
//        }
//        //医生统计表
//        DoctorHelp doctorHelp = doctorHelpDao.findByDoctor(specialistCode);
//        if (doctorHelp == null) {
//            doctorHelp = new DoctorHelp();
//            doctorHelp.setDoctor(specialistCode);
//            doctorHelp.setAverageResponse(0L);
//            doctorHelp.setInviteNum(1L);
//            doctorHelp.setResponseTime(0L);
//            doctorHelp.setReplyRate("0%");
//            doctorHelp.setInvitedNum(0L);
//            doctorHelp.setCreateTime(new Date());
//            doctorHelp.setEvaluateScore(80D);
//            doctorHelp.setReplyNum(1L);
//        } else {
//            doctorHelp.setInviteNum(doctorHelp.getInviteNum() + 1L);
//        }
//        doctorHelpDao.save(doctorHelp);
//        List<ConsultHelp> consultHelpList = consultHelpDao.findConsult(consultCode);
//
//        Consult consult = consultDao.findByCode(consultCode);
//        Doctor doctor = doctorDao.findByCode(doctorCode);
//        Doctor specialist = doctorDao.findByCode(specialistCode);
//        Patient patient = patientDao.findByCode(consult.getPatient());
//        Hospital hospital = hospitalDao.findByCode(doctor.getHospital());
//        SignFamily signFamily = signFamilyDao.findByPatient(consult.getPatient());
//        ConsultHelp help = new ConsultHelp();
//        help.setStatus("0");
//        help.setType(consult.getType() + "");
//        help.setPatientName(patient.getName());
//        help.setCreateTime(new Date());
//        help.setConsult(consultCode);
//        help.setPatient(consult.getPatient());
//        help.setDoctor(doctorCode);
//        help.setDoctorName(doctor.getName());
//        help.setHospital(doctor.getHospital());
//        help.setHospitalName(doctor.getHospitalName());
//        help.setSpecialist(specialistCode);
//        help.setSpecialistDept(specialist.getDept());
//        help.setSpecialistName(specialist.getName());
//        help.setSpecialistHospital(specialist.getHospital());
//        help.setSpecialistHospitalName(specialist.getHospitalName());
//        help.setSpecialistDeptName(specialist.getDeptName());
//        help.setTown(hospital.getTown());
//        help.setSessionId(sessionId);
//        help.setAdminTeamId(signFamily.getAdminTeamId());
//        consultHelpDao.save(help);
//
//
//        imUtill.updateParticipant(sessionId, specialistCode, null);
//        //设置邀请消息
//        //居民端和家庭医生端 家庭医生【姓名】已邀请 专科医生【姓名】进入咨询
//        //专科医生端 家庭医生【姓名】邀请您加入了群聊,群聊参与人还有: {患者姓名}{其他群聊成员}
//        String content1 = "家庭医生[" + doctor.getName() + "]已邀请 专科医生[" + specialist.getName() + "]进入咨询";
//        String doctors = signFamily.getDoctorName();
//        if (StringUtils.isNotBlank(signFamily.getDoctorHealthName()) && !doctors.equals(signFamily.getDoctorHealthName())) {
//            doctors += "," + signFamily.getDoctorHealthName();
//        }
//        for (ConsultHelp consultHelp : consultHelpList) {
//            doctors += "," + consultHelp.getSpecialistName();
//        }
//        String content2 = "家庭医生[" + doctor.getName() + "]邀请您加入了群聊,群聊参与人还有:{" + patient.getName() + "}{" + doctors + "}";
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "46", content1, null);
//        imUtill.sendTopicIM(doctor.getCode(), doctor.getName(), consultCode, "47", content2, null);
//
//        //发送医生助手消息
//        String first = specialist.getName() + "医生您好,您收到来自" + doctor.getHospitalName() + "的" + doctor.getName() + "咨询求助,请访问厦门i健康APP查看。";
//        doctorAssistantUtil.sendWXTemplate(9, specialist.getOpenid(), specialist.getCid(), first, "请及时处理", "咨询求助", specialist.getHospitalName(), specialist.getName());
//
//        messageService.addSpecialistDynamicMessages(patient, specialist, doctor, "咨询求助", null, "3", null);
//    }
    /**
     * 医生主动发送im消息
     */
@ -548,1618 +168,18 @@ public class ConsultTeamService extends ConsultService {
            } else if ("3".equals(contentType)) {
                content = "一条语音消息";
            } else {
                content = "一条消息";
            }
            String url = temp.getUrl() + "&openid=" + p.getOpenid() + "&peerId=" + doctor + "&peerName=" + doctorName;
            json.put("consultcontent", temp.getKeyword1());
            json.put("replycontent", content);
            json.put("doctorName", doctorName);
            json.put("remark", "");
            json.put("url", url);
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
        }
    }
    /**
     * 处方判断
     */
//    public JSONObject isPrescriptConsult(String patient) {
//        JSONObject json = new JSONObject();
//        SignFamily signFamily = signFamilyDao.findByPatient(patient);
//        if (signFamily == null) {
//            json.put("msg", "您还未签约,不能发起续方咨询");
//            return json;
//        }
//
//        //续方说明
//        List<PrescriptionExplain> list = prescriptionExplainDao.findList();
//        JSONArray ja = new JSONArray();
//        for (PrescriptionExplain explain : list) {
//            ja.put(explain.getContent());
//        }
//
//        Doctor doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//
//        Hospital hospital = hospitalDao.findByCode(signFamily.getHospital());
//
//        json.put("doctor", doctor.getCode());
//        json.put("doctorName", doctor.getName());
//        json.put("adminTeamId", signFamily.getAdminTeamId());
//        json.put("hospital", doctor.getHospital());
//        json.put("hospitalName", doctor.getHospitalName());
//        json.put("hospitalAddress", hospital.getAddress());
//        json.put("prescriptionExplain", ja);
//        return json;
//    }
    /**
     * 查询患者是否还有未结束的三师咨询
     */
//    public boolean exist(String patient, Integer type) throws Exception {
//        String memberCode = null;
//        if (type == 2 || type == 18) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//            if (sf == null) {
//                throw new ServiceException("不存在家庭签约");
//            }
//            if (StringUtils.isEmpty(sf.getDoctorHealth())) {
//                memberCode = sf.getDoctor();
//            } else {
//                memberCode = sf.getDoctorHealth();
//            }
//
//        }
//
//        int count = consultTeamDao.countByPatient(patient, type, memberCode);
//        return count > 0;
//    }
    /**
     * 查詢醫生網絡諮詢列表
     *
     * @param type     咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的 5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamDo> findByDoctor(String uid, int type, long id, int pagesize, String patient, String title) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        switch (type) {
//            case 0:
//                // 全部
//                return findByDoctorType0(uid, id, patient, pagesize);
//            case 1:
//                // 咨询我的
//                return findByDoctorType1(uid, type, id, pagesize);
//            case 2:
//                // 我感兴趣的
//                return findByDoctorType2(uid, type, id, pagesize);
//            case 3:
//                // 我回复的
//                return findByDoctorType3(uid, id, pagesize);
//            case 4:
//                // 已完成的
//                return findByDoctorType4(uid, id, pagesize);
//            case 5:
//                // 5 名医咨询 全部
//                return findByDoctorType5(uid, id, pagesize, title);
//            case 6:
//                //6 名医咨询 进行中
//                return findByDoctorType6(uid, 0, id, pagesize, title);
//            case 7:
//                //7 名医咨询 已结束
//                return findByDoctorType6(uid, 1, id, pagesize, title);
//            case 8:
//                return findByDoctorType8(uid, id, pagesize, title);
//            case 9:
//                return findByDoctorType9(uid, id, pagesize);
//            case 10:
//                //我咨询的
//                return findByDoctorType10(uid, id, pagesize, title);
//            case 11:
//                //我咨询的 进行中
//                return findByDoctorType11(uid, 0, id, pagesize, title);
//            case 12:
//                //我咨询的 已结束中
//                return findByDoctorType11(uid, 1, id, pagesize, title);
//        }
//        return null;
//    }
//    private Page<ConsultTeamDo> findByDoctorType11(String uid, int status, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorListByStatus(uid, status, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType10(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findMyFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType8(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorUnReplyReadNoTitleList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType5(String uid, long id, int pagesize, String title) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, title, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, title, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorAllList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorAllList(uid, pageRequest);
//            }
//        }
//    }
//    private Page<ConsultTeamDo> findByDoctorType6(String uid, int type, long id, int pagesize, String title) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isNoneEmpty(title)) {
//            title = "%" + title + "%";
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, title, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, title, type, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findFamousDoctorDoingList(uid, id, type, pageRequest);
//            } else {
//                return consultTeamDao.findFamousDoctorDoingList(uid, type, pageRequest);
//            }
//        }
//    }
    /**
     * 根据状态获取三师家庭咨询
     *
     * @param status 0未处理或未回复 1已回复 2已结束
     */
//    public Page<ConsultTeamDo> findConsultByDoctor(String doctor, int status, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//
//        if (status == 0) {
//            return findConsultByDoctorWcl(doctor, id, pagesize);
//        } else if (status == 1) {
//            return findConsultByDoctorIng(doctor, id, pagesize);
//        } else {
//            return findByDoctorType4(doctor, id, pagesize);
//        }
//    }
    /**
     * 获取三师家庭未处理咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorWcl(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        sort.and(new Sort(Direction.DESC, "czrq"));
//        sort.and(new Sort(Direction.DESC, "doctorRead"));
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorUnReplyReadNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 获取三师家庭已回复咨询
     */
//    private Page<ConsultTeamDo> findConsultByDoctorIng(String uid, long id, int pagesize) {
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        if (id > 0) {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorIngNoTitleList(uid, pageRequest);
//        }
//    }
    /**
     * 查询全部咨询记录
     */
//    public Page<ConsultTeamDo> findByDoctorType0(String uid, long id, String patient, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (StringUtils.isEmpty(patient)) {
//            if (id > 0) {
//                return consultTeamDao.findDoctorList(uid, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorList(uid, pageRequest);
//            }
//        } else {
//            if (id > 0) {
//                return consultTeamDao.findDoctorPatientList(uid, patient, id, pageRequest);
//            } else {
//                return consultTeamDao.findDoctorPatientList(uid, patient, pageRequest);
//            }
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType1(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorPointList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorPointList(uid, pageRequest);
//        }
//    }
    /**
     * 指定医生三师咨询列表查询
     *
     * @param uid 医生标识
     */
    public Page<ConsultTeamDo> findByDoctorType9(String uid, long id, int pagesize) {
        return null;
    }
    /**
     * 公共三师咨询列表查询
     *
     * @param uid  医生标识
     * @param type 咨询类型:1、咨询我的,2、公共的, 3、参与过的,4、已结束的
     */
//    public Page<ConsultTeamDo> findByDoctorType2(String uid, int type, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        // 未指定医生
//        filters.put("type", new SearchFilter("type", Operator.EQ, 0));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未回复
//        filters.put("status", new SearchFilter("status", Operator.EQ, 0));
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamDo> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeam.class);
//
//        return consultTeamDao.findAll(spec, pageRequest);
//    }
    /**
     * 医生参与过的未结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType3(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorJoinList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorJoinList(uid, pageRequest);
//        }
//    }
    /**
     * 医生参与过的已结束的三师咨询列表查询
     */
//    public Page<ConsultTeamDo> findByDoctorType4(String uid, long id, int pagesize) {
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        if (id > 0) {
//            return consultTeamDao.findDoctorFinishList(uid, id, pageRequest);
//        } else {
//            return consultTeamDao.findDoctorFinishList(uid, pageRequest);
//        }
//    }
    /**
     * 网络咨询咨询日志查询
     *
     * @param consult  咨询标识
     * @param pagesize 每页显示数,默认为10
     */
//    public Page<ConsultTeamLog> findLogByConsult(String consult, long id, int pagesize) {
//        if (id < 0) {
//            id = 0;
//        }
//
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("consult", new SearchFilter("consult", Operator.EQ, consult));
//
//        if (id > 0) {
//            if (pagesize > 0)
//                filters.put("id", new SearchFilter("id", Operator.LT, id));
//            else
//                filters.put("id", new SearchFilter("id", Operator.GT, id));
//        }
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<ConsultTeamLog> spec = DynamicSpecifications.bySearchFilter(filters.values(), ConsultTeamLog.class);
//
//        if (pagesize <= 0) {
//            Page<ConsultTeamLog> p = new PageImpl<>(consultTeamLogDao.findAll(spec));
//            return p;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        return consultTeamLogDao.findAll(spec, pageRequest);
//    }
    /**
     * 批量回复
     */
//    public void reply(List<ConsultTeamLogDo> logs, String patient) throws Exception {
//        ConsultTeamDo consultTeam = consultTeamDao.findByConsult(logs.get(0).getConsult());
//        WlyyTalkGroup wlyyTalkGroup = talkGroupService.findConsultTalkGroupByType(logs.get(0).getConsult(), 2);
//        for (ConsultTeamLog log : logs) {
//            reply(log, patient, null, log.getType());
//            //判断当前咨询是否创建讨论租
//            if (wlyyTalkGroup != null) {
//                sendGroupIM(patient, wlyyTalkGroup.getCode(), log.getChatType() + "", log.getContent());
//            } else {
//                //推送给IM
//                sendIM(patient, consultTeam.getDoctor(), log.getChatType() + "", log.getContent());
//            }
//        }
//    }
    /**
     * 查询居民咨询记录
     */
//    public JSONArray findByPatientAndTeam(String patient, Long teamCode, int page, int pageSize) {
//        PageRequest pageRequest = new PageRequest(page, pageSize);
//        BasePatientDO  p = patientDao.findByCode(patient);
//        Page<Object> result = consultDao.findByPatientAll(patient, pageRequest);
//        JSONArray array = new JSONArray();
//
//        for (Object obj : result) {
//            JSONObject consult = new JSONObject();
//            Object[] objArr = (Object[]) obj;
//            consult.put("id", objArr[0]);
//            consult.put("code", objArr[2]);
//            consult.put("type", objArr[1]);
//            consult.put("title", objArr[3]);
//            consult.put("symptoms", objArr[4]);
//            consult.put("czrq", objArr[5]);
//            consult.put("status", objArr[6]);
//            consult.put("adminTeamCode", objArr[7]);
//            consult.put("team", objArr[8]);
//            consult.put("patient", patient);
//            consult.put("patientName", p.getName());
//            consult.put("patientPhoto", p.getPhoto());
//            consult.put("total", result.getTotalElements());
//            array.put(consult);
//        }
//
//        return array;
//    }
    /**
     * 添加咨询记录
     *
     * @param log  日志对象
     * @param type 类型,0问,1回复,2追问,3评价
     */
//    public ConsultTeamLogDo reply(ConsultTeamLogDo log, String patient, String teamOrDoctor, int type) {
//        log.setCzrq(clock.getCurrentDate());
//        // 保存咨询记录
//        ConsultTeamLogDo temp = consultTeamLogDao.save(log);
//        if (temp != null) {
//            // 发送消息
//            if (type == 1) {
//                // 医生回复,给患者发消息
//                // 患者未读数量+1
//                consultTeamDao.increasePatientRead(log.getConsult());
//                // 医生有回复
//                consultTeamDoctorDao.updateReply(log.getConsult(), teamOrDoctor);
//
//                //shenzaixin v1.2.0 推送消息给患者
//                //HttpUtil.sendWeixinWebsocketMsg(patient, "{busiType:'qianyuezixun',msgid:'" + log.getId() + "'}");
//            } else if (type == 0 || type == 2) {
//                // 查询相关联的医生
//                Iterable<ConsultTeamDoctorDo> iterable = consultTeamDoctorDao.findByConsult(log.getConsult());
//                if (iterable != null && iterable.iterator().hasNext()) {
//                    Iterator<ConsultTeamDoctorDo> iterator = iterable.iterator();
//                    while (iterator.hasNext()) {
//                        // 患者提问或追问,给医生发消息
//                        ConsultTeamDoctorDo ctd = iterator.next();
//                        if (ctd == null) {
//                            continue;
//                        }
//                        // 推送消息给医生
//                        pushMsgTask.put(ctd.getTo(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.D_CT_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.指定咨询.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_CONSULT_TEAM_REPLY.您有新的消息.name(), temp.getConsult());
//                    }
//                }
//                // 医生未读数量+1
//                consultTeamDao.increaseDoctorRead(log.getConsult());
//            }
//        }
//        return temp;
//    }
    /**
     * 患者直接发起康复咨询
     */
//    public JSONObject addRecoverConsult(ConsultTeamDo ct, Long teamId, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        //议题添加团队内所有成员
//        JSONObject users = new JSONObject();
//        String specialDoctorCode = "";
//        List<BaseDoctorDO> docList = doctorAdminTeamMemberDao.findAllMembers(teamId);
//        for (BaseDoctorDO doc : docList) {
//            if (StringUtils.isBlank(specialDoctorCode) && doc.getLevel() == 1) {
//                specialDoctorCode = doc.getId();
//            }
//            users.put(doc.getId(), 0);
//        }
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        // 获取家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//        if (sf == null) {
//            // 不存在家庭签约
//            re.put("status", -1);
//            return re;
//        }
//        ct.setTeam(sf.getTeamCode());
//        // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//        //查找病人所在的团队
//        //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//        if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//            users.put(sf.getDoctorHealth(), 0);
//            ct.setDoctor(sf.getDoctorHealth());
//            if (StringUtils.isNotBlank(sf.getDoctor())) {
//                if (users.isNull(sf.getDoctor())) {
//                    //全科需要判断是否开启健管师邀请后在接收消息
//                    int isGetMessage = 1;
//                    if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                        isGetMessage = 0;
//                    }
//                    users.put(sf.getDoctor(), isGetMessage);
//                }
//            }
//        } else {
//            ct.setDoctor(sf.getDoctor());
//            users.put(sf.getDoctor(), 0);
//        }
//        ct.setAdminTeamId(teamId);
//
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        String sessionId = patient + "_" + ct.getDoctor() + "_" + specialDoctorCode + "_" + ct.getType();
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        //specialDoctorCode
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//            SpecialDiseaseMessages diseaseMessages = new SpecialDiseaseMessages();
//            diseaseMessages.setCode(patient);
//            diseaseMessages.setName(tempPatient.getName());
//            diseaseMessages.setAddress(tempPatient.getAddress());
//            diseaseMessages.setCodeType("2");
//            diseaseMessages.setCreateTime(sdf.format(new Date()));
//            diseaseMessages.setResult("发起康复咨询");
//            specialDiseaseMessagesDao.save(diseaseMessages);
//        } catch (Exception e) {
//            logger.info("ConsultTeamService中 addRecoverConsult 方法保存出错");
//            e.printStackTrace();
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 患者端
     * 添加三师咨询
     *
     * @param ct      三师咨询对象
     * @param patient 患者标识
     */
//    public JSONObject addTeamConsult(ConsultTeamDo ct, String patient, String agent, String times) throws Exception {
//        JSONObject re = new JSONObject();
//        if (exist(patient, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
//            re.put("status", -3);
//            return re;
//        }
//
//        JSONObject users = new JSONObject();
//
//        if (patient.equals(agent)) {
//            agent = null;
//        }
//
//        if (ct.getType() == 2) {
//            // 咨询家庭医生
//            SignFamily sf = signFamilyDao.findByjiatingPatient(patient);
//
//            if (sf == null) {
//                // 不存在家庭签约
//                re.put("status", -1);
//                return re;
//            }
//            ct.setTeam(sf.getTeamCode());
//            // 设置健康管理师,家庭医生咨询默认给健康管理师处理
//            //查找病人所在的团队
//            //1.3.3.2 更改从签约记录判断团队成员,分配建管师
//            if (StringUtils.isNotBlank(sf.getDoctorHealth())) {
//                users.put(sf.getDoctorHealth(), 0);
//                ct.setDoctor(sf.getDoctorHealth());
//                if (StringUtils.isNotBlank(sf.getDoctor())) {
//                    if (users.isNull(sf.getDoctor())) {
//                        //全科需要判断是否开启健管师邀请后在接收消息
//                        int isGetMessage = 1;
//                        if (!messageService.getMessageNoticeSettingByMessageType(sf.getDoctor(), "1", MessageNoticeSetting.MessageTypeEnum.familyTopicSwitch.getValue())) {
//                            isGetMessage = 0;
//                        }
//                        users.put(sf.getDoctor(), isGetMessage);
//                    }
//                }
//            } else {
//                ct.setDoctor(sf.getDoctor());
//                users.put(sf.getDoctor(), 0);
//            }
//
//            // 设置家庭医生
//            ct.setAdminTeamId(sf.getAdminTeamId());
//        }
//        // 设置患者信息
//        ct.setPatient(patient);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patient);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patient, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), ct.getVoice(), agent);
//        users.put(patient, 0);//+ " "+(tempPatient.getSex()==1?"(男 ":"(女 ") + IdCardUtil.getAgeForIdcard(tempPatient.getIdcard())+")"
//        String sessionId = patient + "_" + ct.getTeam() + "_" + ct.getType();
//        JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_MUC);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        try {
//            //发送图片
//            if (StringUtils.isNotBlank(ct.getVoice())) {
//                String voices[] = ct.getVoice().split(",");
//                String tims[] = times.split(",");
//                for (int i = 0; i < voices.length; i++) {
//                    String voice = voices[i];
//                    JSONObject json = new JSONObject();
//                    json.put("path", voice);
//                    json.put("times", tims[i]);
//                    ImUtill.sendImMsg(patient, tempPatient.getName(), sessionId, "3", json.toString(), "1");
//                }
//                jdbcTemplate.update("update " + imdb + ".topics set reply=0,reply_time=null,reply_message_id=null,reply_user=null where id = '" + consult.getCode() + "' ");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patient.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//
//    }
    /**
     * 添加续方咨询
     *
     * @param signTag      0为家签 1为非家签
     * @param hospital     机构CODE
     * @param hospitalName 机构名称
     * @param adminTeamId  机构名称
     */
//    public Integer addPrescriptionConsult(String jwCode, String patient, String agent, String doctorCode, ConsultTeam ct,
//                                          String reason, Integer type, String addressJson, int dispensaryType, Integer signTag,
//                                          String hospital, String hospitalName, Long adminTeamId, String systolic,
//                                          String diastolic, String bloodSugar, String bloodSugarType, String rateType) throws Exception {
//
//        synchronized (jwCode.intern()) {
//            String check = prescriptionInfoService.presCheckState(jwCode);
//            if ("0".equals(check)) {//存在未审核的续方
//                return -1;
//            }
//
//            Doctor doctor = doctorDao.findByCode(doctorCode);
//            if (signTag == null) {
//                signTag = 0;
//            }
//            //非家签 下线非家签可续方
////            if(1 == signTag){
////                ct.setAdminTeamId(adminTeamId);
////            }else{
//            //家签
//            SignFamily signFamily = signFamilyDao.findByPatient(patient);
//            if (signFamily == null) {
//                return -2;
//            }
//
//            ct.setAdminTeamId(signFamily.getAdminTeamId());
//            doctor = doctorDao.findByAdminTeamId(signFamily.getAdminTeamId());
//            doctorCode = doctor.getCode();
//            adminTeamId = signFamily.getAdminTeamId();
////            }
//
//            // 查询患者信息
//            BasePatientDO  p = patientDao.findByCode(patient);
//
//            //1、获取基位处方详情(保存续方表、药品续方信息表、续方疾病类型表)
//            Prescription prescription = new Prescription();
//            //家签,非家签的标签
//            prescription.setSignTag(signTag);
//
//            prescription.setDiastolic(diastolic);
//            prescription.setSystolic(systolic);
//            prescription.setBloodSugar(bloodSugar);
//            prescription.setBloodSugarType(bloodSugarType);
//
//            prescription = savePrescription(prescription, jwCode, doctor, p, ct, reason, hospital, rateType);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("title", p.getName() + "申请续方");
//
//            //2、获取体征记录
//            List<PatientDevice> devices = patientDeviceDao.findByPatient(patient);
//            if (devices != null && devices.size() > 0) {
//                int count = messageDao.findTzMessage(patient);
//                jsonObject.put("tzMsg", "最近七天有" + count + "条异常记录");
//            } else {
//                jsonObject.put("tzMsg", "居民未绑定体征设备");
//            }
//            //3、获取上次续方时间:与平安的“智慧医保的审方系统”对接,判断居民上次续方时间,点击跳转上次续方记录。(此功能需与第三方系统对接,如果本次版本无法实现,则消息中不显示此条信息)
//            jsonObject.put("lastTime", "");
//
//            String content = jsonObject.toString();
//
//            //4、创建咨询
//            JSONObject users = new JSONObject();//咨询参与者
//            users.put(patient, 0);
//            users.put(doctorCode, 0);
//            if (patient.equals(agent)) {
//                agent = null;
//            }
//            //关联业务code
//            ct.setRelationCode(prescription.getCode());
//            //医生信息
//            ct.setDoctor(doctorCode);
//            ct.setDoctorName(doctor.getName());
//            // 设置患者信息
//            ct.setPatient(patient);
//            if (1 == type) {
//                ct.setSymptoms("高血压");
//            } else if (2 == type) {
//                ct.setSymptoms("糖尿病");
//            } else if (3 == type) {
//                ct.setSymptoms("高血压,糖尿病");
//            } else if (4 == type) {
//                ct.setSymptoms("其他疾病");
//            }
//
//            // 设置患者姓名
//            ct.setName(p.getName());
//            // 设置患者生日
//            ct.setBirthday(p.getBirthday());
//            //新增性别
//            ct.setSex(p.getSex());
//            // 设置患者头像
//            ct.setPhoto(p.getPhoto());
//            // 设置操作日期
//            ct.setCzrq(new Date());
//            ct.setDel("1");
//            ct.setStatus(0);
//            ct.setEvaluate(0);
//            // 医生未读数量为1
//            ct.setDoctorRead(1);
//            // 添加咨询记录
//            Consult consult = addConsult(ct.getPatient(), "申请续方", ct.getSymptoms(), ct.getImages(), ct.getType());
//            // 设置关联指导
//            consult.setGuidance(ct.getGuidance());
//            //关联业务code
//            consult.setRelationCode(prescription.getCode());
//            // 设置咨询标识
//            ct.setConsult(consult.getCode());
//
//            //推送给IM去创建议题,取得成员消息
//            JSONObject messages = ImUtill.getCreateTopicMessage(patient, p.getName(), consult.getTitle(), content, consult.getImages(), agent);
//
//            //5、(im创建咨询) 续方咨询的sessionid为居民code+续方code+咨询类型
//            String sessionId = patient + "_" + consult.getCode() + "_" + ct.getType();
//            JSONObject obj = ImUtill.createTopics(sessionId, consult.getCode(), p.getName(), users, messages, ImUtill.SESSION_TYPE_PRESCRIPTION);
//            if (obj == null) {
//                throw new ServiceException("IM消息发送异常!");
//            }
//            if (obj.getInt("status") == -1) {//im议题创建失败
//                throw new ServiceException(obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//            consultTeamDao.save(ct);
//            consultDao.save(consult);
//
//            //设置咨询code
//            prescription.setConsult(consult.getCode());
//            prescription.setViewSuifang(0);
//            prescription.setViewWenjuan(0);
//            prescription.setViewXufang(0);
//            prescription.setViewChufang(0);
//            prescription.setViewTizhen(0);
//            prescription.setViewJiancha(0);
//            prescriptionDao.save(prescription);
//
//            //6、记录咨询的医生详情
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(doctorCode);
//            consultTeamDoctorDao.save(cd);
//
//            //7、发送系统消息提示团队长有未审核的消息
//            addCheckMessage(prescription, sessionId, p);
//
//            //8、 保存医生咨询信息
//            // 添加咨询转发记录
//            // 添加医生咨询日志
//            addLogs(ct);
//
//            Patient patientObj = patientDao.findByCode(patient);
//
//            //9、添加续方的随访记录
//            Followup followup = new Followup();
//            followup.setFollowupDate(new Date());
//            followup.setFollowupPlanDate(new Date());
//            followup.setDoctorCode(doctorCode);
//            followup.setDoctorName(doctor.getName());
//            followup.setOrgCode(doctor.getHospital());
//            followup.setOrgName(doctor.getHospitalName());
//            followup.setPatientCode(patient);
//            followup.setPatientName(patientObj.getName());
//            followup.setIdcard(patientObj.getIdcard());
//
//            if (3 == type) {
//                followup.setFollowupClass("1,2");
//            } else {
//                followup.setFollowupClass(String.valueOf(type));
//            }
//
//            followup.setFollowupType("1");//门诊随访
//
//            followup.setDataFrom("2");//数据来源 1基卫 2APP
//            followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
//            followup.setCreateTime(new Date());
//            followup.setCreater(doctorCode);
//            followup.setAdminTeamCode(adminTeamId);
//            followup.setSignType(2);
//            //保存质询code
//            followup.setSignCode(patientService.getSignCodeByPatient(patient));
//            followup.setPrescriptionCode(prescription.getCode());
//            followupDao.save(followup);
//
//
//            PrescriptionExpressage expressage = expressageDao.findByPrescriptionPay(prescription.getCode());
//            if (expressage == null) {
//                expressage = new PrescriptionExpressage();
//                expressage.setCode(getCode());
//            }
//            expressage.setPrescriptionCode(prescription.getCode());
//            com.alibaba.fastjson.JSONObject addressInfo = JSON.parseObject(addressJson);
//
//            String phone = addressInfo.getString("phone");
//            expressage.setMobile(phone);//收货人手机号码
////        配药机构信息(签约机构)
//            expressage.setHospitalCode(prescription.getHospital());
//            expressage.setHospitalName(prescription.getHospitalName());
////            expressage.setHospitalAddress(signAddress);
//
//            //微信登录患者信息
//            String userName = p.getName();
//            String userProvince = p.getProvince();
//            String userProvinceName = p.getProvinceName();
//            String userCity = p.getCity();
//            String userCityName = p.getCityName();
//            String userTown = p.getTown();
//            String userTownName = p.getTownName();
//            String userStreet = p.getStreet();
//            String userStreetName = p.getStreetName();
//            String userAddress = p.getAddress();
//            switch (dispensaryType) {
//                case 1:
//                    prescription.setDispensaryType(1);//取药类型:1 自取 2快递配送 3健管师配送
//                    //自取保存居民信息
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 2:
//                    prescription.setDispensaryType(2);//取药类型:1 自取 2快递配送 3健管师配送
//                    //快递保存信息
//                    String name = addressInfo.getString("receiver");
//                    String proviceCode = addressInfo.getString("provinceCode");
//                    String proviceName = addressInfo.getString("provinceName");
//                    String cityCode = addressInfo.getString("cityCode");
//                    String cityName = addressInfo.getString("cityName");
//                    String townCode = addressInfo.getString("townCode");
//                    String townName = addressInfo.getString("townName");
//                    String streeCode = addressInfo.getString("streeCode");
//                    String streeName = addressInfo.getString("streeName");
//                    String address = addressInfo.getString("address");
//
//                    expressage.setName(name);//居民姓名
//                    expressage.setProvinceCode(proviceCode);//省代码
//                    expressage.setProvinceName(proviceName);//省名称
//                    expressage.setCityCode(cityCode);//市代码
//                    expressage.setCityName(cityName);//市名称
//                    expressage.setTownCode(townCode);//区code
//                    expressage.setTownName(townName);//区名称
//                    expressage.setStreetCode(streeCode);//街道code
//                    expressage.setStreetName(streeName);//街道名称
//                    expressage.setAddress(address);//居民详细地址
//
//                    expressage.setExpressageHospitalName("顺丰快递");
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 3:
//                    prescription.setDispensaryType(3);//取药类型:1 自取 2快递配送 3健管师配送
//                    //健管师配送
//                    expressage.setName(userName);//居民姓名
//                    expressage.setProvinceCode(userProvince);//省代码
//                    expressage.setProvinceName(userProvinceName);//省名称
//                    expressage.setCityCode(userCity);//市代码
//                    expressage.setCityName(userCityName);//市名称
//                    expressage.setTownCode(userTown);//区code
//                    expressage.setTownName(userTownName);//区名称
//                    expressage.setStreetCode(userStreet);//街道code
//                    expressage.setStreetName(userStreetName);//街道名称
//                    expressage.setAddress(userAddress);//居民详细地址
//
//                    //居民选择的要送达的服务站
//                    String userOrgCode = addressInfo.getString("code");
//                    String userOrgName = addressInfo.getString("name");
//                    String userOrgAddress = addressInfo.getString("address");
//                    expressage.setPatientHospitalCode(userOrgCode);
//                    expressage.setPatientHospitalName(userOrgName);
//                    expressage.setPatientHospitalAddress(userOrgAddress);
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(0);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//                case 4:
//                    prescription.setDispensaryType(4);//取药类型:1 自取 2快递配送 3健管师配送 4网格员派送
//
//                    expressage.setName(addressInfo.getString("receiver"));//居民姓名
//                    expressage.setProvinceCode(addressInfo.getString("provinceCode"));//省代码
//                    expressage.setProvinceName(addressInfo.getString("provinceName"));//省名称
//                    expressage.setCityCode(addressInfo.getString("cityCode"));//市代码
//                    expressage.setCityName(addressInfo.getString("cityName"));//市名称
//                    expressage.setTownCode(addressInfo.getString("townCode"));//区code
//                    expressage.setTownName(addressInfo.getString("townName"));//区名称
//                    expressage.setStreetCode(addressInfo.getString("streeCode"));//街道codestreetCode
//                    expressage.setStreetName(addressInfo.getString("streeName"));//街道名称
//                    expressage.setAddress(addressInfo.getString("address"));//居民详细地址
//
//                    expressage.setCreateTime(new Date());//创建时间
//                    expressage.setOneselfPickupFlg(1);//是否自取 1是 0否
//                    expressage.setDel(1);//有效
//                    break;
//            }
//
//            //保存物流信息
//            expressageDao.save(expressage);
//
//            return 1;
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addCheckMessage(Prescription prescription, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(prescription.getDoctor());
//        message.setSender(prescription.getPatient());
//        message.setCode(getCode());
//        message.setSenderName(prescription.getPatientName());
//        message.setTitle(prescription.getPatientName() + "申请续方");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(6);//续方咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(prescription.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(prescription.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 保存续方信息
     */
//    public Prescription savePrescription(Prescription prescription, String jwCode, Doctor doctor, Patient p, ConsultTeam ct, String reason, String hospital, String ratType) throws Exception {
//        //获取智业处方详细
//        String response = jwPrescriptionService.getRecipe(jwCode, p.getSsc(), null, hospital);
//        com.alibaba.fastjson.JSONObject jsonObject = presModeAdapter.modelToSinglePrescription(response);
//
//        //续方主表
//        prescription.setCode(getCode());
//        prescription.setParentCode(jwCode);
//        prescription.setHospitalName(doctor.getHospitalName());
//        prescription.setHospital(doctor.getHospital());
//        prescription.setAdminTeamId(ct.getAdminTeamId());
//        prescription.setCreateTime(new Date());
//        prescription.setDept(doctor.getDept());
//        prescription.setDeptName(doctor.getDeptName());
//        prescription.setDoctor(doctor.getCode());
//        prescription.setDoctorName(doctor.getName());
//        prescription.setJwCode(jwCode);
//        prescription.setPatient(p.getCode());
//        prescription.setPatientName(p.getName());
//        prescription.setSsc(p.getSsc());
//        prescription.setReason(reason);
//        prescription.setType(2);
//        prescription.setStatus(PrescriptionLog.PrescriptionLogStatus.revieweding.getValue());
//        prescription.setConsult(ct.getConsult());
//        prescription.setJwPayStatus(0);//处方结算状态,0为未结算,1为结算成功,默认为0
//        prescription.setZyCancelState(0);//智业取消状态
//        //保存智业的医生信息
//        Map<String, Object> map = zyDictService.findJwDoctorByDoctor(doctor.getCode());
//        if (map != null) {
//            prescription.setJwDoctorCode(map.get("jw_doctor").toString());
//            prescription.setJwHospital(map.get("jw_doctor_hospital").toString());
//        }
//        //设置费别类型
//        prescription.setJwRateTypeCode(zyDictService.getRateType(ratType));
//        prescription.setPresCreateTime(DateUtil.stringToDate(jsonObject.getString("createTime"), "yyyy-MM-dd"));
//
//
//        //保存续方药品(处方)信息
//        com.alibaba.fastjson.JSONArray infos = jsonObject.getJSONArray("prescriptionInfo");
//        int day = 0;
//        if (infos != null && infos.size() > 0) {
//            day = infos.getJSONObject(0).getInteger("dayCount");
//        }
//        for (int i = 0; i < infos.size(); i++) {
//            com.alibaba.fastjson.JSONObject info = infos.getJSONObject(i);
//            PrescriptionInfo prescriptionInfo = new PrescriptionInfo();
//            prescriptionInfo.setPrescriptionCode(prescription.getCode());
//            prescriptionInfo.setCode(getCode());
//            prescriptionInfo.setDel(1);
//            prescriptionInfo.setDirection(info.getString("USAGE_NAME"));//药品用法
//            prescriptionInfo.setDrugCode(info.getString("drugCode"));//药品code
//            prescriptionInfo.setDrugName(info.getString("drugName"));//药品名称
//            prescriptionInfo.setDrugRate(info.getString("drugRate"));//吃药频率
//            prescriptionInfo.setDrugRateName(getZyCommonDictName(info.getString("drugRate")));
//            prescriptionInfo.setDrugFormat(info.getString("drugFormat"));//药品规格
//            prescriptionInfo.setNum(info.getInteger("num"));//药品数目
//            prescriptionInfo.setPrice(CommonUtil.doubleToInt(info.getDouble("price")));//药品单价
////            prescriptionInfo.setIsRefrigerate(0);//是否冷藏 1是 0否
//            prescriptionInfo.setJwSubCode(info.getString("jwSubCode"));//智业子处方号
//
//            prescriptionInfo.setDrugNumUnit(info.getString("drugNumUnit"));//数量单位编码
//            prescriptionInfo.setDrugNumUnitName(info.getString("drugNumUnitName"));//数量单位名称
//            prescriptionInfo.setCost(CommonUtil.doubleToInt(info.getDouble("cost")));//金额
//            prescriptionInfo.setCharge(CommonUtil.doubleToInt(info.getDouble("charge")));//自付
//            prescriptionInfo.setBindFlag(info.getString("bindFlag"));//成组标志, 0.非成组,1.成组
//            prescriptionInfo.setDayCount(info.getInteger("dayCount"));//用药天数
//            //设置最小用药天数
//            if (prescriptionInfo.getDayCount() != null && prescriptionInfo.getDayCount() < day) {
//                day = prescriptionInfo.getDayCount();
//            }
//            prescriptionInfo.setDrugUsage(info.getString("drugUsage"));//用药方法编码
//            prescriptionInfo.setUsageName(info.getString("usageName"));//用药方法名称
//            prescriptionInfo.setPhysicDose(info.getString("physicDose"));//用药剂量
//            prescriptionInfo.setPhysicDoseUnit(info.getString("physicDoseUnit"));//剂量单位编码
//            prescriptionInfo.setPhysicDoseUnitName(info.getString("physicDoseUnitName"));//剂量单位名称
//            prescriptionInfo.setPhysicInjectPlace(info.getString("physicInjectPlace"));//注射地点编码
//            prescriptionInfo.setPhysicInjectPlaceName(info.getString("physicInjectPlaceName"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTest(info.getString("physicSkinTest"));//注射地点名称
//            prescriptionInfo.setPhysicSkinTestName(info.getString("physicSkinTestName"));//皮试类型名称
//            prescriptionInfo.setRemark(info.getString("Remark"));//备注
//            //需要特殊处理的字段
//            ZyIvPhysicDict physicDict = zyDictService.findByPhysicCode(prescriptionInfo.getDrugCode());
//            String subjectClass = info.getString("subjectClass");//科目类型
//            String physicAmount = info.getString("physicAmount");//用药总量
//            String physicAmountUnit = info.getString("physicAmountUnit");//总量单位编码
//            String physicAmountUnitName = info.getString("physicAmountUnitName");//总量单位名称
//            int isRefrigerate = 0;
//            if (physicDict != null) {
//                subjectClass = physicDict.getSubjectClass();
//                isRefrigerate = "2".equals(physicDict.getStorageConditions()) ? 1 : isRefrigerate;
//                physicAmount = null;
//                physicAmountUnit = physicDict.getPackUnit();
//                physicAmountUnitName = zyDictService.findByDictNameAndCode("IV_MEASURE_UNIT_DICT", physicAmountUnit);
//            }
//            prescriptionInfo.setPhysicAmount(physicAmount);
//            prescriptionInfo.setPhysicAmountUnit(physicAmountUnit);
//            prescriptionInfo.setPhysicAmountUnitName(physicAmountUnitName);
//            prescriptionInfo.setIsRefrigerate(isRefrigerate);
//            prescriptionInfo.setSubjectClass(subjectClass);//科目编码
//
//            prescriptionInfoDao.save(prescriptionInfo);
//        }
//        //设置最小用药天数
//        prescription.setMinDrugDay(day);
//        //保存续方记录
//        prescriptionDao.save(prescription);
//
//
//        //保存续方疾病类型
//        com.alibaba.fastjson.JSONArray jaDiagnosis = jsonObject.getJSONArray("prescriptionDt");
//        for (Iterator iterator = jaDiagnosis.iterator(); iterator.hasNext(); ) {
//            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) iterator.next();
//            PrescriptionDiagnosis diagnosis = new PrescriptionDiagnosis();
//            diagnosis.setCode(json.getString("code"));
//            diagnosis.setPrescriptionCode(prescription.getCode());
//            diagnosis.setCreateTime(new Date());
//            diagnosis.setName(json.getString("name"));
//            diagnosis.setHealthProblemName(json.getString("healthProblemName"));
//            diagnosis.setHealthProblem(json.getString("healthProblem"));
//            diagnosis.setUpdateTime(new Date());
//            prescriptionDiagnosisDao.save(diagnosis);
//        }
//
//        //保存审核信息
//        PrescriptionReviewed reviewed = new PrescriptionReviewed();
//        reviewed.setPrescriptionCode(prescription.getCode());
//        reviewed.setCode(getCode());
//        reviewed.setStatus(PrescriptionReviewed.PrescriptionReviewedStatus.reviewed_wait.getValue());
//        reviewed.setCreateTime(new Date());
//        reviewed.setDoctor(prescription.getDoctor());
//        reviewed.setDoctorName(prescription.getDoctorName());
//        reviewed.setHospital(prescription.getHospital());
//        reviewed.setHospitalName(prescription.getHospitalName());
//        prescriptionReviewedDao.save(reviewed);
//
//        //添加保存日志
//        prescriptionLogService.addLog(prescription, PrescriptionLog.PrescriptionLogType.create.getValue(), 1, 1);
//
//        return prescription;
//    }
    public String getZyCommonDictName(String code) {
        try {
            String sql = "SELECT t.name FROM zy_common_dict t WHERE t.code=? AND t.dict_name='IV_RECIPE_FREQUENCY_DICT'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{code});
            if (list != null && list.size() > 0) {
                return (String) (list.get(0).get("name"));
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendIM(String from, String to, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/pm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("to", to));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    private String sendGroupIM(String from, String groupCode, String contentType, String content) {
        String imAddr = im_list_get + "api/v1/chats/gm";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("group", groupCode));
        params.add(new BasicNameValuePair("groupType", "1"));
        params.add(new BasicNameValuePair("contentType", contentType));
        params.add(new BasicNameValuePair("content", content));
        String response = httpClientUtil.post(imAddr, params, "UTF-8");
        return response;
    }
    /**
     * 添加三师咨询日志
     */
//    private String addLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //先判断从健康指导转咨询是否存在指导。
//            JSONObject json = guidanceService.findById(ct.getGuidance());
//
//            if (json == null) {
//                //再判断从健康教育文章转咨询是否存在文章 20170602
//                HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//                if (article != null) {
//                    return verdictAddLogs(ct);
//                }
//                throw new ServiceException("健康指导不存在");
//            } else {
//                //  健康指导转咨询的指导内容
//                content += "医生" + (json.get("doctorName") != null ? json.get("doctorName").toString() : "")
//                        + "发出的指导:" + (json.getString("content") != null ? json.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLog infoLog = new ConsultTeamLog();
//        infoLog.setConsult(ct.getConsult());
//        if (content.length() > 2500) {
//            content = content.substring(0, 2500);
//        }
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLog imgLog = new ConsultTeamLog();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLog voiceLog = new ConsultTeamLog();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLog> iterable = consultTeamLogDao.save(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 添加三师咨询日志(增加咨询来源是否存在判断)
     */
//    private String verdictAddLogs(ConsultTeamDo ct) {
//        List<ConsultTeamLogDo> logs = new ArrayList<>();
//        // 添加问题咨询日志
//        String content = "";
//
//        if (ct.getGuidance() != null && ct.getGuidance() > 0) {
//            //再判断从健康教育文章转咨询是否存在文章 20170602
//            HealthEduArticle article = healthEduArticleService.findArticleById(ct.getGuidance());
//            if (article == null) {
//                throw new RuntimeException("健康教育文章不存在!");
//            } else {
//                //  健康指导转咨询的指导内容
//                JSONObject jsonArticle = new JSONObject();
//
//                jsonArticle.put("doctorName", ct.getDoctorName() != null ? ct.getDoctorName() : "");
//                jsonArticle.put("content", article.getSummary() != null ? article.getSummary() : "");
//                jsonArticle.put("czrq", article.getCzrq() != null ? DateUtil.dateToStr(article.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM) : "");
//
//                content += "医生" + (jsonArticle.get("doctorName") != null ? jsonArticle.get("doctorName").toString() : "")
//                        + "发出的文章:" + (jsonArticle.getString("content") != null ? jsonArticle.getString("content") : "") + "<br/>";
//            }
//
//        }
//
//        content += "咨询问题:" + (StringUtils.isEmpty(ct.getSymptoms()) ? "无" : ct.getSymptoms());
//
//        // 生成提问日志,并推送相关消息
//        ConsultTeamLogDo infoLog = new ConsultTeamLogDo();
//        infoLog.setConsult(ct.getConsult());
//        infoLog.setContent(content);
//        infoLog.setDel("1");
//        infoLog.setType(0);
//        infoLog.setChatType(1);
//        infoLog.setCzrq(new Date());
//        logs.add(infoLog);
//        // 图片日志
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ConsultTeamLogDo imgLog = new ConsultTeamLogDo();
//                    // 设置咨询标识
//                    imgLog.setConsult(ct.getConsult());
//                    // 设置图片URL
//                    imgLog.setContent(image);
//                    imgLog.setDel("1");
//                    infoLog.setType(0);
//                    imgLog.setCzrq(new Date());
//                    // 图片类型
//                    imgLog.setChatType(2);
//                    // 添加到待保存队列
//                    logs.add(imgLog);
//                }
//            }
//        }
//        // 语音日志
//        if (StringUtils.isNotEmpty(ct.getVoice())) {
//            ConsultTeamLogDo voiceLog = new ConsultTeamLogDo();
//            // 设置咨询标识
//            voiceLog.setConsult(ct.getConsult());
//            // 设置语音URL
//            voiceLog.setContent(ct.getVoice());
//            voiceLog.setDel("1");
//            infoLog.setType(0);
//            // 语音类型
//            voiceLog.setChatType(3);
//            voiceLog.setCzrq(new Date());
//            // 添加到待保存队列
//            logs.add(voiceLog);
//        }
//        if (!logs.isEmpty()) {
//            Iterable<ConsultTeamLogDo> iterable = consultTeamLogDao.saveAll(logs);
//            if (iterable == null || !iterable.iterator().hasNext()) {
//                // 日志保存失败
//                throw new RuntimeException("咨询日志保存失败!");
//            }
//        }
//        return content;
//    }
    /**
     * 查询咨询列表
     *
     * @param patientCode 患者标志
     * @param status      咨询状态(0未结束,1已结束,-1 已取消)
     * @param pageSize    页数
     */
//    public Page<ConsultTeamDo> findByPatient(String patientCode, int status, long id, int pageSize) {
//        if (id < 0) {
//            id = 0;
//        }
//        if (pageSize <= 0) {
//            pageSize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
//
//        Page<ConsultTeamDo> list = null;
//        switch (status) {
//            case 0:
//                // 未结束
//                if (id > 0) {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findNotFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case 1:
//                // 已结束
//                if (id > 0) {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findFinishedBypatient(patientCode, pageRequest);
//                }
//                break;
//            case -1:
//                // 已取消
//                if (id > 0) {
//                    list = consultTeamDao.findCancelBypatient(patientCode, id, pageRequest);
//                } else {
//                    list = consultTeamDao.findCancelBypatient(patientCode, pageRequest);
//                }
//                break;
//        }
//        return list;
//    }
    /**
     * 医生关闭三师咨询(续方咨询)
     *
     * @param consult 三师咨询标识
     */
//    public int finish(String consult, String endOperator, int endType) throws Exception {
//
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String name = "";
//        String returnJson = "";
//        //推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            name = p.getName();
//            returnJson = sendIM(consultTeam.getPatient(), consultTeam.getDoctor(), "7", name + "结束了本次咨询");
//        } else {
//            Doctor d = doctorDao.findByCode(endOperator);
//            name = d.getName();
//            returnJson = sendIM(consultTeam.getDoctor(), consultTeam.getPatient(), "7", name + "结束了本次咨询");
//        }
//
//        if (StringUtils.isEmpty(returnJson)) {
//            throw new ServiceException("send consult finished IM message failed");
//        } else {
//            JSONObject jo = new JSONObject(returnJson);            //设置消息ID
//            consultTeam.setEndMsgId(jo.getInt("startId") + "");
//            consultTeam.setEndOperator(endOperator);
//            consultTeam.setEndType(endType);
//        }
//
//        JSONObject group = talkGroupService.findConsultTalkGroup(consultTeam.getConsult());
//
//        if (group != null) {
//            String json = sendGroupIM(endOperator, group.getString("code"), "7", name + "结束了本次咨询");
//
//            if (StringUtils.isEmpty(json)) {
//                throw new ServiceException("send consult finished IM message failed");
//            }
//        }
//
//        return consultTeamDao.updateStatusByConsult(consult);
//    }
                content = "一条消息";
            }
            String url = temp.getUrl() + "&openid=" + p.getOpenid() + "&peerId=" + doctor + "&peerName=" + doctorName;
            json.put("consultcontent", temp.getKeyword1());
            json.put("replycontent", content);
            json.put("doctorName", doctorName);
            json.put("remark", "");
            json.put("url", url);
            pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 3, p.getOpenid(), p.getName(), json);
        }
    }
    /**
     * 设置咨询已读
@ -2171,12 +191,6 @@ public class ConsultTeamService extends ConsultService {
        return 1;
    }
    /**
     * 取消三师咨询
     */
//    public int cancel(String consult) {
//        return consultTeamDao.cancel(consult);
//    }
    public ConsultTeamDo findByCode(String code) {
        return consultTeamDao.findByConsult(code);
    }
@ -2185,208 +199,11 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamDao.findById(id).orElse(null);
    }
    /**
     * 三师咨询转接医生
     *
     * @param from    转出医生标识
     * @param to      转入医生标识
     * @param consult 三师咨询标识
     */
//    public void transfer(String from, String to, String consult) {
//        // 检查是否存在
//        if (consultTeamDoctorDao.isExist(consult, to) == 0) {
//            ConsultTeam ct = consultTeamDao.findByConsult(consult);
//            int count = consultTeamLogDao.countByConsult(consult);
//            // 设置未读消息数
//            ct.setDoctorRead(count);
//            consultTeamDao.save(ct);
//            // 查询医生信息
//            Doctor d = doctorDao.findByCode(from);
//            // 再保存
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult);
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setFrom(d.getCode());
//            cd.setFromName(d.getName());
//            cd.setTo(to);
//            consultTeamDoctorDao.save(cd);
//        }
//    }
    /**
     * 查询患者视频和三师咨询记录
     */
//    public Page<ConsultDo> findConsultRecordByPatientType(String patient, long id, int pagesize) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "id");
//        // 分页信息
//        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//        // 设置查询条件
//        Map<String, SearchFilter> filters = new HashMap<>();
//        filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//        filters.put("type", new SearchFilter("type", Operator.LT, 3));
//        if (id > 0) {
//            filters.put("id", new SearchFilter("id", Operator.LT, id));
//        }
//        // 未作废
//        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//        Specification<Consult> spec = DynamicSpecifications.bySearchFilter(filters.values(), Consult.class);
//        return consultDao.findAll(spec, pageRequest);
//    }
    /**
     * 清空医生未读数量
     */
//    public void clearDoctorRead(String consult) {
//        consultTeamDao.clearDoctorRead(consult);
//    }
    /**
     * 查询医生的咨询统计
     */
//    public Map<String, Long> getAllCount(String doctorCode) {
//        Map<String, Long> result = new HashMap<>();
//
//        //根据医生code查询总咨询数
//        long allCount = consultTeamDoctorDao.getAllCountByDoctorCode(doctorCode);
//
//        //根据医生code查询今日咨询数
//        long todayCount = consultTeamDoctorDao.getTodayCountByDoctorCode(doctorCode);
//
//        result.put("all", allCount);
//        result.put("today", todayCount);
//
//        return result;
//    }
    /**
     * 查找未完成咨询
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient) {
//        return consultTeamDao.findUnfinishedConsult(patient);
//    }
//    public List<ConsultHelp> findUnfinishedByPatientAndSpecialist(String patient, String doctor) {
//        return consultHelpDao.findUnfinishedByPatientAndSpecialist(patient, doctor);
//    }
    /**
     * 查询居民与某个医生未结束的咨询
     *
     * @param patient 居民
     * @param doctor  医生
     */
//    public List<ConsultTeamDo> getUnfinishedConsult(String patient, String doctor) {
//        return consultTeamDao.findUnfinishedConsultType(patient, doctor);
//    }
    /**
     * 查询患者全部的咨询数目
     */
//    public Integer findByDoctorSize(String patientCode, String doctorCode) {
//
//        return consultDao.findByPatient(patientCode, doctorCode);
//    }
    public List<Map<String, Object>> getConsultSign(String[] consults) {
        String params = "";
        List<String> paramList = new ArrayList<>();
        for (int i = 0; i < consults.length; i++) {
            params += (i == 0 ? "?" : ",?");
        }
        paramList.addAll(Arrays.asList(consults));
        paramList.addAll(Arrays.asList(consults));
        String sqlgp = "select DISTINCT consult,to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlgpm = "select DISTINCT to_doctor from wlyy_consult_team_doctor ctd,wlyy_doctor d where ctd.to_doctor = d.code and d.level = 2 and ctd.consult in (" + params + ") and ctd.del = '1'";
        String sqlQu = "select * from wlyy_quota_result where qkdoctor_code in (" + sqlgpm + ") and quato_code = '1' and level1_type = '1'";
        String sqlQuSum = "select a.consult,sum(ifnull(b.result,0)) sign from (" + sqlgp + ") a left join (" + sqlQu + ") b on a.to_doctor = b.qkdoctor_code group by a.consult ";
        return jdbcTemplate.queryForList(sqlQuSum, paramList.toArray());
    }
    public ConsultTeamLogDo oneLog(Long logId) {
        return consultTeamLogDao.findById(String.valueOf(logId)).orElse(null);
    }
//    public boolean isExistConsult(String uid, String doctor) {
//        int consultTeam = consultTeamDao.countByPatient(uid, 2, doctor);
//        return consultTeam > 0;
//    }
    /**
     * 进入咨询
     */
//    public int intoTopic(String consult, String patient, String agent) throws Exception {
//        ConsultTeamDo ct = consultTeamDao.findByConsult(consult);
//        if (ct.getStatus() != 0) {
//            return -1;
//        }
//
//        String content = "进入了咨询";
//        BasePatientDO  p = patientDao.findById(patient);
//        String intoUserName = p.getName();
//        if (patient.equals(agent)) {
//            content = intoUserName + content;
//        } else {
//            PatientFamilyMember familyMember = familyMemberDao.findByPatientAndFamilyMember(patient, agent);
//            Patient member = patientDao.findByCode(agent);
//            content = member.getName() + "(" + relations.get(familyMember.getFamilyRelation()) + ")" + content;
//        }
//
//        imUtil.sendIntoTopicIM(ct.getPatient(), ct.getPatient(), ct.getConsult(), content, agent, intoUserName);
//
//        return 0;
//    }
    /**
     * 根据健康管理师和患者 找到正在进行中的咨询
     */
//    public ConsultTeam getConsultByPatientAndDoctor(String patientCode, String doctor) {
//        ConsultTeam consultTeam = consultTeamDao.findByParientCodeAndSignTypeAndDoctor(patientCode, doctor, 2);
//        return consultTeam;
//    }
//    public List<String> getConsultListByPatientAndDoctor(String doctor) throws Exception {
//        List<String> list = consultTeamDao.findParientListByDoctor(doctor);
//        return list;
//    }
//    public void transfers(String uid, String doctor, String consult) {
//        String[] doctors = doctor.split(",");
//        for (int i = 0; i < doctors.length; i++) {
//            transfer(uid, doctors[i], consult);
//        }
//    }
//    public String produceConsultAdminTeamCode() {
//        StringBuffer sf = new StringBuffer();
//        StringBuffer sf1 = new StringBuffer();
//        long size = 0L;
//        //找出家庭签约中团队code是空的
//        List<ConsultTeamDo> consultTeams = consultTeamDao.findByTypeAndAdminTeamIdIsNull(2);
//        sf.append("家庭签约咨询中团队code是空的数据数:" + consultTeams.size());
//        for (ConsultTeam consultTeam : consultTeams) {
//            //得到签约中的全科医生的团队
//            SignFamily signfamily = signFamilyDao.findByjiatingPatient(consultTeam.getPatient());
//            if (signfamily != null) {
//                if (signfamily.getAdminTeamId() != null && signfamily.getAdminTeamId() > 0) {
//                    consultTeam.setAdminTeamId(signfamily.getAdminTeamId());
//                    size++;
//                }
//            } else {
//                sf1.append(",找不到医生所属的团队,家庭签约咨询的Id:" + consultTeam.getId());
//            }
//        }
//        sf.append(",填充团队的签约数据数:" + size);
//        sf.append(sf1);
//        return sf.toString();
//    }
    public void save(ConsultTeamDo consult) {
        consultTeamDao.save(consult);
    }
@ -2395,675 +212,6 @@ public class ConsultTeamService extends ConsultService {
        return consultTeamDao.findByConsult(consultCode);
    }
//    public List<ConsultTeamLogDo> getConsultLog(String consultCode) {
//        return consultTeamLogDao.getConsultLogByConsultLog(consultCode);
//    }
//    public void addForHelpTeamConsult(ConsultTeamDo ct, String uid, String oldConsultCode) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        BaseDoctorDO doctorTemp = doctorDao.findById(uid);
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        String returnJson = null;
//        JSONObject jo;
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        if (StringUtils.isEmpty(returnJson))
//            returnJson = sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        else
//            sendIM(ct.getPatient(), ct.getDoctor(), "6", content);
//        jo = new JSONObject(returnJson);
//        //设置消息ID
//        ct.setStartMsgId(jo.getInt("startId") + "");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public void sendForHelpMsg(ConsultTeam ct, String uid, String oldConsultCode) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ConsultTeam oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null) {
//                sendIM(ct.getPatient(), ct.getDoctor(), "6", "居民问题:" + oldConsult.getSymptoms());
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                        }
//                    }
//                }
//            }
//        }
//        sendIM(ct.getPatient(), ct.getDoctor(), "6", "咨询问题:" + ct.getSymptoms());
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    sendIM(ct.getPatient(), ct.getDoctor(), "2", image);
//                }
//            }
//        }
//    }
//    public List<ConsultTeamDo> hasUnfinished(String doctorCode, String uid) {
//        return consultTeamDao.findUnfinishedConsult(uid, doctorCode);
//    }
    /**
     * 判断两医生是否在同一团队内
     */
    public boolean isCommonTeam(String docCode1, String docCode2) {
        String sqlQuSum =
                "SELECT c.team_id FROM " +
                        "(SELECT a.* FROM wlyy_admin_team_member a where a.doctor_code='" + docCode1 + "' ) c " +
                        "LEFT JOIN " +
                        "(SELECT b.* FROM wlyy_admin_team_member b where b.doctor_code='" + docCode2 + "' ) d " +
                        "on c.team_id=d.team_id " +
                        "WHERE d.team_id IS NOT NULL";
        List ls = jdbcTemplate.queryForList(sqlQuSum);
        return ls != null && ls.size() > 0;
    }
    /**
     * 通过team获取医生code
     *
     * @param consult 关联的上一个咨询
     */
//    public List findByTeam(String consult) {
//        return consultTeamDao.findByTeamAndType(consult, 10);
//    }
    /**
     * 全科医生求助专科医生(同团队)
     *
     * @param isSend 是否转发患者咨询内容
     */
//    public void addSeekHelpTeam(ConsultTeamDo ct, String uid, String oldConsultCode, int isSend) {
//        ct.setPatient(uid);
//        //推送给IM文字消息
//        JSONObject participants = new JSONObject();
//        participants.put(ct.getPatient(), 0);
//        participants.put(ct.getDoctor(), 0);
//        BaseDoctorDO doctor = doctorService.findDoctorByCode(uid);
//        JSONObject sessionJson = imUtill.createSession(participants, imUtill.SESSION_TYPE_P2P, doctor.getName() + "发起求助!", "");
//        if (sessionJson.getString("status").equals("-1")) {
//            throw new RuntimeException(sessionJson.getString("message"));
//        }
//        JSONObject session = sessionJson.getJSONObject("data");
//        if (StringUtils.isNotEmpty(oldConsultCode)) {
//            ct.setTeam(oldConsultCode);
//            ConsultTeamDo oldConsult = consultTeamDao.findByConsult(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "居民问题:" + oldConsult.getSymptoms(), "1");
//                //推送给IM图片
//                if (StringUtils.isNotEmpty(oldConsult.getImages())) {
//                    String[] images = oldConsult.getImages().split(",");
//                    for (String image : images) {
//                        if (StringUtils.isNoneEmpty(image)) {
//                            imUtill.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                        }
//                    }
//                }
//            }
//            BaseDoctorDO doctorTemp = doctorDao.findById(ct.getDoctor());
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + "_consult_" + oldConsult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctorTemp.getName());
//            imUtill.sendTopicIM(doctor.getId(), doctor.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//
//
//        ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "1", "咨询问题:" + ct.getSymptoms(), "1");
//        //推送给IM图片
//        if (StringUtils.isNotEmpty(ct.getImages())) {
//            String[] images = ct.getImages().split(",");
//            for (String image : images) {
//                if (StringUtils.isNoneEmpty(image)) {
//                    ImUtil.sendImMsg(ct.getPatient(), ct.getDoctor(), session.getString("id"), "2", image, "1");
//                }
//            }
//        }
//    }
    /**
     * 全科医生求助专科医生(不同团队)
     */
//    public void addSeekHelpOtherTeam(ConsultTeam ct, String uid, String oldConsultCode, int isSend) throws Exception {
//        // 设置患者信息
//        ct.setPatient(uid);
//        Doctor doctorTemp = doctorDao.findByCode(uid);
//        Doctor doctor = doctorDao.findByCode(ct.getDoctor());
//        // 设置医生姓名
//        ct.setName(doctorTemp.getName());
//        // 设置医生生日
//        ct.setBirthday(doctorTemp.getBirthday());
//        //新增性别
//        ct.setSex(doctorTemp.getSex());
//        // 设置医生头像
//        ct.setPhoto(doctorTemp.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        if (StringUtils.isBlank(oldConsultCode)) {
//            JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, consult.getImages(), null);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put(ct.getPatient(), 0);
//            jsonObject.put(ct.getDoctor(), 0);
//            //设置消息ID
//            JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//            if (obj == null || obj.getInt("status") == -1) {
//                throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//            }
//            ct.setStartMsgId(obj.get("start_msg_id").toString());
//        } else {
//            //转发咨询问题
//            Consult oldConsult = consultDao.findByCode(oldConsultCode);
//            ConsultTeam consultTeam = consultTeamDao.findByConsult(oldConsultCode);
//            ct.setTeam(oldConsultCode);
//            if (oldConsult != null && isSend == 1) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), "居民问题:" + oldConsult.getSymptoms(), oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//                ct.setStartMsgId(obj.get("start_msg_id").toString());
//                Thread.sleep(100);//消息发送顺序问题处理
//                ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "6", content, null);
//                if (StringUtils.isNotBlank(consult.getImages())) {
//                    String imgs[] = consult.getImages().split(",");
//                    for (String url : imgs)
//                        ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), consult.getCode(), "2", url, null);
//                }
//            } else if (oldConsult != null && isSend == 0) {
//                JSONObject messages = ImUtill.getCreateTopicMessage(doctorTemp.getCode(), doctorTemp.getName(), consult.getTitle(), content, oldConsult.getImages(), null);
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put(ct.getPatient(), 0);
//                jsonObject.put(ct.getDoctor(), 0);
//                JSONObject obj = ImUtill.createTopics(null, consult.getCode(), doctorTemp.getName(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//                if (obj == null || obj.getInt("status") == -1) {
//                    throw new ServiceException("im消息创建异常!" + obj == null ? "" : obj.getString("message"));
//                }
//            }
//            JSONObject qiuzuObj = new JSONObject();
//            qiuzuObj.put("session_id", oldConsult.getPatient() + consultTeam.getTeam() + consult.getType());
//            qiuzuObj.put("patient", ct.getPatient());
//            qiuzuObj.put("old_consult_code", oldConsultCode);
//            qiuzuObj.put("doctor", ct.getDoctor());
//            qiuzuObj.put("doctor_name", doctor.getName());
//            ImUtill.sendTopicIM(doctorTemp.getCode(), doctorTemp.getName(), oldConsultCode, "5", qiuzuObj.toString(), null);
//        }
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//    }
//    public int finishConsult(String consult, String endOperator, int endType) throws Exception {
//        ConsultTeam consultTeam = consultTeamDao.findByConsult(consult);
//        Consult cons = consultDao.findByCode(consult);
//
//        if (consultTeam.getStatus() == 1) {
//            return -1;
//        }
//
//        //新增续方咨询结束判断 (续方未审核时不可由医生或居民关闭)
//        if (consultTeam.getType() == 8) {
//            Prescription prescription = prescriptionDao.findByCode(consultTeam.getRelationCode());
//            if (prescription.getStatus() == 0) {
//                return -2;
//            }
//        }
//
//        String endName = "";
//        String endId = "";
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            endId = p.getCode();
//        } else {
//            if (endOperator.equals("admin")) {
//                endId = "system";
//                endName = "咨询超时未回复,系统自动";
//            } else {
//                Doctor d = doctorDao.findByCode(endOperator);
//                endId = d.getCode();
//                endName = d.getName();
//            }
//        }
//
//        JSONObject obj = ImUtill.endTopics(consultTeam.getPatient(), endId, endName, consultTeam.getConsult());
//        if (obj == null) {
//            throw new ServiceException("IM消息结束异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(String.valueOf(obj.get("message")));
//        }
//
//        //结束咨询才发送推送给IM文字消息
//        if (endType == 1) {
//            BasePatientDO  p = patientDao.findByCode(endOperator);
//            endName = p.getName();
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (endName == null ? "" : endName));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = endName + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
////                first += "咨询已结束,请及时对咨询医生进行评价。";
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//            }
//        } else {
//            if (consultTeam.getType() == 2 || consultTeam.getType() == 8) {
//                BasePatientDO  p = patientDao.findByCode(consultTeam.getPatient());
//                String name = p.getName();
//                String openId = p.getOpenid();
//
//                WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxpj");
//
//                if (endOperator.equals("admin")) {
//                    templateConfig = templateConfigDao.findByScene("template_doctor_survey", "zxcspj");
//                }
//                String first = templateConfig.getFirst();
//                first = first.replace("key1", (name == null ? "" : name));
//                String keyword1 = templateConfig.getKeyword1();
//
//                JSONObject json = new JSONObject();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                json.put("keyword1", keyword1);
//                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", p.getCode());
//                json.put("represented", p.getCode());//被代理人
//                json.put("remark", "");
//                json.put("consult", consult);
////                String first = name + ",您好!您有1条";;
//                if (consultTeam.getType() == 8) {
////                    first += "续方";
//                    first = first.replace("key2", "续方");
//                } else {
//                    first = first.replace("key2", "");
//                }
//                /*if (endOperator.equals("admin")) {
//                    first += "咨询超时未回复,系统自动关闭,请及时对咨询医生进行评价。";
//                }else {
//                    first += "咨询已结束,请及时对咨询医生进行评价。";
//                }*/
//                json.put("first", first);
//                if (StringUtils.isNotBlank(p.getOpenid())) {
//                    pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, openId, p.getName(), json);
//                } else {
//                    //发送代理人
//                    JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
//                    if (jsonArray != null && jsonArray.length() > 0) {
//                        for (int i = 0; i < jsonArray.length(); i++) {
//                            JSONObject j = jsonArray.getJSONObject(i);
//                            Patient member = (Patient) j.get("member");
//                            JSONObject data = json;
//                            data.remove("toUser");
//                            data.put("toUser", member.getCode());
//                            data.remove("first");
//                            data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
//                            pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 17, member.getOpenid(), p.getName(), data);
//                        }
//                    }
//                }
//
//            }
//        }
//
//        consultTeam.setEndMsgId(obj.getString("id"));
//        cons.setEndTime(new Date());
//        consultTeam.setEndTime(new Date());
//        consultTeam.setStatus(1);
//        consultDao.save(cons);
//        consultTeamDao.save(consultTeam);
//
//        //结束医生求组的记录
//        endConsultHelp(consult);
//        return 1;
//    }
    /**
     * 新增名医咨询
     * type  1患者 2医生
     * agent 代理人
     */
//    public JSONObject famousConsult(ConsultTeam ct, String uid, String type, String agent) throws Exception {
//        // 设置患者信息
//        agent = uid.equals(agent) ? null : agent;
//        ct.setPatient(uid);
//        String senderId = "";
//        String senderName = "";
//        if ("1".equals(type)) {
//            // 查询患者信息
//            Patient tempPatient = patientDao.findByCode(uid);
//            // 设置患者姓名
//            ct.setName(tempPatient.getName());
//            // 设置患者生日
//            ct.setBirthday(tempPatient.getBirthday());
//            //新增性别
//            ct.setSex(tempPatient.getSex());
//            // 设置患者头像
//            ct.setPhoto(tempPatient.getPhoto());
//
//            senderId = tempPatient.getCode();
//
//            senderName = tempPatient.getName();
//
//        } else if ("2".equals(type)) {
//            Doctor doctorTemp = doctorDao.findByCode(uid);
//            // 设置医生姓名
//            ct.setName(doctorTemp.getName());
//            // 设置医生生日
//            ct.setBirthday(doctorTemp.getBirthday());
//            //新增性别
//            ct.setSex(doctorTemp.getSex());
//            // 设置医生头像
//            ct.setPhoto(doctorTemp.getPhoto());
//
//            senderId = doctorTemp.getCode();
//
//            senderName = doctorTemp.getName();
//        }
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 患者未读数量为0
//        ct.setPatientRead(0);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), null, ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        // 添加咨询转发记录
//        ConsultTeamDoctor cd = new ConsultTeamDoctor();
//        cd.setConsult(consult.getCode());
//        cd.setDel("1");
//        cd.setCzrq(new Date());
//        cd.setTo(ct.getDoctor());
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        //推送给IM文字消息
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put(ct.getPatient(), 0);
//        jsonObject.put(ct.getDoctor(), 0);
//
//        JSONObject messages = ImUtill.getCreateTopicMessage(senderId, senderName, senderName + "发起咨询", content, ct.getImages(), agent);
//
//        JSONObject obj = ImUtill.createTopics(null, consult.getCode(), consult.getSymptoms(), jsonObject, messages, ImUtill.SESSION_TYPE_P2P);
//        if (obj == null) {
//            throw new ServiceException("im消息创建异常!");
//        }
//        if (obj.getInt("status") == -1) {
//            throw new ServiceException(obj.getString("message"));
//        }
//        //设置消息ID
//        ct.setStartMsgId(obj.getString("start_msg_id"));
//        JSONObject object = ImUtill.getTopic(ct.getConsult());
//        JSONArray array = new JSONArray(object.get("data").toString());
//        consultTeamDao.save(ct);  // 保存医生咨询信息
//        consultTeamDoctorDao.save(cd);
//        consultDao.save(consult);
//        if (array.length() == 0) {
//            //由于IM是异步操作,会话生成后,可能还未生成到数据库导致无法
//            //获取会话ID。休眠1秒后继续获取相应信息
//            // PS:可以通过前端请求两次去解决,由于离职,就不挖坑了,后来者可以改善、
//            Thread.sleep(1000);
//            object = ImUtill.getTopic(ct.getConsult());
//            array = new JSONArray(object.get("data").toString());
//        }
//        return array.getJSONObject(0);
//    }
//    @Override
//    public void sendMucMessageBySingnType(String doctor, String doctorName, String patient, String content, String contentType, String title) {
//        super.sendMucMessageBySingnType(doctor, doctorName, patient, content, contentType, title);
//    }
    //过滤非本次咨询专科医生
//    public void removeSpecialist(JSONObject jsonObject, String uid, String consult) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        List<ConsultHelp> helpList = consultHelpDao.findConsult(consult);
//        Map<String, String> speMap = helpList.stream().collect(Collectors.toMap(ConsultHelp::getSpecialist, ConsultHelp::getSpecialist));
//        SignFamily signFamily = signFamilyDao.findByPatient(uid);
//        if (signFamily != null) {
//            speMap.put(signFamily.getDoctor(), "1");
//            if (StringUtils.isNotBlank(signFamily.getDoctorHealth())) {
//                speMap.put(signFamily.getDoctorHealth(), "1");
//            }
//        }
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                if (!speMap.containsKey(code)) {
//                    j.remove(i);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONObject jsonObject, String uid) {
//        JSONArray j = jsonObject.getJSONArray("users");
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
//    public void removeRenewPerson(JSONArray j, String uid) {
//        List<Integer> indexs = new ArrayList<>();
//        if (j != null && j.length() > 0) {
//            for (int i = 0; i < j.length(); i++) {
//                JSONObject doctor = (JSONObject) j.get(i);
//                String code = (String) doctor.get("id");
//                String SQL = "SELECT t.id FROM wlyy_sign_family_renew t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + DateUtil.getSignYear() + "' AND t.patient ='" + uid + "' ";
//
//                String SQL2 = "SELECT t.id FROM wlyy_sign_family t " +
//                        " WHERE (t.doctor ='" + code + "' OR t.doctor_health ='" + code + "' ) " +
//                        " AND t.sign_year ='" + (DateUtil.getSignYear() - 1) + "' AND t.patient ='" + uid + "' AND t.status>0 AND t.expenses_status ='1' ";
//                List<Map<String, Object>> isExits = jdbcTemplate.queryForList(SQL);
//                List<Map<String, Object>> isExitsSign = jdbcTemplate.queryForList(SQL2);
//                if (isExitsSign == null) {
//                    if (isExits != null && isExits.size() > 0) {
//                        indexs.add(i);
//                    }
//                }
//            }
//            if (indexs != null && indexs.size() > 0) {
//                for (Integer index : indexs) {
//                    j.remove(index);
//                }
//            }
//        }
//    }
    /**
     * 医生发送血糖血压快捷回复咨询
     */
//    public void addPrescriptionBloodStatusConsult(String prescriptionCode, String type, String followupid) throws Exception {
//
//        if ("1".equals(type)) {//血压
//            prescriptionFollowupContentService.importPatientBloodPressureToFollowup(prescriptionCode, followupid, true, "");
//        } else if ("2".equals(type)) {//血糖
//            prescriptionFollowupContentService.importPatientBloodSugarToFollowup(prescriptionCode, followupid, true, "");
//        }
//
//    }
    /**
     * 医生发送症状、体征及生活方式回复咨询
     */
//    public void addPrescriptionFollowupContentConsult(String prescriptionCode, String type, String followupid) throws Exception {
//        Prescription prescription = prescriptionDao.findByCode(prescriptionCode);
//        org.json.JSONObject contentobj = new org.json.JSONObject();
//        //医生发送的消息
//        if ("1".equals(type)) {
//            contentobj.put("text", "请填写您近期身体异常症状问卷");
//        } else {
//            contentobj.put("text", "请填写您近期体征及生活方式调查问卷");
//        }
//        contentobj.put("doctorremind", "已向居民发送问卷填写请求,填写完成后您将收到消息提醒");
//        contentobj.put("patientremind", "填写完成并提交后,医生将可以查看您的问卷内容");
//        contentobj.put("msgType", type);
//        contentobj.put("isSendWxTemplate", true);//是否发送咨询回复的微信模板
//        //医生发送Im消息
//        ImUtil.sendTopicIM(prescription.getDoctor(), prescription.getDoctorName(), prescription.getConsult(), "17", contentobj.toString(), null);
//    }
    /**
     * 根据续方code获取咨询
     */
    public ConsultTeamDo getConsultStatus(String prescriptionCode) {
        //先注释掉
//        WlyyPrescriptionDO prescription = prescriptionDao.findByCode(prescriptionCode);
//        if (prescription != null) {
//            return consultTeamDao.findByConsult(prescription.getConsult());
//        }
        return null;
    }
    /**
     * pcim 使用
@ -3085,31 +233,6 @@ public class ConsultTeamService extends ConsultService {
        return re;
    }
    /**
     * 根据居民code获取剩余家庭咨询次数
     */
//    public JSONObject countRemainConsult(String patient) {
//        JSONObject json = new JSONObject();
//        try {
//            String consultTimes = systemDictDao.findByDictNameAndCode("CONSULT_TIMES", "1.4.2");
//            int count = Integer.parseInt(consultTimes);
//            json.put("count", count);
//            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
//            if (signFamily == null) {
//                return json;
//            }
//            int amount = consultTeamDao.countRemainConsult(patient, 2, signFamily.getBegin(), signFamily.getEnd());
//            amount = count - amount;
//            if (amount < 0) {
//                amount = 0;
//            }
//            json.put("amount", amount);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return json;
//    }
    /**
     * 返回json
     */
@ -3151,21 +274,6 @@ public class ConsultTeamService extends ConsultService {
        return re.toString();
    }
    //判断居民家庭医生专科是否有共管关系
    public int getSpecialDoctorFamilyDoctorPatientCount(String patient, String special_doctor, String family_doctor) {
        String sql = "SELECT " +
                "count(a.id) FROM wlyy_specialist_patient_relation a " +
                "JOIN wlyy.wlyy_sign_family b " +
                "ON a.patient=b.patient " +
                "AND b.`status`=1 " +
                "WHERE a.sign_status> 0 " +
                "AND a.`status`>=0 " +
                "AND a.doctor='" + special_doctor + "' " +
                "AND (b.doctor='" + family_doctor + "' or b.doctor_health='" + family_doctor + "')" +
                "AND a.patient='" + patient + "'";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
    /**
     * 添加在线复诊咨询
@ -3304,32 +412,6 @@ public class ConsultTeamService extends ConsultService {
//        }
//    }
    /**
     * 保存审核提醒消息
     */
//    public void addExaminationCheckMessage(Examination examination, String sessionId, BasePatientDO p) {
//        SystemMessageDO message = new SystemMessageDO();
//        message.setCreateTime(new Date());
//        message.setCreateTime(new Date());
//        message.setIsRead("1");//设置未读
//        message.setOver("1");
//        message.setSenderPhoto(p.getPhoto());
//        message.setReceiver(examination.getDoctor());
//        message.setSender(examination.getPatient());
//        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
//        message.setSenderName(examination.getPatientName());
//        message.setTitle(examination.getPatientName() + "申请在线复诊");
//        message.setContent("您有一条新的续方申请待处理!");
//        message.setType(31);//在线复诊咨询待审核提醒
//        message.setReadonly(1);//是否只读消息
//        message.setDel("1");
//        message.setRelationCode(examination.getConsult());
//        message.setPrescriptionStatus("0");
//        message.setSessionId(sessionId);
//        message.setSessionName(examination.getPatientName());
//        messageDao.save(message);
//    }
    /**
     * 根据关联业务code查询咨询记录 wlyyDoorServiceOrderService.queryOneDetail(consult.getRelationCode());
@ -3352,9 +434,6 @@ public class ConsultTeamService extends ConsultService {
        }
        //这是id
        ConsultDo consult = consultDao.queryByIdAndType(code, type);
//        ConsultDo consult = consultDao.findByRelationCode(code);
        if (null == consult) {
            result.put("data", "");
            return result;
@ -3389,108 +468,4 @@ public class ConsultTeamService extends ConsultService {
        return new org.json.JSONObject(response);
    }
//    public JSONObject addTeamSpecialConsult(ConsultTeam ct, String patientCode, String agent, String specialDoctorCode, String doctorCode) throws Exception {
//        JSONObject re = new JSONObject();
////        if (exist(patientCode, ct.getType())) {//判断是否有未结束的咨询移到同步方法中
////            re.put("status", -3);
////            return re;
////        }
//
//        JSONObject users = new JSONObject();
//
//        if (patientCode.equals(agent)) {
//            agent = null;
//        }
//
//        users.put(doctorCode, 0);
//        users.put(specialDoctorCode, 0);
//
//        // 设置患者信息
//        ct.setPatient(patientCode);
//        // 查询患者信息
//        Patient tempPatient = patientDao.findByCode(patientCode);
//        // 设置患者姓名
//        ct.setName(tempPatient.getName());
//        // 设置患者生日
//        ct.setBirthday(tempPatient.getBirthday());
//        //新增性别
//        ct.setSex(tempPatient.getSex());
//        // 设置患者头像
//        ct.setPhoto(tempPatient.getPhoto());
//        // 设置操作日期
//        ct.setCzrq(new Date());
//        ct.setDel("1");
//        ct.setStatus(0);
//        ct.setEvaluate(0);
//        // 医生未读数量为1
//        ct.setDoctorRead(1);
//        // 添加咨询记录
//        Consult consult = addConsult(ct.getPatient(), tempPatient.getName() + "康复咨询", ct.getSymptoms(), ct.getImages(), ct.getType());
//        // 设置关联指导
//        consult.setGuidance(ct.getGuidance());
//        // 设置咨询标识
//        ct.setConsult(consult.getCode());
//        ct.setDoctor(doctorCode);
//
//        //推送给IM去创建议题,取得成员消息
//        JSONObject messages = ImUtill.getCreateTopicMessage(patientCode, tempPatient.getName(), consult.getTitle(), consult.getSymptoms(), consult.getImages(), agent);
//        users.put(patientCode, 0);
//        JSONObject obj = ImUtill.createTopics(patientCode + "_" + doctorCode + "_" + specialDoctorCode + "_" + ct.getType(), consult.getCode(), tempPatient.getName(), users, messages, ImUtill.SESSION_TYPE_KANGFU);
//        if (obj == null) {
//            throw new ServiceException("IM消息发送异常!");
//        }
//        if (obj.getInt("status") == -1) {//im议题创建失败
//            throw new ServiceException(obj.getString("message"));
//        }
//        ct.setStartMsgId(obj.get("start_msg_id").toString());
//        consultTeamDao.save(ct);
//        consultDao.save(consult);
//
//        JSONArray doctor = new JSONArray();
//        for (String key : users.keySet()) {
//            if (patientCode.equals(key)) {
//                continue;
//            }
//            doctor.put(key);
//            //记录咨询的医生详情误删
//            ConsultTeamDoctor cd = new ConsultTeamDoctor();
//            cd.setConsult(consult.getCode());
//            cd.setDel("1");
//            cd.setCzrq(new Date());
//            cd.setTo(key);
//            consultTeamDoctorDao.save(cd);
//        }
//
//        // 保存医生咨询信息
//        // 添加咨询转发记录
//        // 添加医生咨询日志
//        String content = addLogs(ct);
//        re.put("doctor", doctor);
//        re.put("status", 1);
//        return re;
//    }
//    public JSONObject getConsultDoctorForConsulting(String patientCode) {
//        JSONObject result = new JSONObject();
//        String sql = "SELECT DISTINCT p.patient, p.name AS patient_name, p.`team_code`,te.`name` AS team_name, d.`code` as special_code, d.`name` as special_name, d.dept_name,d.hospital_name \n" +
//                "FROM wlyy_patient_rehabilitation_plan p, wlyy_doctor d ,wlyy_admin_team te\n" +
//                "WHERE p.patient = '" + patientCode + "' AND d.`code`= p.create_user and te.id = p.team_code AND te.available=1 GROUP BY p.patient, p.create_user,p.team_code";
//        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        result.put("ConsultTeamList", list);
//        //家庭医生
//        SignFamily sf = signFamilyDao.findByjiatingPatient(patientCode);
//        if (StringUtils.isNoneBlank(sf.getDoctor())) {
//            result.put("doctor", sf.getDoctor());
//            result.put("doctorName", sf.getDoctorName());
//        }
//        if (StringUtils.isNoneBlank(sf.getDoctorHealth())) {
//            result.put("doctorHealth", sf.getDoctorHealth());
//            result.put("doctorHealthName", sf.getDoctorHealthName());
//        }
//        return result;
//    }
}

+ 0 - 92
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java

@ -653,10 +653,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                "	1 = 1 \n" +
                "	AND t.`code` = 'dispatcher' \n";
//        if (StringUtils.isNotBlank(hospitalCode)) {
//            sql += " AND a.org_code = '" + hospitalCode + "' \n";
//        }
        List<Map<String, Object>> dispatcherInfoList = jdbcTemplate.queryForList(sql);
        return dispatcherInfoList;
    }
@ -700,7 +696,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            orderDO.setStatus(1);//待派单(调度员)
        }
        if (StringUtils.isEmpty(orderDO.getPatient())) {
            throw new Exception("当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient());
        }
@ -762,71 +757,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        boolean flag = true;
        JSONObject result = new JSONObject();
//        //创建订单信息
//        BasePatientDO pateint = patientDao.findById(orderDO.getPatient());
//        //查询是否存在订单信息
//        BusinessOrderDO businessOrderDO = businessOrderDao.findByOrderId(orderDO.getId());
//        if (businessOrderDO == null) {
//            businessOrderDO = new BusinessOrderDO();
//            businessOrderDO.setPatient(pateint.getId());
//            //支付账号
//            businessOrderDO.setYkOrderId(pateint.getMobile());
//            businessOrderDO.setPatientName(pateint.getName());
//            businessOrderDO.setOrderType(1);
//            businessOrderDO.setOrderCategory(type);
//            Date date = new Date();
//            Long lastPayTime = date.getTime() + 1000 * 60 * 30;//订单截至支付日期
//            businessOrderDO.setDescription("上门服务");
//            businessOrderDO.setRelationCode(orderDO.getId());//订单id
//            businessOrderDO.setRelationName("上门服务");
//            businessOrderDO.setCreateTime(date);
//            businessOrderDO.setUpdateTime(date);
//            businessOrderDO.setStatus(0);
//            businessOrderDO.setOrderNo(orderDO.getNumber());
//            businessOrderDO.setUploadStatus(0);
//            businessOrderDO.setPayType(1);
//            businessOrderDO.setPayPrice(Double.valueOf(orderDO.getTotalFee().doubleValue()));
//            businessOrderDO.setLastPayTime(lastPayTime);
//        } else {
//            /**
//             * 暂时没用,线下付款的
//             * 1、是否付款完成
//             * 2、判断付款时间是否超过时长了--还需要定时任务监听订单修改状态,把未付款改成已取消
//             */
////            if (businessOrderDO.getStatus() != 1) {
////                long nowTime = System.currentTimeMillis();
////                Long lastPayTime = businessOrderDO.getLastPayTime();
////                if (lastPayTime > nowTime) {
////                    //超时了 修改工单状态成已取消
////                    orderDO.setStatus(-1);//-已取消
////                    wlyyDoorServiceOrderDao.saveAll(orderDO);//更新上门工单
////                    businessOrderDO.setStatus(2);//已取消
////                    businessOrderDao.saveAll(businessOrderDO);//更新业务表
////                    flag = false;//不用创建咨询内容
////                }
////            }
//        }
        /**
         *  1、费用0时无需支付
         *  2、调用微信支付 再来更新flag标识
         */
//        if ("5".equals(type) && 0.0 == orderDO.getTotalFee().doubleValue()) {
//            businessOrderDO.setStatus(1);//1已支付
//            businessOrderDao.saveAll(businessOrderDO);
//        } else {
//            /**
//             * 保存订单信息-这边要判断付款回调修改状态值-付款失败取消订单
//             * businessOrderService
//             */
//            businessOrderDO.setStatus(0);//0待支付
//            businessOrderDao.saveAll(businessOrderDO);
//        }
        //保存业务表
//        businessOrderDao.saveAll(businessOrderDO);
        /**
         * 目前是线下付款的
         * 给出标识是否成功,往下面创建咨询信息发送内容
@ -839,12 +769,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            JSONObject successOrNot = consultTeamService.addDoorServiceConsult(orderDO.getId());
            ConsultTeamDo consultTeam = (ConsultTeamDo) successOrNot.get(ResponseContant.resultMsg);
            System.out.println("===调度员的信息开始======");
            for (Map<String, Object> map : dispatcherList) {
                System.out.println("调度员=>" + JSON.toJSONString(map));
            }
            System.out.println("===调度员的信息结束======");
            //判断其是否有分配执行人。如果有不用走调度平台
            if (StringUtils.isNotBlank(orderDO.getDoctor())) {
                orderDO.setStatus(2);//待接单
@ -891,22 +815,6 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
            int flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
            System.out.println("flagCount==>" + flagCount);
            //模拟一,重试3次
//            int tryCount = 3;
//            int flagCount = 0;
//            for (int i = 0; i < tryCount; i++) {
//                //发送消息
//                flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
//                if (flagCount == 1) {
//                    break;
//                }
//            }
//            //模式2,睡眠1秒钟
//            Thread.sleep(1000);
//            flagCount = qucikSendIM(orderDO.getId(), "system", "智能助手", "2101", orderInfoContent.toJSONString());
            //后面这个要修改下,加个字段判断下是否转派
            if (StringUtils.isNoneBlank(orderDO.getDoctor())) {
                //服务医生修改,直接转派