浏览代码

bug修改

suqinyi 1 年之前
父节点
当前提交
bb44dca3f1

文件差异内容过多而无法显示
+ 4 - 3
business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java


+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServiceItemPlanDO.java

@ -16,7 +16,7 @@ import javax.persistence.Transient;
public class ServiceItemPlanDO extends UuidIdentityEntityWithCreateTime {
    private String patient;//居民id
    private String status;//状态0未完成 1已完成 2待补录
    private String status;//状态0未完成 1已完成 2待补录  补充【3进行中】
    private String planTime;//计划时间
    private String completeTime;//完成时间
    private String doctor;//医生id

+ 5 - 10
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/dict/DictJobTitleEndpoint.java

@ -76,16 +76,11 @@ public class DictJobTitleEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseRequestMapping.DictJobTitle.PAGE)
    @ApiOperation(value = "获取分页")
    public PageEnvelop<DictJobTitleVO> page(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段") @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件") @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档") @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1") @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15") @RequestParam(value = "size") int size) throws Exception {
        List<DictJobTitleDO> dictJobTitles = dictJobTitleService.search(fields, filters, sorts, page, size);
        int count = (int) dictJobTitleService.getCount(filters);
        return success(dictJobTitles, count, page, size, DictJobTitleVO.class);

+ 896 - 922
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -69,950 +69,924 @@ import java.util.*;
@Api(value = "居民端咨询IM接口", description = "居民端咨询IM接口", tags = {"居民端咨询IM接口"})
public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	private static final Logger logger = LoggerFactory.getLogger(PatientConsultEndpoint.class);
	@Autowired
	private ImService imService;
	
	@Autowired
	private PrescriptionService prescriptionService;
	
	@Autowired
	private BasePatientService basePatientService;
	
	
	@Autowired
	private WechatInfoService wechatInfoService;
	
	@Autowired
	private WechatDao wechatDao;
	
	@Autowired
	private HospitalSystemMessageService hospitalSystemMessageService;
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Autowired
	private WlyyBusinessService wlyyBusinessService;
	@Autowired
	private BaseDoctorDao baseDoctorDao;
	@Autowired
	private BasePatientDao basePatientDao;
	
	@Autowired
	FileUploadService fileUploadService;
	@Autowired
	private BaseDoctorInfoService doctorInfoService;
	@Autowired
	private BusinessOrderService businessOrderService;
	@Autowired
	private SystemMessageService systemMessageService;
	@Autowired
	private ConsultDao consultDao;
	@Autowired
	private YkyyService ykyyService;
	@Autowired
	private BaseDoctorRoleDao doctorRoleDao;
	@Autowired
	public ImUtil imUtil;
	@Autowired
	private OutpatientDao outpatientDao;
	@Autowired
	private YlzPayService ylzPayService;
	@Autowired
	private PatientMappingDao patientMappingDao;
	@Autowired
	private PrescriptionDao prescriptionDao;
	@Autowired
	private EntranceService entranceService;
	@Autowired
	private WlyyFamilyMemberService familyMemberService;
	@Value("${fastDFS.fastdfs_file_url}")
	private String fastdfs_file_url;
	
	@Value("${wlyy.url}")
	private String wlyyUrl;
	
	@Value("${qywx.url}")
	private String qywxUrl;
	
	@Value("${qywx.id}")
	private String qywxId;
	@Value("${wechat.id}")
	private String wxId;
	@Value("${pay.flag}")
	private boolean payFlag;
	@Value("${testPattern.remote_inner_url}")
	private String remote_inner_url;
	@Autowired
	private RobotService robotService;
	@Autowired
	private FileUtil fileUtil;
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.records)
	@ApiOperation(value = "患者咨询记录查询")
	public Envelop records(
								@ApiParam(name = "patient", value = "居民id")
								@RequestParam(value = "patient",required = true) String patient,
								@ApiParam(name = "doctorId", value = "医生id",required = false)
								@RequestParam(value = "doctorId",required = false) String doctorId,
								@ApiParam(name = "title", value = "咨询标题关键字")
								@RequestParam(value = "title",required = false) String title,
								@ApiParam(name = "id", value = "咨询ID")
								@RequestParam(value = "id",required = false) String id,
								@ApiParam(name = "type", value = "咨询类型")
								@RequestParam(value = "type",required = true) String type,
								@ApiParam(name = "status", value = "咨询状态:0全部,1候诊中,2就诊中,3结束")
								@RequestParam(value = "status",required = false) Integer status,
								@ApiParam(name = "payStatus", value = "支付状态0支付1已支付")
								@RequestParam(value = "payStatus",required = false) Integer payStatus,
								@ApiParam(name = "page", value = "第几页")
								@RequestParam(value = "page",required = false) int page,
								@ApiParam(name = "pagesize", value = "分页大小")
								@RequestParam(value = "pagesize",required = false) int pagesize,
								@ApiParam(name = "doctorName", value = "医生名字")
								@RequestParam(value = "doctorName",required = false) String doctorName
								){
		try {
			List<Map<String,Object>>  data = imService.findConsultRecordByPatient(patient, id,type, page,pagesize, title,status,payStatus,doctorName,doctorId);
			Long total = imService.countConsultRecordByPatient(patient, id,type,title,doctorId);
			JSONObject result = new JSONObject();
			result.put("total",total);
			result.put("list",data);
			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.isExistsUnfinishedConsult)
	@ApiOperation(value = "查询居民与某个医生是否存在未结束的专家咨询")
	public Envelop isExistsUnfinishedConsult(
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor,
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = true) String patient)throws Exception {
		
		try {
			if(StringUtils.isEmpty(patient)){
				patient= getUID();
			}
			String consultCode = imService.getUnfinishedConsult(patient, doctor);
			return success("请求成功",consultCode);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.isExistsUnfinishedOutpatient)
	@ApiOperation(value = "查询居民与某个医生是否存在未结束的专家咨询")
	public Envelop isExistsUnfinishedOutpatient(
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor,
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = true) String patient)throws Exception {
		try {
			if(StringUtils.isEmpty(patient)){
				patient= getUID();
			}
			String consultCode = imService.getUnfinishedConsult2(patient, doctor);
			return success("请求成功",consultCode);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.participants)
	@ApiOperation(value = "获取会话成员")
	public ListEnvelop participants(
			@ApiParam(name = "sessionId", value = "会话ID")
			@RequestParam(value = "sessionId",required = true) String sessionId)throws Exception{
		
		try {
			JSONArray participants = imService.getSessions(sessionId);
			return success(participants);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getSessionMessage)
	@ApiOperation(value = "根据会话ID获取消息记录")
	public ListEnvelop getSessionMessage(
			@ApiParam(name = "sessionId", value = "会话ID")
			@RequestParam(value = "sessionId",required = true) String sessionId,
			@ApiParam(name = "startMsgId", value = "开始的消息记录ID")
			@RequestParam(value = "startMsgId",required = false) String startMsgId,
			@ApiParam(name = "endMsgId", value = "结束的消息记录ID")
			@RequestParam(value = "endMsgId",required = false) String endMsgId,
			@ApiParam(name = "page", value = "第几页")
			@RequestParam(value = "page",required = true) int page,
			@ApiParam(name = "pagesize", value = "分页数")
			@RequestParam(value = "pagesize",required = true) int pagesize)throws Exception{
		try {
			JSONArray messageArray = imService.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getUID());
			return success(messageArray);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.intoTopic)
	@ApiOperation(value = "根据咨询CODE进入会话")
	public Envelop intoTopic(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult,
			@ApiParam(name = "patientCode", value = "居民CODE")
			@RequestParam(value = "patientCode",required = true) String patientCode
			){
		try {
			int result = imService.intoTopic(consult,patientCode,"");
			if(result==-1){
				return failed("该咨询不是进行中");
			}
			return success("进入成功");
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.append)
	@ApiOperation(value = "居民咨询发消息(追问接口)")
	public ListEnvelop append(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult,
			@ApiParam(name = "content", value = "追问内容")
			@RequestParam(value = "content",required = true) String content,
			@ApiParam(name = "type", value = "追问内容类型:1文字,2图片,3语音  ... (im消息类型)")
			@RequestParam(value = "type",required = true) Integer type,
			@ApiParam(name = "times", value = "")
			@RequestParam(value = "times",required = false) Integer times,
			@ApiParam(name = "wechat_appid", value = "来源:xm_ihealth_wx厦门i健康,xm_zsyy_wx中山医院")
			@RequestParam(value = "wechat_appid",required = false) String wechat_appid,
			@ApiParam(name = "patientCode", value = "居民CODE")
			@RequestParam(value = "patientCode",required = false) String patientCode) throws Exception {
		try {
			List<String> failed = new ArrayList<>();
			//处理语音文件
			if(!org.springframework.util.StringUtils.isEmpty(wechat_appid)){
    private static final Logger logger = LoggerFactory.getLogger(PatientConsultEndpoint.class);
    @Autowired
    private ImService imService;
    @Autowired
    private PrescriptionService prescriptionService;
    @Autowired
    private BasePatientService basePatientService;
    @Autowired
    private WechatInfoService wechatInfoService;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private HospitalSystemMessageService hospitalSystemMessageService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private WlyyBusinessService wlyyBusinessService;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    FileUploadService fileUploadService;
    @Autowired
    private BaseDoctorInfoService doctorInfoService;
    @Autowired
    private BusinessOrderService businessOrderService;
    @Autowired
    private SystemMessageService systemMessageService;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private YkyyService ykyyService;
    @Autowired
    private BaseDoctorRoleDao doctorRoleDao;
    @Autowired
    public ImUtil imUtil;
    @Autowired
    private OutpatientDao outpatientDao;
    @Autowired
    private YlzPayService ylzPayService;
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private WlyyFamilyMemberService familyMemberService;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Value("${wlyy.url}")
    private String wlyyUrl;
    @Value("${qywx.url}")
    private String qywxUrl;
    @Value("${qywx.id}")
    private String qywxId;
    @Value("${wechat.id}")
    private String wxId;
    @Value("${pay.flag}")
    private boolean payFlag;
    @Value("${testPattern.remote_inner_url}")
    private String remote_inner_url;
    @Autowired
    private RobotService robotService;
    @Autowired
    private FileUtil fileUtil;
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.records)
    @ApiOperation(value = "患者咨询记录查询")
    public Envelop records(
            @ApiParam(name = "patient", value = "居民id") @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "doctorId", value = "医生id", required = false) @RequestParam(value = "doctorId", required = false) String doctorId,
            @ApiParam(name = "title", value = "咨询标题关键字") @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "id", value = "咨询ID") @RequestParam(value = "id", required = false) String id,
            @ApiParam(name = "type", value = "咨询类型") @RequestParam(value = "type", required = true) String type,
            @ApiParam(name = "status", value = "咨询状态:0全部,1候诊中,2就诊中,3结束") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(name = "payStatus", value = "支付状态0支付1已支付") @RequestParam(value = "payStatus", required = false) Integer payStatus,
            @ApiParam(name = "page", value = "第几页") @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "pagesize", value = "分页大小") @RequestParam(value = "pagesize", required = false) int pagesize,
            @ApiParam(name = "doctorName", value = "医生名字") @RequestParam(value = "doctorName", required = false) String doctorName
    ) {
        try {
            List<Map<String, Object>> data = imService.findConsultRecordByPatient(patient, id, type, page, pagesize, title, status, payStatus, doctorName, doctorId);
            Long total = imService.countConsultRecordByPatient(patient, id, type, title, doctorId);
            JSONObject result = new JSONObject();
            result.put("total", total);
            result.put("list", data);
            return success(result);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.isExistsUnfinishedConsult)
    @ApiOperation(value = "查询居民与某个医生是否存在未结束的专家咨询")
    public Envelop isExistsUnfinishedConsult(
            @ApiParam(name = "doctor", value = "医生CODE")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "patient", value = "居民CODE")
            @RequestParam(value = "patient", required = true) String patient) throws Exception {
        try {
            if (StringUtils.isEmpty(patient)) {
                patient = getUID();
            }
            String consultCode = imService.getUnfinishedConsult(patient, doctor);
            return success("请求成功", consultCode);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.isExistsUnfinishedOutpatient)
    @ApiOperation(value = "查询居民与某个医生是否存在未结束的专家咨询")
    public Envelop isExistsUnfinishedOutpatient(
            @ApiParam(name = "doctor", value = "医生CODE")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "patient", value = "居民CODE")
            @RequestParam(value = "patient", required = true) String patient) throws Exception {
        try {
            if (StringUtils.isEmpty(patient)) {
                patient = getUID();
            }
            String consultCode = imService.getUnfinishedConsult2(patient, doctor);
            return success("请求成功", consultCode);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.participants)
    @ApiOperation(value = "获取会话成员")
    public ListEnvelop participants(
            @ApiParam(name = "sessionId", value = "会话ID")
            @RequestParam(value = "sessionId", required = true) String sessionId) throws Exception {
        try {
            JSONArray participants = imService.getSessions(sessionId);
            return success(participants);
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.getSessionMessage)
    @ApiOperation(value = "根据会话ID获取消息记录")
    public ListEnvelop getSessionMessage(
            @ApiParam(name = "sessionId", value = "会话ID")
            @RequestParam(value = "sessionId", required = true) String sessionId,
            @ApiParam(name = "startMsgId", value = "开始的消息记录ID")
            @RequestParam(value = "startMsgId", required = false) String startMsgId,
            @ApiParam(name = "endMsgId", value = "结束的消息记录ID")
            @RequestParam(value = "endMsgId", required = false) String endMsgId,
            @ApiParam(name = "page", value = "第几页")
            @RequestParam(value = "page", required = true) int page,
            @ApiParam(name = "pagesize", value = "分页数")
            @RequestParam(value = "pagesize", required = true) int pagesize) throws Exception {
        try {
            JSONArray messageArray = imService.getSessionMessage(sessionId, startMsgId, endMsgId, page, pagesize, getUID());
            return success(messageArray);
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.intoTopic)
    @ApiOperation(value = "根据咨询CODE进入会话")
    public Envelop intoTopic(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = true) String consult,
            @ApiParam(name = "patientCode", value = "居民CODE")
            @RequestParam(value = "patientCode", required = true) String patientCode
    ) {
        try {
            int result = imService.intoTopic(consult, patientCode, "");
            if (result == -1) {
                return failed("该咨询不是进行中");
            }
            return success("进入成功");
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.append)
    @ApiOperation(value = "居民咨询发消息(追问接口)")
    public ListEnvelop append(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = true) String consult,
            @ApiParam(name = "content", value = "追问内容")
            @RequestParam(value = "content", required = true) String content,
            @ApiParam(name = "type", value = "追问内容类型:1文字,2图片,3语音  ... (im消息类型)")
            @RequestParam(value = "type", required = true) Integer type,
            @ApiParam(name = "times", value = "")
            @RequestParam(value = "times", required = false) Integer times,
            @ApiParam(name = "wechat_appid", value = "来源:xm_ihealth_wx厦门i健康,xm_zsyy_wx中山医院")
            @RequestParam(value = "wechat_appid", required = false) String wechat_appid,
            @ApiParam(name = "patientCode", value = "居民CODE")
            @RequestParam(value = "patientCode", required = false) String patientCode) throws Exception {
        try {
            List<String> failed = new ArrayList<>();
            //处理语音文件
            if (!org.springframework.util.StringUtils.isEmpty(wechat_appid)) {
//			imService.getInputStream("1",wechat_appid);
				if(3 == type){//语音文件
					String voicepath = imService.fetchWxVoices(wechat_appid);
					logger.info("voice_path:"+voicepath);
					JSONObject obj = new JSONObject();
					String voiceurl = "";
					// 将临时语音拷贝到正式存储路径下
					if (org.apache.commons.lang3.StringUtils.isNotEmpty(voicepath)) {
						if("xm_ihealth_wx".equals(wechat_appid)){
							logger.info("voice_wx_type:"+wechat_appid);
							voiceurl = fileUploadService.uploadWxVoice(voicepath);
                if (3 == type) {//语音文件
                    String voicepath = imService.fetchWxVoices(wechat_appid);
                    logger.info("voice_path:" + voicepath);
                    JSONObject obj = new JSONObject();
                    String voiceurl = "";
                    // 将临时语音拷贝到正式存储路径下
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(voicepath)) {
                        if ("xm_ihealth_wx".equals(wechat_appid)) {
                            logger.info("voice_wx_type:" + wechat_appid);
                            voiceurl = fileUploadService.uploadWxVoice(voicepath);
//					uploadVO.setFullUri(map.get("accessory").toString());
						}else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid)||"xm_hcyy_wx".equalsIgnoreCase(wechat_appid)){
							voiceurl = fileUploadService.uploadWxVoiceToEntrance(remote_inner_url,voicepath);
							logger.info(voiceurl);
						}else {
							voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
						}
						obj.put("path", voiceurl);
						obj.put("times", times);
						content = obj.toString();
					}
				}else if(2 == type){//图片文件
					String imagepath = imService.fetchWxImages(wechat_appid);
					logger.info("image_path:"+imagepath);
					JSONObject obj = new JSONObject();
					String imgeUrl = "";
					// 将临时语音拷贝到正式存储路径下
					if (org.apache.commons.lang3.StringUtils.isNotEmpty(imagepath)) {
						if("xm_ihealth_wx".equals(wechat_appid)){
							logger.info("imge_wx_type:"+wechat_appid);
							imgeUrl = fileUploadService.uploadWxImage(imagepath);
                        } else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid) || "xm_hcyy_wx".equalsIgnoreCase(wechat_appid)) {
                            voiceurl = fileUploadService.uploadWxVoiceToEntrance(remote_inner_url, voicepath);
                            logger.info(voiceurl);
                        } else {
                            voiceurl = fileUtil.copyTempVoice(voicepath, fastdfs_file_url);
                        }
                        obj.put("path", voiceurl);
                        obj.put("times", times);
                        content = obj.toString();
                    }
                } else if (2 == type) {//图片文件
                    String imagepath = imService.fetchWxImages(wechat_appid);
                    logger.info("image_path:" + imagepath);
                    JSONObject obj = new JSONObject();
                    String imgeUrl = "";
                    // 将临时语音拷贝到正式存储路径下
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(imagepath)) {
                        if ("xm_ihealth_wx".equals(wechat_appid)) {
                            logger.info("imge_wx_type:" + wechat_appid);
                            imgeUrl = fileUploadService.uploadWxImage(imagepath);
//					uploadVO.setFullUri(map.get("accessory").toString());
						}else{
							imgeUrl = fileUtil.copyTempVoice(imagepath,fastdfs_file_url);
						}
						content = imgeUrl;
					}
				}else{}
			}
			failed = imService.append(consult,content,type,times,patientCode,wechat_appid);
			return success(failed);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.Prescription.findDoctorByHospitalAndDiseaseAndDept)
	@ApiOperation(value = "根据疾病名称,热门部门查询医生", notes = "根据疾病名称,热门部门查询医生")
	public MixEnvelop findDoctorByHospitalAndDiseaseAndDept(@ApiParam(name = "iswork", value = "机构code")
																 @RequestParam(value = "iswork", required = false)String iswork,
															@ApiParam(name = "patientid", value = "居民ID")
	                                                         @RequestParam(value = "patientid", required = false)String patientid,
															@ApiParam(name = "orgCode", value = "机构code")
	                                               @RequestParam(value = "orgCode", required = false)String orgCode,
															@ApiParam(name = "dept", value = "部门code")
	                                               @RequestParam(value = "dept", required = false)String dept,
															@ApiParam(name = "diseaseKey", value = "疾病名称关键字")
	                                               @RequestParam(value = "diseaseKey", required = false)String diseaseKey,
															@ApiParam(name = "doctorNameKey", value = "医生名称关键字")
	                                               @RequestParam(value = "doctorNameKey", required = false)String doctorNameKey,
															@ApiParam(name = "jobTitleNameKey", value = "医生职称关键字")
                                                   @RequestParam(value = "jobTitleNameKey", required = false)String jobTitleNameKey,
															@ApiParam(name = "outpatientType", value = "咨询类型1图文,2视频")
                                                   @RequestParam(value = "outpatientType", required = false)String outpatientType,
															@ApiParam(name = "keyName", value = "姓名/科室/疾病模糊搜索关键字")
                                                   @RequestParam(value = "keyName", required = false)String keyName,
															@ApiParam(name = "workingTime", value = "排班时间YYYY-MM-DD")
	                                               @RequestParam(value = "workingTime", required = false)String workingTime,
															@ApiParam(name = "consultStatus", value = "在线状态")
	                                               @RequestParam(value = "consultStatus", required = false,defaultValue = "")String consultStatus,
															@ApiParam(name = "chargType", value = "医生号别")
	                                                @RequestParam(value = "chargType", required = false,defaultValue = "")String chargType,
															@ApiParam(name = "consutlSort", value = "咨询量排序")
                                                   @RequestParam(value = "consutlSort", required = true,defaultValue = "DESC")String consutlSort,
															@ApiParam(name = "isAttention", value = "是否关注")
													@RequestParam(value = "isAttention", required = false)String isAttention,
															@ApiParam(name = "page", value = "第几页")
	                                                     @RequestParam(value = "page",required = false) Integer page,
															@ApiParam(name = "pagesize", value = "分页大小")
	                                                     @RequestParam(value = "pagesize",required = false) Integer pagesize
	) throws Exception{
		try {
			logger.info("findDoctorByHospitalAndDiseaseAndDept start:"+DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss:SSS"));
			return prescriptionService.findDoctorByHospitalAndDiseaseAndDept2(iswork,patientid,
					orgCode,dept,
					diseaseKey,doctorNameKey,
					jobTitleNameKey,outpatientType,
					keyName,workingTime,consultStatus,chargType,consutlSort,isAttention,page,pagesize);
		}catch (Exception e){
			return failedMixEnvelopException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.Prescription.findHotDeptAndDiseaseDict)
	@ApiOperation(value = "获取常见疾病、热门部门、医生拒绝接诊原因 字典", notes = "获取常见疾病、热门部门、医生拒绝接诊原因 字典")
	public ListEnvelop findHotDeptAndDiseaseDict(@ApiParam(name = "dictName", value = "dictName")
	                                             @RequestParam(value = "dictName", required = true,defaultValue = "ONLINE_HOSPITAL_DEPT_350211A1002")String dictName)throws Exception{
		try {
			return success(prescriptionService.findHotDeptAndDiseaseDict(dictName));
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.add)
	@ApiOperation(value = "居民添加咨询接口", notes = "居民添加咨询接口")
	public Envelop add(
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = false) String patient,
			@ApiParam(name = "doctor", value = "医生CODE")
			@RequestParam(value = "doctor",required = true) String doctor,
			@ApiParam(name = "when", value = "发病时间")
			@RequestParam(value = "when",required = false) String when,
			@ApiParam(name = "symptoms", value = "主述")
			@RequestParam(value = "symptoms",required = false) String symptoms,
			@ApiParam(name = "images", value = "图片")
			@RequestParam(value = "images",required = false) String images,
			@ApiParam(name = "voice", value = "语音")
			@RequestParam(value = "voice",required = false) String voice,
			@ApiParam(name = "relationCode", value = "关联业务表的code(服务项执行计划id)")
			@RequestParam(value = "relationCode",required = false) String relationCode,
			@ApiParam(name = "type", value = "咨询类型:1专家咨询 14导诊助手 17专家视频咨询 28康复咨询")
			@RequestParam(value = "type",required = false) Integer type,
			@ApiParam(name = "source", value = "咨询类型来源")
			@RequestParam(value = "source",required = false) String source)throws Exception{
		System.out.println("symptoms="+symptoms);
		if (type == null) {
			type = 1;
		}
		ConsultTeamDo consult = new ConsultTeamDo();
		// 设置咨询类型:1专家咨询  14导诊助手
		consult.setType(type);
		// 设置发病时间
		consult.setWhen(when);
		// 设置主要症状
		consult.setSymptoms(symptoms);
		// 设置咨询图片URL
		consult.setImages(images);
		// 设置咨询语音URL
		consult.setVoice(voice);
		consult.setDoctor(doctor);
		consult.setPatient(patient);
		// 保存到数据库
                        } else {
                            imgeUrl = fileUtil.copyTempVoice(imagepath, fastdfs_file_url);
                        }
                        content = imgeUrl;
                    }
                } else {
                }
            }
            failed = imService.append(consult, content, type, times, patientCode, wechat_appid);
            return success(failed);
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.findDoctorByHospitalAndDiseaseAndDept)
    @ApiOperation(value = "根据疾病名称,热门部门查询医生", notes = "根据疾病名称,热门部门查询医生")
    public MixEnvelop findDoctorByHospitalAndDiseaseAndDept(
            @ApiParam(name = "iswork", value = "机构code") @RequestParam(value = "iswork", required = false) String iswork,
            @ApiParam(name = "patientid", value = "居民ID") @RequestParam(value = "patientid", required = false) String patientid,
            @ApiParam(name = "orgCode", value = "机构code") @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "dept", value = "部门code") @RequestParam(value = "dept", required = false) String dept,
            @ApiParam(name = "diseaseKey", value = "疾病名称关键字") @RequestParam(value = "diseaseKey", required = false) String diseaseKey,
            @ApiParam(name = "doctorNameKey", value = "医生名称关键字") @RequestParam(value = "doctorNameKey", required = false) String doctorNameKey,
            @ApiParam(name = "jobTitleNameKey", value = "医生职称关键字") @RequestParam(value = "jobTitleNameKey", required = false) String jobTitleNameKey,
            @ApiParam(name = "outpatientType", value = "咨询类型1图文,2视频") @RequestParam(value = "outpatientType", required = false) String outpatientType,
            @ApiParam(name = "keyName", value = "姓名/科室/疾病模糊搜索关键字") @RequestParam(value = "keyName", required = false) String keyName,
            @ApiParam(name = "workingTime", value = "排班时间YYYY-MM-DD") @RequestParam(value = "workingTime", required = false) String workingTime,
            @ApiParam(name = "consultStatus", value = "在线状态") @RequestParam(value = "consultStatus", required = false, defaultValue = "") String consultStatus,
            @ApiParam(name = "chargType", value = "医生号别") @RequestParam(value = "chargType", required = false, defaultValue = "") String chargType,
            @ApiParam(name = "consutlSort", value = "咨询量排序") @RequestParam(value = "consutlSort", required = true, defaultValue = "DESC") String consutlSort,
            @ApiParam(name = "isAttention", value = "是否关注") @RequestParam(value = "isAttention", required = false) String isAttention,
            @ApiParam(name = "page", value = "第几页") @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pagesize", value = "分页大小") @RequestParam(value = "pagesize", required = false) Integer pagesize
    ) throws Exception {
        try {
            logger.info("findDoctorByHospitalAndDiseaseAndDept start:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
            return prescriptionService.findDoctorByHospitalAndDiseaseAndDept2(iswork, patientid,
                    orgCode, dept,
                    diseaseKey, doctorNameKey,
                    jobTitleNameKey, outpatientType,
                    keyName, workingTime, consultStatus, chargType, consutlSort, isAttention, page, pagesize);
        } catch (Exception e) {
            return failedMixEnvelopException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.findHotDeptAndDiseaseDict)
    @ApiOperation(value = "获取常见疾病、热门部门、医生拒绝接诊原因 字典", notes = "获取常见疾病、热门部门、医生拒绝接诊原因 字典")
    public ListEnvelop findHotDeptAndDiseaseDict(@ApiParam(name = "dictName", value = "dictName")
                                                 @RequestParam(value = "dictName", required = true, defaultValue = "ONLINE_HOSPITAL_DEPT_350211A1002") String dictName) throws Exception {
        try {
            return success(prescriptionService.findHotDeptAndDiseaseDict(dictName));
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.add)
    @ApiOperation(value = "居民添加咨询接口", notes = "居民添加咨询接口")
    public Envelop add(
            @ApiParam(name = "patient", value = "居民CODE")
            @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "doctor", value = "医生CODE")
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "when", value = "发病时间")
            @RequestParam(value = "when", required = false) String when,
            @ApiParam(name = "symptoms", value = "主述")
            @RequestParam(value = "symptoms", required = false) String symptoms,
            @ApiParam(name = "images", value = "图片")
            @RequestParam(value = "images", required = false) String images,
            @ApiParam(name = "voice", value = "语音")
            @RequestParam(value = "voice", required = false) String voice,
            @ApiParam(name = "relationCode", value = "关联业务表的code(服务项执行计划id)")
            @RequestParam(value = "relationCode", required = false) String relationCode,
            @ApiParam(name = "type", value = "咨询类型:1专家咨询 14导诊助手 17专家视频咨询 28康复咨询")
            @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(name = "source", value = "咨询类型来源")
            @RequestParam(value = "source", required = false) String source) throws Exception {
        System.out.println("symptoms=" + symptoms);
        if (type == null) {
            type = 1;
        }
        ConsultTeamDo consult = new ConsultTeamDo();
        // 设置咨询类型:1专家咨询  14导诊助手
        consult.setType(type);
        // 设置发病时间
        consult.setWhen(when);
        // 设置主要症状
        consult.setSymptoms(symptoms);
        // 设置咨询图片URL
        consult.setImages(images);
        // 设置咨询语音URL
        consult.setVoice(voice);
        consult.setDoctor(doctor);
        consult.setPatient(patient);
        // 保存到数据库
//		int res = 0;
//		JSONArray dts = null;
		synchronized (patient.intern()){//新增同步方法。设备保存写在service层但是不生效,写在controller层才生效
			JSONObject re = null;
			re = imService.addTeamConsult(consult, patient,doctor,source,relationCode);
        synchronized (patient.intern()) {//新增同步方法。设备保存写在service层但是不生效,写在controller层才生效
            JSONObject re = null;
            re = imService.addTeamConsult(consult, patient, doctor, source, relationCode);
//			res = re.getInteger("status");
//			dts = re.containsKey("doctor")?re.getJSONArray("doctor"):null;
			if (payFlag){
				//线上问诊支付提醒
				if (type==17||type==1){
					SystemMessageDO systemMessageDO = new SystemMessageDO();
					systemMessageDO.setTitle("支付提醒");
					systemMessageDO.setType("11");
					systemMessageDO.setSender(re.getString("doctor"));
					systemMessageDO.setSenderName(re.getString("doctorName"));
					systemMessageDO.setRelationCode(re.getString("consult"));
					systemMessageDO.setReceiver(re.getString("patient"));
					systemMessageDO.setReceiverName(re.getString("patientName"));
					net.sf.json.JSONObject data = new net.sf.json.JSONObject();
					data.put("name",re.getString("patientName"));
					data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
					data.put("gender",IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
					data.put("question",symptoms);
					data.put("type",type);
					String msg= "";
					/*prescriptionService.sendWxTemplateMsg(wxId,"",consult,type+"","payRemind","");*/
					prescriptionService.saveInquirySystemMessage(null,consult);
					data.put("msg",msg);
					systemMessageDO.setData(data.toString());
					systemMessageService.saveMessage(systemMessageDO);
					BasePatientDO patientDO = basePatientDao.findById(patient).orElse(null);
					if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
						String templateMsgResult = ykyyService.pushNotificationToYktPatient(patientDO.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
					}
				}
			}
			//发送系统消息
			SystemMessageDO systemMessageDO = new SystemMessageDO();
			systemMessageDO.setTitle("新增"+re.getString("title"));
			systemMessageDO.setType("4");
			systemMessageDO.setReceiver(re.getString("doctor"));
			systemMessageDO.setReceiverName(re.getString("doctorName"));
			systemMessageDO.setRelationCode(re.getString("sessiond_id"));
			systemMessageDO.setSender(re.getString("patient"));
			systemMessageDO.setSenderName(re.getString("patientName"));
			net.sf.json.JSONObject data = new net.sf.json.JSONObject();
			data.put("name",re.getString("patientName"));
			data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
			data.put("gender",IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
			data.put("question",symptoms);
			data.put("type",1);
			systemMessageDO.setData(data.toString());
			hospitalSystemMessageService.saveMessage(systemMessageDO);
			BaseDoctorDO d = baseDoctorDao.findByIdAndDel(re.getString("doctor"));
			BasePatientDO p = basePatientDao.findById(re.getString("patient")).orElse(null);
			
			try {
				//眼科支付订单
				if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
					BusinessOrderDO businessOrderDO = new BusinessOrderDO();
					businessOrderDO.setDoctor(doctor);
					businessOrderDO.setRematk(symptoms);
					businessOrderDO.setPatient(patient);
					businessOrderDO.setPatientName(re.getString("patientName"));
					businessOrderDO.setDescription("专家咨询费");
					businessOrderDO.setOrderCategory("1");
					if (type==1){
						businessOrderDO.setOrderType(1);
						businessOrderDO.setRelationCode(re.getString("consult"));
						businessOrderDO.setRelationName("新增专家咨询");
					}else if (type==17){
						businessOrderDO.setOrderType(3);
						businessOrderDO.setRelationCode(re.getString("consult"));
						businessOrderDO.setRelationName("新增专家咨询");
					}
					businessOrderService.saveOrder(businessOrderDO);
				}else if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
					Double price = 0.0;
					if(d!=null&& org.apache.commons.lang3.StringUtils.isNoneBlank(d.getFee())){
						price = Double.parseDouble(d.getFee());
					}
					ConsultDo consultDo = consultDao.findById(re.getString("consult")).orElse(null);
					if (price==0.0){
						consultDo.setPayStatus(1);
						consultDao.save(consultDo);
					}
					businessOrderService.recharge(re.getString("consult"),"新增专家咨询","1","专家咨询费",patient,re.getString("patientName"),doctor,price);
				}else if (wxId.equalsIgnoreCase("xm_xzzx_wx")){
					Double price = 0.0;
					if(d!=null&& org.apache.commons.lang3.StringUtils.isNoneBlank(d.getFee())){
						price = Double.parseDouble(d.getFee());
					}
					ConsultDo consultDo = consultDao.findById(re.getString("consult")).orElse(null);
					if (price==0.0){
						consultDo.setPayStatus(1);
						consultDao.save(consultDo);
					}
					businessOrderService.recharge(re.getString("consult"),"新增专家咨询","1","专家咨询费",patient,re.getString("patientName"),doctor,price);
				}
			}catch (Exception e){
			    logger.info("支付订单失败:"+e.getMessage());
			}
			//发送企业号推送
			try{
				
				
				if("zsyy".equals(qywxId)){
					String url = qywxUrl+"/ims-app-web/#/onlineChat/chatroom?rstitle="+p.getName()+"%20专家咨询&type="+type+"&sessionId="+re.getString("sessiond_id");
					logger.info("发送企业号url:"+url);
					enterpriseService.sendMKMesByMobile(qywxId,d.getMobile(),"您的专家咨询有新的消息,请您尽快回复[查看详情]("+url+")");
				}else if("xm_xzzx_wx".equals(qywxId)){
					String roomUrl = "pages/doctor/index?opath=/onlineChat/chatroom&rstitle="+p.getName()+"%20专家咨询&type="+type+"&sessionId="+re.getString("sessiond_id");
					logger.info("发送企业号url:"+roomUrl);
					enterpriseService.sendXCXMesByDoctor(qywxId,
							re.getString("doctor"),
							"wx53f6bb4ac081d840",
							roomUrl,
							p.getName()+"%20专家咨询","您有新的咨询消息",false,"");
				}else{}
				
				
			}catch (Exception e){
				logger.info("发送企业号失败"+e.toString());
			}
			if(!"zsyy".equals(qywxId) && !"xm_xzzx_wx".equals(qywxId)){
				//发送厦门i健康智能推送
				try{
					String wxurl = wlyyUrl+"/im/common/message/sendDoctorTemplateByDoctorIdcard?sessionId="+p.getId()+"_"+d.getId()+"_1&sessionType=1&from="+p.getId()+"&content="+URLEncoder.encode(symptoms)+"&businessType=1&doctor_idcard="+d.getIdcard()+"&patientName="+URLEncoder.encode(p.getName())+"&url=1";
					logger.info("发送厦门i健康智能推送url:"+wxurl);
					wlyyBusinessService.sendDoctorTemplateByDoctorIdcard(wxurl);
				}catch (Exception e){
					logger.info("发送厦门i健康智能失败"+e.toString());
				}
			}
		}
		return success("操作成功", consult);
	}
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.patientInfo)
	@ApiOperation(value = "根据居民ID获取居民详情信息", notes = "根据居民ID获取居民详情信息")
	public Envelop patientInfo(
			@ApiParam(name = "patient", value = "居民CODE")
			@RequestParam(value = "patient",required = false) String patient) throws Exception {
		try {
			BasePatientDO result = basePatientService.findByIdAndDel(patient);
			//---居民性别取身份证字段--
			result.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(result.getIdcard())));
			if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
				familyMemberService.saveYktFamily(patient);
			}
			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.finish)
	@ApiOperation(value = "居民结束咨询", notes = "居民结束咨询")
	public Envelop finish(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult,
			@ApiParam(name = "patientCode", value = "居民COEE")
			@RequestParam(value = "patientCode",required = false) String patientCode
			) throws Exception {
		int resutl = imService.finish(consult,patientCode,1);
		//医生未回复可以退费
		try {
			businessOrderService.consultRefund(consult,wxId);
		}catch (Exception e){
			e.printStackTrace();
		}
		BasePatientDO basePatientDO = basePatientService.findByIdAndDel(patientCode);
		JSONObject msgObj = new JSONObject();
		msgObj.put("msg",basePatientDO.getName()+"结束了咨询");
		msgObj.put("consultcode",consult);
		String jsonStr = "";
		if ("xm_zsyy_wx".equalsIgnoreCase(wxId)){
		//结束时医生未开处方则发送模板消息结算
		ConsultDo cons = consultDao.findById(consult).orElse(null);
		if (org.apache.commons.lang3.StringUtils.isNoneBlank(cons.getRelationCode())){
			WlyyOutpatientDO outpatientDO = outpatientDao.findById(cons.getRelationCode()).orElse(null);
			List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutpatientId(outpatientDO.getId());
			if (wlyyPrescriptionDOS==null||wlyyPrescriptionDOS.size()==0){
				logger.info("发送诊查费支付模板消息start");
				BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient()).orElse(null);
				String userName = null;
				String idcard = null;
				if (patientDO != null) {
					userName = patientDO.getName();
					idcard = patientDO.getIdcard();
				}
				PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(outpatientDO.getConsumer());
				String userNo = null;
				if (patientMappingDO != null) {
					userNo = patientMappingDO.getMappingCode();
				}
				String cardNo = null;
				if (org.apache.commons.lang3.StringUtils.isNoneBlank(outpatientDO.getCardNo())) {
					cardNo = outpatientDO.getCardNo();
				}
				String free = 0+"";
				String date=DateUtil.dateToStr(outpatientDO.getRegisterDate(), "yyyyMMddHHmmss");
				if (org.apache.commons.lang3.StringUtils.isNoneBlank(outpatientDO.getRealOrder())){
					net.sf.json.JSONObject object =entranceService.BS15054(patientMappingDO.getMappingCode(),outpatientDO.getRealOrder(),false);
					if(object!=null){
						net.sf.json.JSONObject res = object.getJSONObject("resquest");
						String rsCode = res.getString("@RESULT");
						if ("0".equals(rsCode)) {
							if (res.getString("@settle_flag").equalsIgnoreCase("N")){
								free = res.getString("@total_charge");
							}
						}
						logger.info("获取待结算数据 res: " + res.toString());
					}
				}
				List<WlyyOutpatientDO> outpatientDOS = outpatientDao.findByRegisterNoList(outpatientDO.getRegisterNo());
				if (outpatientDOS!=null&&outpatientDOS.size()>1){
					outpatientDO.setHisStatus(1);
				}else {
					prescriptionService.sendWxTemplateMsg(wxId, outpatientDO.getId(), null,"", "diagnoPayRemind", "");
				}
            if (payFlag) {
                //线上问诊支付提醒
                if (type == 17 || type == 1) {
                    SystemMessageDO systemMessageDO = new SystemMessageDO();
                    systemMessageDO.setTitle("支付提醒");
                    systemMessageDO.setType("11");
                    systemMessageDO.setSender(re.getString("doctor"));
                    systemMessageDO.setSenderName(re.getString("doctorName"));
                    systemMessageDO.setRelationCode(re.getString("consult"));
                    systemMessageDO.setReceiver(re.getString("patient"));
                    systemMessageDO.setReceiverName(re.getString("patientName"));
                    net.sf.json.JSONObject data = new net.sf.json.JSONObject();
                    data.put("name", re.getString("patientName"));
                    data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
                    data.put("gender", IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
                    data.put("question", symptoms);
                    data.put("type", type);
                    String msg = "";
                    /*prescriptionService.sendWxTemplateMsg(wxId,"",consult,type+"","payRemind","");*/
                    prescriptionService.saveInquirySystemMessage(null, consult);
                    data.put("msg", msg);
                    systemMessageDO.setData(data.toString());
                    systemMessageService.saveMessage(systemMessageDO);
                    BasePatientDO patientDO = basePatientDao.findById(patient).orElse(null);
                    if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
                        String templateMsgResult = ykyyService.pushNotificationToYktPatient(patientDO.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
                    }
                }
            }
            //发送系统消息
            SystemMessageDO systemMessageDO = new SystemMessageDO();
            systemMessageDO.setTitle("新增" + re.getString("title"));
            systemMessageDO.setType("4");
            systemMessageDO.setReceiver(re.getString("doctor"));
            systemMessageDO.setReceiverName(re.getString("doctorName"));
            systemMessageDO.setRelationCode(re.getString("sessiond_id"));
            systemMessageDO.setSender(re.getString("patient"));
            systemMessageDO.setSenderName(re.getString("patientName"));
            net.sf.json.JSONObject data = new net.sf.json.JSONObject();
            data.put("name", re.getString("patientName"));
            data.put("age", IdCardUtil.getAgeForIdcard(re.getString("patient_idcard")));
            data.put("gender", IdCardUtil.getSexForIdcard_new(re.getString("patient_idcard")));
            data.put("question", symptoms);
            data.put("type", 1);
            systemMessageDO.setData(data.toString());
            hospitalSystemMessageService.saveMessage(systemMessageDO);
            BaseDoctorDO d = baseDoctorDao.findByIdAndDel(re.getString("doctor"));
            BasePatientDO p = basePatientDao.findById(re.getString("patient")).orElse(null);
            try {
                //眼科支付订单
                if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                    BusinessOrderDO businessOrderDO = new BusinessOrderDO();
                    businessOrderDO.setDoctor(doctor);
                    businessOrderDO.setRematk(symptoms);
                    businessOrderDO.setPatient(patient);
                    businessOrderDO.setPatientName(re.getString("patientName"));
                    businessOrderDO.setDescription("专家咨询费");
                    businessOrderDO.setOrderCategory("1");
                    if (type == 1) {
                        businessOrderDO.setOrderType(1);
                        businessOrderDO.setRelationCode(re.getString("consult"));
                        businessOrderDO.setRelationName("新增专家咨询");
                    } else if (type == 17) {
                        businessOrderDO.setOrderType(3);
                        businessOrderDO.setRelationCode(re.getString("consult"));
                        businessOrderDO.setRelationName("新增专家咨询");
                    }
                    businessOrderService.saveOrder(businessOrderDO);
                } else if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                    Double price = 0.0;
                    if (d != null && org.apache.commons.lang3.StringUtils.isNoneBlank(d.getFee())) {
                        price = Double.parseDouble(d.getFee());
                    }
                    ConsultDo consultDo = consultDao.findById(re.getString("consult")).orElse(null);
                    if (price == 0.0) {
                        consultDo.setPayStatus(1);
                        consultDao.save(consultDo);
                    }
                    businessOrderService.recharge(re.getString("consult"), "新增专家咨询", "1", "专家咨询费", patient, re.getString("patientName"), doctor, price);
                } else if (wxId.equalsIgnoreCase("xm_xzzx_wx")) {
                    Double price = 0.0;
                    if (d != null && org.apache.commons.lang3.StringUtils.isNoneBlank(d.getFee())) {
                        price = Double.parseDouble(d.getFee());
                    }
                    ConsultDo consultDo = consultDao.findById(re.getString("consult")).orElse(null);
                    if (price == 0.0) {
                        consultDo.setPayStatus(1);
                        consultDao.save(consultDo);
                    }
                    businessOrderService.recharge(re.getString("consult"), "新增专家咨询", "1", "专家咨询费", patient, re.getString("patientName"), doctor, price);
                }
            } catch (Exception e) {
                logger.info("支付订单失败:" + e.getMessage());
            }
            //发送企业号推送
            try {
                if ("zsyy".equals(qywxId)) {
                    String url = qywxUrl + "/ims-app-web/#/onlineChat/chatroom?rstitle=" + p.getName() + "%20专家咨询&type=" + type + "&sessionId=" + re.getString("sessiond_id");
                    logger.info("发送企业号url:" + url);
                    enterpriseService.sendMKMesByMobile(qywxId, d.getMobile(), "您的专家咨询有新的消息,请您尽快回复[查看详情](" + url + ")");
                } else if ("xm_xzzx_wx".equals(qywxId)) {
                    String roomUrl = "pages/doctor/index?opath=/onlineChat/chatroom&rstitle=" + p.getName() + "%20专家咨询&type=" + type + "&sessionId=" + re.getString("sessiond_id");
                    logger.info("发送企业号url:" + roomUrl);
                    enterpriseService.sendXCXMesByDoctor(qywxId,
                            re.getString("doctor"),
                            "wx53f6bb4ac081d840",
                            roomUrl,
                            p.getName() + "%20专家咨询", "您有新的咨询消息", false, "");
                } else {
                }
            } catch (Exception e) {
                logger.info("发送企业号失败" + e.toString());
            }
            if (!"zsyy".equals(qywxId) && !"xm_xzzx_wx".equals(qywxId)) {
                //发送厦门i健康智能推送
                try {
                    String wxurl = wlyyUrl + "/im/common/message/sendDoctorTemplateByDoctorIdcard?sessionId=" + p.getId() + "_" + d.getId() + "_1&sessionType=1&from=" + p.getId() + "&content=" + URLEncoder.encode(symptoms) + "&businessType=1&doctor_idcard=" + d.getIdcard() + "&patientName=" + URLEncoder.encode(p.getName()) + "&url=1";
                    logger.info("发送厦门i健康智能推送url:" + wxurl);
                    wlyyBusinessService.sendDoctorTemplateByDoctorIdcard(wxurl);
                } catch (Exception e) {
                    logger.info("发送厦门i健康智能失败" + e.toString());
                }
            }
        }
        return success("操作成功", consult);
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.patientInfo)
    @ApiOperation(value = "根据居民ID获取居民详情信息", notes = "根据居民ID获取居民详情信息")
    public Envelop patientInfo(
            @ApiParam(name = "patient", value = "居民CODE")
            @RequestParam(value = "patient", required = false) String patient) throws Exception {
        try {
            BasePatientDO result = basePatientService.findByIdAndDel(patient);
            //---居民性别取身份证字段--
            result.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(result.getIdcard())));
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                familyMemberService.saveYktFamily(patient);
            }
            return success(result);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.finish)
    @ApiOperation(value = "居民结束咨询", notes = "居民结束咨询")
    public Envelop finish(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = false) String consult,
            @ApiParam(name = "patientCode", value = "居民COEE")
            @RequestParam(value = "patientCode", required = false) String patientCode
    ) throws Exception {
        int resutl = imService.finish(consult, patientCode, 1);
        //医生未回复可以退费
        try {
            businessOrderService.consultRefund(consult, wxId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BasePatientDO basePatientDO = basePatientService.findByIdAndDel(patientCode);
        JSONObject msgObj = new JSONObject();
        msgObj.put("msg", basePatientDO.getName() + "结束了咨询");
        msgObj.put("consultcode", consult);
        String jsonStr = "";
        if ("xm_zsyy_wx".equalsIgnoreCase(wxId)) {
            //结束时医生未开处方则发送模板消息结算
            ConsultDo cons = consultDao.findById(consult).orElse(null);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(cons.getRelationCode())) {
                WlyyOutpatientDO outpatientDO = outpatientDao.findById(cons.getRelationCode()).orElse(null);
                List<WlyyPrescriptionDO> wlyyPrescriptionDOS = prescriptionDao.findByOutpatientId(outpatientDO.getId());
                if (wlyyPrescriptionDOS == null || wlyyPrescriptionDOS.size() == 0) {
                    logger.info("发送诊查费支付模板消息start");
                    BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient()).orElse(null);
                    String userName = null;
                    String idcard = null;
                    if (patientDO != null) {
                        userName = patientDO.getName();
                        idcard = patientDO.getIdcard();
                    }
                    PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(outpatientDO.getConsumer());
                    String userNo = null;
                    if (patientMappingDO != null) {
                        userNo = patientMappingDO.getMappingCode();
                    }
                    String cardNo = null;
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(outpatientDO.getCardNo())) {
                        cardNo = outpatientDO.getCardNo();
                    }
                    String free = 0 + "";
                    String date = DateUtil.dateToStr(outpatientDO.getRegisterDate(), "yyyyMMddHHmmss");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(outpatientDO.getRealOrder())) {
                        net.sf.json.JSONObject object = entranceService.BS15054(patientMappingDO.getMappingCode(), outpatientDO.getRealOrder(), false);
                        if (object != null) {
                            net.sf.json.JSONObject res = object.getJSONObject("resquest");
                            String rsCode = res.getString("@RESULT");
                            if ("0".equals(rsCode)) {
                                if (res.getString("@settle_flag").equalsIgnoreCase("N")) {
                                    free = res.getString("@total_charge");
                                }
                            }
                            logger.info("获取待结算数据 res: " + res.toString());
                        }
                    }
                    List<WlyyOutpatientDO> outpatientDOS = outpatientDao.findByRegisterNoList(outpatientDO.getRegisterNo());
                    if (outpatientDOS != null && outpatientDOS.size() > 1) {
                        outpatientDO.setHisStatus(1);
                    } else {
                        prescriptionService.sendWxTemplateMsg(wxId, outpatientDO.getId(), null, "", "diagnoPayRemind", "");
                    }
				/*if (!free.equalsIgnoreCase("0")){
					ylzPayService.msgPush("01", cardNo, "01", patientDO.getMobile(), "00", userNo, userName, idcard, outpatientDO.getXtgzh(), outpatientDO.getDeptName(), outpatientDO.getDoctorName(), date, free, "1","WX_PUB");
				}*/
				logger.info("发送诊查费支付模板消息end");
			}
			outpatientDO.setEndTime(new Date());
			outpatientDao.save(outpatientDO);
		}
		}
		if(1 == resutl){
			jsonStr = "{\"id\":\""+UUID.randomUUID().toString()+"\",\"sender_id\":\""+patientCode+"\",\"sender_name\":\"系统\",\"timestamp\":"+new Date().getTime()+",\"content_type\":7,\"content\":"+msgObj.toString()+",\"business_type\":1}";
		}
                    logger.info("发送诊查费支付模板消息end");
                }
                outpatientDO.setEndTime(new Date());
                outpatientDao.save(outpatientDO);
            }
        }
        if (1 == resutl) {
            jsonStr = "{\"id\":\"" + UUID.randomUUID().toString() + "\",\"sender_id\":\"" + patientCode + "\",\"sender_name\":\"系统\",\"timestamp\":" + new Date().getTime() + ",\"content_type\":7,\"content\":" + msgObj.toString() + ",\"business_type\":1}";
        }
//		else{
//			throw  new Exception("结束失败");
//		}
		return success(jsonStr);
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getTopic)
	@ApiOperation(value = "根据咨询CODE获取session_id", notes = "根据咨询CODE获取session_id")
	public Envelop getTopic(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = false) String consult)throws Exception {
		try {
			return success("请求成功",imService.getTopic(consult));
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getConsultCodeByOutpatientId)
	@ApiOperation(value = "根据复诊记录ID获取咨询CODE", notes = "根据复诊记录ID获取咨询CODE")
	public Envelop getConsultCodeByOutpatientId(
			@ApiParam(name = "outpatientid", value = "复诊ID")
			@RequestParam(value = "outpatientid",required = true) String outpatientid)throws Exception {
		try {
			return success("请求成功",imService.getConsultCodeByOutpatientId(outpatientid));
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.evaluationByConsultCode)
	@ApiOperation(value = "评价咨询", notes = "评价咨询")
	public Envelop evaluationByConsultCode(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult,
			@ApiParam(name = "scoreContent", value = "评价内容")
			@RequestParam(value = "scoreContent",required = false) String scoreContent,
			@ApiParam(name = "type", value = "1、实名,2、匿名")
			@RequestParam(value = "type",required = true) Integer type,
			@ApiParam(name = "bannerList",value = "锦旗")
			@RequestParam(value = "bannerList",required = false) String bannerList)throws Exception{
        return success(jsonStr);
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.getTopic)
    @ApiOperation(value = "根据咨询CODE获取session_id", notes = "根据咨询CODE获取session_id")
    public Envelop getTopic(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = false) String consult) throws Exception {
        try {
            return success("请求成功", imService.getTopic(consult));
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.getConsultCodeByOutpatientId)
    @ApiOperation(value = "根据复诊记录ID获取咨询CODE", notes = "根据复诊记录ID获取咨询CODE")
    public Envelop getConsultCodeByOutpatientId(
            @ApiParam(name = "outpatientid", value = "复诊ID")
            @RequestParam(value = "outpatientid", required = true) String outpatientid) throws Exception {
        try {
            return success("请求成功", imService.getConsultCodeByOutpatientId(outpatientid));
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.evaluationByConsultCode)
    @ApiOperation(value = "评价咨询", notes = "评价咨询")
    public Envelop evaluationByConsultCode(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = true) String consult,
            @ApiParam(name = "scoreContent", value = "评价内容")
            @RequestParam(value = "scoreContent", required = false) String scoreContent,
            @ApiParam(name = "type", value = "1、实名,2、匿名")
            @RequestParam(value = "type", required = true) Integer type,
            @ApiParam(name = "bannerList", value = "锦旗")
            @RequestParam(value = "bannerList", required = false) String bannerList) throws Exception {
//		if(StringUtils.isEmpty(scoreContent)){
//			scoreContent= "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"测试评语。。。。123123\"}]";
//		}
		try {
			imService.evaluationByConsultCode(consult,scoreContent,type,bannerList);
			return success("请求成功");
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getEvaluationByConsultCode)
	@ApiOperation(value = "根据咨询CODE获取评价", notes = "根据咨询CODE获取评价")
	public ListEnvelop getEvaluationByConsultCode(
			@ApiParam(name = "consult", value = "咨询CODE")
			@RequestParam(value = "consult",required = true) String consult)throws Exception{
        try {
            imService.evaluationByConsultCode(consult, scoreContent, type, bannerList);
            return success("请求成功");
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.getEvaluationByConsultCode)
    @ApiOperation(value = "根据咨询CODE获取评价", notes = "根据咨询CODE获取评价")
    public ListEnvelop getEvaluationByConsultCode(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult", required = true) String consult) throws Exception {
//		if(StringUtils.isEmpty(scoreContent)){
//			scoreContent= "[{\"scoreType\":\"1\",\"score\":100,\"content\":\"\"},{\"scoreType\":\"2\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"3\",\"score\":80,\"content\":\"\"},{\"scoreType\":\"4\",\"score\":0,\"content\":\"测试评语。。。。123123\"}]";
//		}
		try {
			return success("请求成功",imService.getEvaluationByConsultCode(consult));
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.getSign)
	@ApiOperation(value = "获取微信签名", notes = "获取微信签名")
	public Envelop getSign(@ApiParam(name = "pageUrl", value = "授权页面")
	                       @RequestParam(value = "pageUrl", required = true)String pageUrl,
	                       @ApiParam(name = "wxId", value = "微信id")
	                       @RequestParam(value = "wxId", required = true)String wxId) throws Exception {
		try {
			logger.info("pageUrl="+pageUrl);
			logger.info("wxId="+wxId);
			String ticket = wechatInfoService.getJsapi_ticketByToken(wxId);
			WxWechatDO wxWechatDO = wechatDao.findByIdAndStatus(wxId);
			Map<Object, Object> map = new HashMap<Object, Object>();
			if (ticket != null) {
				String noncestr = UUID.randomUUID().toString();
				long timestamp = System.currentTimeMillis() / 1000;
				String url = pageUrl;
				logger.info("getSign.url="+url);
				String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
				logger.info("getSign.str="+str);
				// sha1加密
				String signature = SHA1(str);
				map.put("noncestr", noncestr);
				map.put("timestamp", timestamp);
				map.put("signature", signature);
				map.put("appid", wxWechatDO.getAppId());
				return success(PatientRequestMapping.Wechat.api_success,map);
			}
			return failed(PatientRequestMapping.Wechat.api_error);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	/**
	 * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串
	 **/
	public String SHA1(String str) throws Exception {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexStr = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexStr.append(0);
				}
				hexStr.append(shaHex);
			}
			return hexStr.toString();
			
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.getPatientGuaidenceConsult)
	@ApiOperation(value = "导诊的咨询对话", notes = "导诊的咨询对话")
	public Envelop getPatientGuaidenceConsult(@ApiParam(name = "patientCode", value = "居民CODE")
												  @RequestParam(value = "patientCode", required = true)String patientCode,
											  @ApiParam(name = "type", value = "_guidance_14 导诊收")
											  @RequestParam(value = "type", required = true)String type) throws Exception {
		try {
			String session_id = patientCode+type;
			session_id = imService.getPatientGuaidenceConsult(patientCode,session_id,type);
			return success(session_id);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.sessionIsExist)
	@ApiOperation(value = "判断导诊sessionId是否存在", notes = "判断导诊sessionId是否存在")
	public Envelop sessionIsExist(@ApiParam(name = "patientCode", value = "居民CODE")
											  @RequestParam(value = "patientCode", required = true)String patientCode,
											  @ApiParam(name = "type", value = "type")
											  @RequestParam(value = "type", required = false)String type) throws Exception {
		try {
			String session_id = null;
			if (org.apache.commons.lang3.StringUtils.isNoneBlank(type)){
				session_id = patientCode+"_guidance_"+type;
			}
			Boolean re = imUtil.sessionIsExist(session_id);
			return success(re);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.updateConsultParticipant)
	@ApiOperation(value = "更新会话成员(新增或删除)", notes = "更新会话成员(新增或删除)")
	public Envelop updateConsultParticipant(@ApiParam(name = "sessionid", value = "会话ID", defaultValue = "1")
	                                       @RequestParam(value = "sessionid", required = true) String sessionid,
	                                       @ApiParam(name = "userid", value = "新增成员ID,多个以英文逗号隔开", defaultValue = "1")
	                                       @RequestParam(value = "userid", required = true) String userid,
	                                       @ApiParam(name = "olduserid", value = "删除的成员id")
	                                       @RequestParam(value = "olduserid", required = false) String olduserid)throws Exception{
		try {
			imService.updateParticipant(sessionid,userid,olduserid);
			return success("操作成功");
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.PatientIM.patientGuaidenceAppend)
	@ApiOperation(value = "居民导诊会话发送消息", notes = "居民导诊会话发送消息")
	public Envelop patientGuaidenceAppend(
			@ApiParam(name = "sender_id", value = "发送者id", defaultValue = "")
			@RequestParam(value = "sender_id", required = true) String sender_id,
			@ApiParam(name = "sender_name", value = "发送者姓名", defaultValue = "")
			@RequestParam(value = "sender_name", required = true) String sender_name,
			@ApiParam(name = "session_id", value = "session_id", defaultValue = "")
			@RequestParam(value = "session_id", required = false) String session_id,
			@ApiParam(name = "content_type", value = "内容类型", defaultValue = "")
			@RequestParam(value = "content_type", required = true) String content_type,
			@ApiParam(name = "content", value = "消息内容", defaultValue = "")
			@RequestParam(value = "content", required = true) String content,
			@ApiParam(name = "extend", value = "扩展内容", defaultValue = "")
			@RequestParam(value = "extend", required = false) String extend,
			@ApiParam(name = "type", value = "咨询type", defaultValue = "")
			@RequestParam(value = "type", required = false) String type,
			@ApiParam(name = "times", value = "times", defaultValue = "")
			@RequestParam(value = "times", required = false) Integer times,
			@ApiParam(name = "wechat_appid", value = "wechat_appid", defaultValue = "")
			@RequestParam(value = "wechat_appid", required = false) String wechat_appid
	){
		try {
			//处理语音文件
			if(!org.springframework.util.StringUtils.isEmpty(wechat_appid)){
				if("3".equalsIgnoreCase(content_type)){//语音文件
					String voicepath = imService.fetchWxVoices(wechat_appid);
					logger.info("voice_path:"+voicepath);
					JSONObject obj = new JSONObject();
					String voiceurl = "";
					// 将临时语音拷贝到正式存储路径下
					if (org.apache.commons.lang3.StringUtils.isNotEmpty(voicepath)) {
						if("xm_ihealth_wx".equals(wechat_appid)){
							logger.info("voice_wx_type:"+wechat_appid);
							voiceurl = fileUploadService.uploadWxVoice(voicepath);
						}else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid)){
							voiceurl = fileUploadService.uploadWxVoiceToEntrance(remote_inner_url,voicepath);
							logger.info(voiceurl);
						}else {
							voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
						}
						obj.put("path", voiceurl);
						obj.put("times", times);
						content = obj.toString();
					}
				}else if("2".equalsIgnoreCase(content_type)){//图片文件
					String imagepath = imService.fetchWxImages(wechat_appid);
					logger.info("image_path:"+imagepath);
					JSONObject obj = new JSONObject();
					String imgeUrl = "";
					// 将临时语音拷贝到正式存储路径下
					if (org.apache.commons.lang3.StringUtils.isNotEmpty(imagepath)) {
						if("xm_ihealth_wx".equals(wechat_appid)){
							logger.info("imge_wx_type:"+wechat_appid);
							imgeUrl = fileUploadService.uploadWxImage(imagepath);
						}else{
							imgeUrl = fileUtil.copyTempVoice(imagepath,fastdfs_file_url);
						}
						content = imgeUrl;
					}
				}else{
				}
			}
			content = StringUtils.isNotEmpty(content)?content.trim():content;
			Map<String,JSONObject> map = robotService.robotReply(session_id,type,content);
			session_id = imService.getPatientGuaidenceConsult(sender_id,session_id,type);
			String result = imService.patientGuaidenceAppend(sender_id,sender_name,session_id,content_type,content,"1",extend);
			robotService.sendReplyMap(map);
			//消息存在时文本及问题集类型发送时自动回复
			robotService.replyGuaidenceContent(session_id,type,content,content_type,"1",extend);
			List<BaseDoctorRoleDO> doctorRoleDOS = doctorRoleDao.findByRoleCode("guidance");
			for (BaseDoctorRoleDO doctorRoleDO:doctorRoleDOS){
				System.out.println("发送外层SOCKET消息:通知医生导诊");
				JSONObject object = new JSONObject();
				object.put("socket_sms_type",13);
				object.put("relation_code",session_id);
				imService.sendWaiSocketMessage(sender_id,doctorRoleDO.getDoctorCode(),object.toString(),"1");
			}
			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	
	
	@GetMapping(value = BaseHospitalRequestMapping.PatientIM.getDoctorConsultCount)
	@ApiOperation(value = "医生端:查询会话视频邀请状态", notes = "医生端:查询会话视频邀请状态")
	public Envelop getDoctorConsultCount(@ApiParam(name = "doctorids", value = "会话ID")
	                                     @RequestParam(value = "doctorids",required = true) String doctorids)throws Exception  {
		return success("查询成功",imService.getDoctorConsultCount(doctorids));
		
	}
	
	
	@PostMapping(value = BaseHospitalRequestMapping.Prescription.followOrgByPatient)
	@ApiOperation(value = "居民关注医院", notes = "居民关注医院")
	public Envelop followOrgByPatient(
			@ApiParam(name = "patientid", value = "居民ID", defaultValue = "")
			@RequestParam(value = "patientid", required = true) String patientid,
			@ApiParam(name = "orgid", value = "医生ID", defaultValue = "")
			@RequestParam(value = "orgid", required = true) String orgid,
			@ApiParam(name = "type", value = "1关注 0取消关注", defaultValue = "")
			@RequestParam(value = "type", required = true) String type
	)throws Exception{
		prescriptionService.followOrgByPatient(patientid,orgid,type);
		return success("操作成功!");
	}
	@GetMapping(value = BaseHospitalRequestMapping.Prescription.selectByGuidance)
	@ApiOperation(value = "查询是否有导诊助手", notes = "查询是否有导诊助手")
	public MixEnvelop selectByGuidance()throws Exception{
		return MixEnvelop.getSuccessList("查询成功",doctorInfoService.selectByGuidance());
	}
        try {
            return success("请求成功", imService.getEvaluationByConsultCode(consult));
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.getSign)
    @ApiOperation(value = "获取微信签名", notes = "获取微信签名")
    public Envelop getSign(@ApiParam(name = "pageUrl", value = "授权页面")
                           @RequestParam(value = "pageUrl", required = true) String pageUrl,
                           @ApiParam(name = "wxId", value = "微信id")
                           @RequestParam(value = "wxId", required = true) String wxId) throws Exception {
        try {
            logger.info("pageUrl=" + pageUrl);
            logger.info("wxId=" + wxId);
            String ticket = wechatInfoService.getJsapi_ticketByToken(wxId);
            WxWechatDO wxWechatDO = wechatDao.findByIdAndStatus(wxId);
            Map<Object, Object> map = new HashMap<Object, Object>();
            if (ticket != null) {
                String noncestr = UUID.randomUUID().toString();
                long timestamp = System.currentTimeMillis() / 1000;
                String url = pageUrl;
                logger.info("getSign.url=" + url);
                String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
                logger.info("getSign.str=" + str);
                // sha1加密
                String signature = SHA1(str);
                map.put("noncestr", noncestr);
                map.put("timestamp", timestamp);
                map.put("signature", signature);
                map.put("appid", wxWechatDO.getAppId());
                return success(PatientRequestMapping.Wechat.api_success, map);
            }
            return failed(PatientRequestMapping.Wechat.api_error);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    /**
     * @description: SHA、SHA1加密 @parameter: str:待加密字符串 @return: 加密串
     **/
    public String SHA1(String str) throws Exception {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.getPatientGuaidenceConsult)
    @ApiOperation(value = "导诊的咨询对话", notes = "导诊的咨询对话")
    public Envelop getPatientGuaidenceConsult(@ApiParam(name = "patientCode", value = "居民CODE")
                                              @RequestParam(value = "patientCode", required = true) String patientCode,
                                              @ApiParam(name = "type", value = "_guidance_14 导诊收")
                                              @RequestParam(value = "type", required = true) String type) throws Exception {
        try {
            String session_id = patientCode + type;
            session_id = imService.getPatientGuaidenceConsult(patientCode, session_id, type);
            return success(session_id);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.sessionIsExist)
    @ApiOperation(value = "判断导诊sessionId是否存在", notes = "判断导诊sessionId是否存在")
    public Envelop sessionIsExist(@ApiParam(name = "patientCode", value = "居民CODE")
                                  @RequestParam(value = "patientCode", required = true) String patientCode,
                                  @ApiParam(name = "type", value = "type")
                                  @RequestParam(value = "type", required = false) String type) throws Exception {
        try {
            String session_id = null;
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(type)) {
                session_id = patientCode + "_guidance_" + type;
            }
            Boolean re = imUtil.sessionIsExist(session_id);
            return success(re);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.updateConsultParticipant)
    @ApiOperation(value = "更新会话成员(新增或删除)", notes = "更新会话成员(新增或删除)")
    public Envelop updateConsultParticipant(@ApiParam(name = "sessionid", value = "会话ID", defaultValue = "1")
                                            @RequestParam(value = "sessionid", required = true) String sessionid,
                                            @ApiParam(name = "userid", value = "新增成员ID,多个以英文逗号隔开", defaultValue = "1")
                                            @RequestParam(value = "userid", required = true) String userid,
                                            @ApiParam(name = "olduserid", value = "删除的成员id")
                                            @RequestParam(value = "olduserid", required = false) String olduserid) throws Exception {
        try {
            imService.updateParticipant(sessionid, userid, olduserid);
            return success("操作成功");
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @PostMapping(value = BaseHospitalRequestMapping.PatientIM.patientGuaidenceAppend)
    @ApiOperation(value = "居民导诊会话发送消息", notes = "居民导诊会话发送消息")
    public Envelop patientGuaidenceAppend(
            @ApiParam(name = "sender_id", value = "发送者id", defaultValue = "")
            @RequestParam(value = "sender_id", required = true) String sender_id,
            @ApiParam(name = "sender_name", value = "发送者姓名", defaultValue = "")
            @RequestParam(value = "sender_name", required = true) String sender_name,
            @ApiParam(name = "session_id", value = "session_id", defaultValue = "")
            @RequestParam(value = "session_id", required = false) String session_id,
            @ApiParam(name = "content_type", value = "内容类型", defaultValue = "")
            @RequestParam(value = "content_type", required = true) String content_type,
            @ApiParam(name = "content", value = "消息内容", defaultValue = "")
            @RequestParam(value = "content", required = true) String content,
            @ApiParam(name = "extend", value = "扩展内容", defaultValue = "")
            @RequestParam(value = "extend", required = false) String extend,
            @ApiParam(name = "type", value = "咨询type", defaultValue = "")
            @RequestParam(value = "type", required = false) String type,
            @ApiParam(name = "times", value = "times", defaultValue = "")
            @RequestParam(value = "times", required = false) Integer times,
            @ApiParam(name = "wechat_appid", value = "wechat_appid", defaultValue = "")
            @RequestParam(value = "wechat_appid", required = false) String wechat_appid
    ) {
        try {
            //处理语音文件
            if (!org.springframework.util.StringUtils.isEmpty(wechat_appid)) {
                if ("3".equalsIgnoreCase(content_type)) {//语音文件
                    String voicepath = imService.fetchWxVoices(wechat_appid);
                    logger.info("voice_path:" + voicepath);
                    JSONObject obj = new JSONObject();
                    String voiceurl = "";
                    // 将临时语音拷贝到正式存储路径下
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(voicepath)) {
                        if ("xm_ihealth_wx".equals(wechat_appid)) {
                            logger.info("voice_wx_type:" + wechat_appid);
                            voiceurl = fileUploadService.uploadWxVoice(voicepath);
                        } else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid)) {
                            voiceurl = fileUploadService.uploadWxVoiceToEntrance(remote_inner_url, voicepath);
                            logger.info(voiceurl);
                        } else {
                            voiceurl = fileUtil.copyTempVoice(voicepath, fastdfs_file_url);
                        }
                        obj.put("path", voiceurl);
                        obj.put("times", times);
                        content = obj.toString();
                    }
                } else if ("2".equalsIgnoreCase(content_type)) {//图片文件
                    String imagepath = imService.fetchWxImages(wechat_appid);
                    logger.info("image_path:" + imagepath);
                    JSONObject obj = new JSONObject();
                    String imgeUrl = "";
                    // 将临时语音拷贝到正式存储路径下
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(imagepath)) {
                        if ("xm_ihealth_wx".equals(wechat_appid)) {
                            logger.info("imge_wx_type:" + wechat_appid);
                            imgeUrl = fileUploadService.uploadWxImage(imagepath);
                        } else {
                            imgeUrl = fileUtil.copyTempVoice(imagepath, fastdfs_file_url);
                        }
                        content = imgeUrl;
                    }
                } else {
                }
            }
            content = StringUtils.isNotEmpty(content) ? content.trim() : content;
            Map<String, JSONObject> map = robotService.robotReply(session_id, type, content);
            session_id = imService.getPatientGuaidenceConsult(sender_id, session_id, type);
            String result = imService.patientGuaidenceAppend(sender_id, sender_name, session_id, content_type, content, "1", extend);
            robotService.sendReplyMap(map);
            //消息存在时文本及问题集类型发送时自动回复
            robotService.replyGuaidenceContent(session_id, type, content, content_type, "1", extend);
            List<BaseDoctorRoleDO> doctorRoleDOS = doctorRoleDao.findByRoleCode("guidance");
            for (BaseDoctorRoleDO doctorRoleDO : doctorRoleDOS) {
                System.out.println("发送外层SOCKET消息:通知医生导诊");
                JSONObject object = new JSONObject();
                object.put("socket_sms_type", 13);
                object.put("relation_code", session_id);
                imService.sendWaiSocketMessage(sender_id, doctorRoleDO.getDoctorCode(), object.toString(), "1");
            }
            return success(result);
        } catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping(value = BaseHospitalRequestMapping.PatientIM.getDoctorConsultCount)
    @ApiOperation(value = "医生端:查询会话视频邀请状态", notes = "医生端:查询会话视频邀请状态")
    public Envelop getDoctorConsultCount(@ApiParam(name = "doctorids", value = "会话ID")
                                         @RequestParam(value = "doctorids", required = true) String doctorids) throws Exception {
        return success("查询成功", imService.getDoctorConsultCount(doctorids));
    }
    @PostMapping(value = BaseHospitalRequestMapping.Prescription.followOrgByPatient)
    @ApiOperation(value = "居民关注医院", notes = "居民关注医院")
    public Envelop followOrgByPatient(
            @ApiParam(name = "patientid", value = "居民ID", defaultValue = "")
            @RequestParam(value = "patientid", required = true) String patientid,
            @ApiParam(name = "orgid", value = "医生ID", defaultValue = "")
            @RequestParam(value = "orgid", required = true) String orgid,
            @ApiParam(name = "type", value = "1关注 0取消关注", defaultValue = "")
            @RequestParam(value = "type", required = true) String type
    ) throws Exception {
        prescriptionService.followOrgByPatient(patientid, orgid, type);
        return success("操作成功!");
    }
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.selectByGuidance)
    @ApiOperation(value = "查询是否有导诊助手", notes = "查询是否有导诊助手")
    public MixEnvelop selectByGuidance() throws Exception {
        return MixEnvelop.getSuccessList("查询成功", doctorInfoService.selectByGuidance());
    }
}

+ 26 - 27
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java

@ -1649,7 +1649,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
    public Envelop getDoctorFreeDetail(@RequestParam(required = true) String strJson) {
        try {
            ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
            Map<String, Object>  result = statisticsEsService.getDoctorFreeDetail(qvo);
            Map<String, Object> result = statisticsEsService.getDoctorFreeDetail(qvo);
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
@ -1735,6 +1735,7 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
        try {
            ScreenQvo qvo = JSON.parseObject(strJson, ScreenQvo.class);
            JSONObject result = statisticsEsService.getHealthChart(qvo);
            System.out.println("获取i健康的患者的健康指标数据==>" + JSON.toJSONString(result));
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
@ -1743,60 +1744,58 @@ public class EsStatisticsEndpoint extends EnvelopRestEndpoint {
    }
    @GetMapping(value = BaseHospitalRequestMapping.DodtorIM.records2)
    @ApiOperation(value = "医生咨询记录查询")
    public Envelop records2(
            @ApiParam(name = "doctor", value = "医生id")
            @RequestParam(value = "doctor",required = false) String doctor,
            @RequestParam(value = "doctor", required = false) String doctor,
            @ApiParam(name = "title", value = "咨询标题关键字")
            @RequestParam(value = "title",required = false) String title,
            @RequestParam(value = "title", required = false) String title,
            @ApiParam(name = "patient", value = "患者id")
            @RequestParam(value = "patient",required = false) String patient,
            @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "id", value = "咨询ID")
            @RequestParam(value = "id",required = false) String id,
            @RequestParam(value = "id", required = false) String id,
            @ApiParam(name = "type", value = "咨询类型")
            @RequestParam(value = "type",required = true) String type,
            @RequestParam(value = "type", required = true) String type,
            @ApiParam(name = "status", value = "咨询状态:0全部,1候诊中,2就诊中,3结束")
            @RequestParam(value = "status",required = true) Integer status,
            @RequestParam(value = "status", required = true) Integer status,
            @ApiParam(name = "start_time", value = "开始时间 YYYY-MM-DD HH:MM:SS")
            @RequestParam(value = "start_time",required = false) String start_time,
            @RequestParam(value = "start_time", required = false) String start_time,
            @ApiParam(name = "end_time", value = "结束时间 YYYY-MM-DD HH:MM:SS")
            @RequestParam(value = "end_time",required = false) String end_time,
            @RequestParam(value = "end_time", required = false) String end_time,
            @ApiParam(name = "page", value = "第几页")
            @RequestParam(value = "page",required = false) int page,
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "pagesize", value = "分页大小")
            @RequestParam(value = "pagesize",required = false) int pagesize
    )throws Exception{
            @RequestParam(value = "pagesize", required = false) int pagesize
    ) throws Exception {
        try {
            List<Map<String,Object>>  data = imService.findConsultRecordByDoctorNew(doctor, id,type,status, page,pagesize, title,start_time,end_time,patient);
            List<Map<String, Object>> data = imService.findConsultRecordByDoctorNew(doctor, id, type, status, page, pagesize, title, start_time, end_time, patient);
            if (data != null) {
                for(Map<String,Object> consult :data){
                for (Map<String, Object> consult : data) {
                    //如果是协同门诊,多返回全科医生的详细信息
                    if(12 == Integer.parseInt(consult.get("type").toString()) && StringUtils.isNoneBlank((String)consult.get("generalDoctor"))){
                        BaseDoctorDO baseDoctorDO = baseDoctorDao.findByIdAndDel((String)consult.get("generalDoctor"));
                        List<BaseDoctorHospitalDO> baseDoctorHospitalDOList = baseDoctorHospitalDao.findByDoctorCode((String)consult.get("generalDoctor"));
                        if(baseDoctorDO!=null){
                    if (12 == Integer.parseInt(consult.get("type").toString()) && StringUtils.isNoneBlank((String) consult.get("generalDoctor"))) {
                        BaseDoctorDO baseDoctorDO = baseDoctorDao.findByIdAndDel((String) consult.get("generalDoctor"));
                        List<BaseDoctorHospitalDO> baseDoctorHospitalDOList = baseDoctorHospitalDao.findByDoctorCode((String) consult.get("generalDoctor"));
                        if (baseDoctorDO != null) {
                            consult.put("generalDoctorName", baseDoctorDO.getName());
                        }
                        if (baseDoctorHospitalDOList!=null&&baseDoctorHospitalDOList.size()!=0){
                        if (baseDoctorHospitalDOList != null && baseDoctorHospitalDOList.size() != 0) {
                            BaseDoctorHospitalDO baseDoctorHospitalDO = baseDoctorHospitalDOList.get(0);
                            consult.put("generalOrgName",baseDoctorHospitalDO.getOrgName());
                            consult.put("generalDeptName",baseDoctorHospitalDO.getDeptName());
                            consult.put("generalOrgName", baseDoctorHospitalDO.getOrgName());
                            consult.put("generalDeptName", baseDoctorHospitalDO.getDeptName());
                        }
                    }
                }
            }
            Long total = imService.countConsultRecordByDoctor2(doctor, id,type,status,title,start_time,end_time);
            Long total = imService.countConsultRecordByDoctor2(doctor, id, type, status, title, start_time, end_time);
            JSONObject result = new JSONObject();
            result.put("total",total);
            result.put("list",data);
            result.put("total", total);
            result.put("list", data);
            return success(result);
        } catch (Exception e){
        } catch (Exception e) {
            return failedException(e);
        }
    }

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

@ -11,6 +11,7 @@ import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSubItemDO;
import com.yihu.jw.entity.base.system.SystemDictDO;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.rehabilitation.ServiceItemPlanDao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.door.*;
@ -129,6 +130,9 @@ public class DoorOrderService {
    @Autowired
    ServiceItemPlanDao serviceItemPlanDao;
    @Autowired
    RehabilitationManageService rehabilitationManageService;
    /**
     * 服务项查询
     * type =4

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

@ -724,10 +724,10 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        //关联code不为空情况
        ServiceItemPlanDO serviceItemPlanDO = null;
        if(StringUtils.isNotBlank(orderDO.getRelationCode())){
        if (StringUtils.isNotBlank(orderDO.getRelationCode())) {
            serviceItemPlanDO = serviceItemPlanDao.findById(orderDO.getRelationCode()).orElse(null);
            if(serviceItemPlanDO!=null){
                if("1".equals(serviceItemPlanDO.getStatus())){
            if (serviceItemPlanDO != null) {
                if ("1".equals(serviceItemPlanDO.getStatus())) {
                    throw new ServiceException("请勿重复申请");
                }
                orderDO.setDoctor(serviceItemPlanDO.getDoctor());
@ -738,9 +738,12 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        //保存服务订单
        orderDO = wlyyDoorServiceOrderDao.save(orderDO);
        if(serviceItemPlanDO!=null){
        if (serviceItemPlanDO != null) {
            serviceItemPlanDO.setRelationCode(orderDO.getId());
            rehabilitationManageService.completePlan(serviceItemPlanDO);
            //创建初不应是已完成
//           rehabilitationManageService.completePlan(serviceItemPlanDO);
            //设置为进行中
            rehabilitationManageService.planCarryOuting(serviceItemPlanDO);
        }
        //新增工单与服务项费用关联关系
@ -1614,6 +1617,10 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, "工单服务已取消!");
        //设置为取消状态
        rehabilitationManageService.cancelPlan(orderId);
        System.out.println("设置为取消状态");
        return result;
    }
@ -2275,7 +2282,7 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
                WlyyDoorDoctorStatusDO.Status.serving.getType(),
        });
        if (null == doorDoctorStatusDO) {
            String failMsg = "当前派单的医生不存在或禁止接单" ;
            String failMsg = "当前派单的医生不存在或禁止接单";
            throw new Exception(failMsg);
        }
@ -3044,12 +3051,12 @@ public class WlyyDoorServiceOrderService extends BaseJpaService<WlyyDoorServiceO
    }
    //获取医生列表
    public List<Map<String, Object>> findDoctorList(String name,Integer page,Integer size) {
    public List<Map<String, Object>> findDoctorList(String name, Integer page, Integer size) {
        String sql = "select id,name from base_doctor where del='1' and enabled=1";
        if(StringUtils.isNotBlank(name)){
            sql += " and name like '%"+name+"%'";
        if (StringUtils.isNotBlank(name)) {
            sql += " and name like '%" + name + "%'";
        }
        sql+= " limit "+(page-1)*size+","+size;
        sql += " limit " + (page - 1) * size + "," + size;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

+ 145 - 125
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationManageService.java

@ -99,27 +99,27 @@ public class RehabilitationManageService {
    private FollowUpDao followupDao;
    //近期康复记录
    public Envelop recentServiceItemPlanRecords(String patient,Integer page,Integer size){
    public Envelop recentServiceItemPlanRecords(String patient, Integer page, Integer size) {
        String sql = "select p.* ";
        String countSql = "select count(p.id) ";
        String filter = " from base_service_item_plan p where p.patient='"+patient+"' and p.plan_time<='"+DateUtil.getStringDateShort()+" 23:59:59' ";
        String ordereBy = " order by p.plan_time desc limit "+(page-1)*size+","+size;
        List<ServiceItemPlanDO> planDOList = jdbcTemplate.query(sql+filter+ordereBy,new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
        long count = jdbcTemplate.queryForObject(countSql+filter,Long.class);
        return PageEnvelop.getSuccessListWithPage("获取成功",planDOList,page,size,count);
        String filter = " from base_service_item_plan p where p.patient='" + patient + "' and p.plan_time<='" + DateUtil.getStringDateShort() + " 23:59:59' ";
        String ordereBy = " order by p.plan_time desc limit " + (page - 1) * size + "," + size;
        List<ServiceItemPlanDO> planDOList = jdbcTemplate.query(sql + filter + ordereBy, new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
        long count = jdbcTemplate.queryForObject(countSql + filter, Long.class);
        return PageEnvelop.getSuccessListWithPage("获取成功", planDOList, page, size, count);
    }
    //添加康复计划日志
    public void addPlanLog(String planId,String doctorCode,String doctorName){
        if(StringUtils.isBlank(doctorCode)){
    public void addPlanLog(String planId, String doctorCode, String doctorName) {
        if (StringUtils.isBlank(doctorCode)) {
            return;
        }
        if(StringUtils.isBlank(doctorName)){
        if (StringUtils.isBlank(doctorName)) {
            BaseDoctorDO doctorDO = doctorDao.findByIdAndDel(doctorCode);
            doctorName = doctorDO.getName();
        }
        PatientRehabilitationPlanLogDO planLogDO = new PatientRehabilitationPlanLogDO();
        planLogDO.setId(UUID.randomUUID().toString().replace("-",""));
        planLogDO.setId(UUID.randomUUID().toString().replace("-", ""));
        planLogDO.setPlanId(planId);
        planLogDO.setCreateTime(new Date());
        planLogDO.setCreateUser(doctorCode);
@ -128,61 +128,61 @@ public class RehabilitationManageService {
    }
    //计划负责人分配执行人
    public void assignExecutor(PatientRehabilitationPlanDO planDO,String uid){
    public void assignExecutor(PatientRehabilitationPlanDO planDO, String uid) {
        PatientRehabilitationPlanDO planDO1 = patientRehabilitationPlanDao.findById(planDO.getId()).orElse(null);
        if(planDO1==null){
        if (planDO1 == null) {
            throw new ServiceException("康复计划不存在");
        }
        if(planDO1.getStatus()!=3){
        if (planDO1.getStatus() != 3) {
            throw new ServiceException("已分配,请勿重复分配");
        }
        if(StringUtils.isNotBlank(uid)){
            if(!uid.equals(planDO1.getPlanDoctor())){
        if (StringUtils.isNotBlank(uid)) {
            if (!uid.equals(planDO1.getPlanDoctor())) {
                throw new ServiceException("您不是该康复计划负责人,不允许操作");
            }
        }
        List<RehabilitationDetailDO> detailDOS = rehabilitationDetailDao.findByPlanIdAndStatus(planDO.getId(),0);
        List<RehabilitationDetailDO> detailDOS = rehabilitationDetailDao.findByPlanIdAndStatus(planDO.getId(), 0);
        List<RehabilitationDetailDO> detailDOList = planDO.getDetailDOList();
        Map<String,RehabilitationDetailDO> map = detailDOList.stream().collect(Collectors.toMap
                (RehabilitationDetailDO::getHospitalServiceItemId, log->log,(oldLog, newLog)->oldLog));
        Map<String, RehabilitationDetailDO> map = detailDOList.stream().collect(Collectors.toMap
                (RehabilitationDetailDO::getHospitalServiceItemId, log -> log, (oldLog, newLog) -> oldLog));
        List<ServiceItemPlanDO> planDOList = new ArrayList<>();
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, String> serviceItemMap = itemDOList.stream().collect(Collectors.toMap(RehabilitationServiceItemDO::getCode, RehabilitationServiceItemDO::getName));
        for (RehabilitationDetailDO detailDO : detailDOS){
        for (RehabilitationDetailDO detailDO : detailDOS) {
            String serviceItemId = detailDO.getHospitalServiceItemId();
            if(map.containsKey(serviceItemId)){
            if (map.containsKey(serviceItemId)) {
                RehabilitationDetailDO newDetail = map.get(serviceItemId);
                detailDO.setDoctor(newDetail.getDoctor());
                detailDO.setDoctorName(newDetail.getDoctorName());
                detailDO.setDept(newDetail.getDept());
                detailDO.setDeptName(newDetail.getDeptName());
                //生成执行计划列表
                planDOList = addServicePlan(serviceItemMap,planDO1,detailDO,planDOList);
                planDOList = addServicePlan(serviceItemMap, planDO1, detailDO, planDOList);
            }
        }
        rehabilitationDetailDao.saveAll(detailDOS);
        if(planDOList.size()>0){
        if (planDOList.size() > 0) {
            serviceItemPlanDao.saveAll(planDOList);
        }
        planDO1.setStatus(1);
        patientRehabilitationPlanDao.save(planDO1);
        addPlanLog(planDO.getId(),uid,null);
        addPlanLog(planDO.getId(), uid, null);
        //更新状态
        if(StringUtils.isNotBlank(planDO1.getPatientInfoCode())){
        if (StringUtils.isNotBlank(planDO1.getPatientInfoCode())) {
            RehabilitationPatientInfoDO infoDO = rehabilitationPatientInfoDao.findByCode(planDO1.getPatientInfoCode());
            infoDO.setStatus(7);
            rehabilitationPatientInfoDao.save(infoDO);
        }
    }
    public List<ServiceItemPlanDO> addServicePlan(Map<String, String> serviceItemMap,PatientRehabilitationPlanDO planDO,
                                                  RehabilitationDetailDO detailDO,List<ServiceItemPlanDO> planDOList){
    public List<ServiceItemPlanDO> addServicePlan(Map<String, String> serviceItemMap, PatientRehabilitationPlanDO planDO,
                                                  RehabilitationDetailDO detailDO, List<ServiceItemPlanDO> planDOList) {
        String planId = planDO.getId();
        String pateint = planDO.getPatient();
        String relationType = detailDO.getHospitalServiceItemId();
        Integer plan_start_time_type = detailDO.getTimeType();//计划开始时间类型
        String server_count = detailDO.getServerCount();//服务次数
        if(StringUtils.isBlank(server_count)||"3".equals(relationType)){
        if (StringUtils.isBlank(server_count) || "3".equals(relationType)) {
            return planDOList;
        }
        String planDetailId = detailDO.getId();
@ -192,8 +192,8 @@ public class RehabilitationManageService {
        LocalDateTime localDateTime = LocalDateTime.now();
        int addNum = 0;
        localDateTime = localDateTime.plusDays(addNum);
        List<String>  timeList = CronUtils.getExecutionTimeByNum(frequency_code,Integer.parseInt(server_count),localDateTime);
        for (String time :timeList){
        List<String> timeList = CronUtils.getExecutionTimeByNum(frequency_code, Integer.parseInt(server_count), localDateTime);
        for (String time : timeList) {
            ServiceItemPlanDO itemPlanDO = new ServiceItemPlanDO();
            itemPlanDO.setPlanTime(time);
            itemPlanDO.setPatient(pateint);
@ -204,10 +204,10 @@ public class RehabilitationManageService {
            itemPlanDO.setPlanDetailId(planDetailId);
            itemPlanDO.setDoctor(doctor);
            itemPlanDO.setDoctorName(doctorName);
            if("6".equals(relationType)){
            if ("6".equals(relationType)) {
                Followup followup = followUpService.addRehabilatationFollowup(itemPlanDO);
                if(followup!=null){
                    itemPlanDO.setRelationCode(followup.getId()+"");
                if (followup != null) {
                    itemPlanDO.setRelationCode(followup.getId() + "");
                }
            }
            planDOList.add(itemPlanDO);
@ -590,11 +590,11 @@ public class RehabilitationManageService {
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetail(String executeStartTime, String executeEndTime, String planId, Integer searchTask,
                                         Integer status, String doctorCode, String taskExecutor,String patient,String diseaseId) throws Exception {
                                         Integer status, String doctorCode, String taskExecutor, String patient, String diseaseId) throws Exception {
        String sql = " select d.* from base_service_item_plan d,wlyy_patient_rehabilitation_plan p  where d.plan_id=p.id ";
        if(StringUtils.isNotBlank(patient)){
        if (StringUtils.isNotBlank(patient)) {
            sql += " and  d.patient = '" + patient + "' ";
        }else {
        } else {
            String[] planIdlist = planId.split(",");
            StringBuilder planCondition = new StringBuilder();
            planCondition.append("'" + planIdlist[0] + "'");
@ -603,7 +603,7 @@ public class RehabilitationManageService {
            }
            sql += " and  d.plan_id in (" + planCondition + " ) ";
        }
        if(StringUtils.isNotBlank(diseaseId)){
        if (StringUtils.isNotBlank(diseaseId)) {
            sql += " and  p.disease = '" + diseaseId + "' ";
        }
        if (StringUtils.isNotBlank(executeStartTime)) {
@ -626,13 +626,13 @@ public class RehabilitationManageService {
            sql += "and d.doctor <>'" + doctorCode + "' ";
        }
        if (status != null) {
            sql += " and d.status='" + status+"' ";
            sql += " and d.status='" + status + "' ";
        }
        sql += " ORDER BY d.plan_time ";
        List<Map<String, Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        Map<String, Map<String, Object>> map = new LinkedHashMap<>();
        for (Map<String, Object> one : rehabilitationDetailList) {
            String executeTime = (one.get("plan_time")+"").substring(0,10);
            String executeTime = (one.get("plan_time") + "").substring(0, 10);
            Map<String, Object> m = new HashMap<>();
            if (map.containsKey(executeTime)) {
                m = map.get(executeTime);
@ -645,16 +645,16 @@ public class RehabilitationManageService {
                    specialist.put("all", 0);
                    specialist.put("finish", 0);
                }
                if ("1".equals(one.get("status")+"")) {
                if ("1".equals(one.get("status") + "")) {
                    specialist.put("finish", (specialist.get("finish")) + 1);
                }
                specialist.put("all", (specialist.get("all")) + 1);
                m.put("doctor", specialist);
            }else{
            } else {
                Map<String, Integer> specialist = new HashMap<>();
                specialist.put("all", 0);
                specialist.put("finish", 0);
                if ("1".equals(one.get("status")+"")) {
                if ("1".equals(one.get("status") + "")) {
                    specialist.put("finish", specialist.get("finish") + 1);
                }
                specialist.put("all", specialist.get("all") + 1);
@ -698,12 +698,12 @@ public class RehabilitationManageService {
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailList(String planId, Integer searchTask, Integer status, String doctorCode,
                                             String executeStartTime, String executeEndTime, String taskExecutor,String patient,String diseaseId) {
                                             String executeStartTime, String executeEndTime, String taskExecutor, String patient, String diseaseId) {
        String sql = " select d.* from base_service_item_plan d,wlyy_patient_rehabilitation_plan p  where d.plan_id=p.id ";
        if(StringUtils.isNotBlank(patient)){
        if (StringUtils.isNotBlank(patient)) {
            sql += " and  d.patient = '" + patient + "' ";
        }else {
        } else {
            String[] planIdlist = planId.split(",");
            StringBuilder planCondition = new StringBuilder();
            planCondition.append("'" + planIdlist[0] + "'");
@ -712,7 +712,7 @@ public class RehabilitationManageService {
            }
            sql += " and  d.plan_id in (" + planCondition + " ) ";
        }
        if(StringUtils.isNotBlank(diseaseId)){
        if (StringUtils.isNotBlank(diseaseId)) {
            sql += " and  p.disease = '" + diseaseId + "' ";
        }
@ -735,11 +735,11 @@ public class RehabilitationManageService {
            sql += "and d.plan_time>='" + executeStartTime + "' and d.plan_time<='" + executeEndTime + " 23:59:59' ";
        }
        if (status != null) {
            sql += "and d.status='" + status+"' ";
            sql += "and d.status='" + status + "' ";
        }
        sql += "  order by d.plan_time desc ";
        List<ServiceItemPlanDO> rehabilitationDetailList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
        List<ServiceItemPlanDO> rehabilitationDetailList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
//        if (rehabilitationDetailList.size() > 0 && null != searchTask) {
//            String patient = rehabilitationDetailList.get(0).getPatient();
//            if (7 == searchTask) { //处方续方 flag 用于判断 1.7.0.5 新增
@ -1337,49 +1337,49 @@ public class RehabilitationManageService {
    //获取其他执行计划
    public List<ServiceItemPlanDO> selectPlanDetailByPlan(String planId, String itemId, String searchTask) {
        String sql = "SELECT * from base_service_item_plan WHERE plan_id='"+planId+"' and relation_type='"+searchTask+"'" +
                " and status='0' and id<>'"+itemId+"' order by plan_time asc";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
        String sql = "SELECT * from base_service_item_plan WHERE plan_id='" + planId + "' and relation_type='" + searchTask + "'" +
                " and status='0' and id<>'" + itemId + "' order by plan_time asc";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ServiceItemPlanDO.class));
    }
    //康复计划服务项列表
    public List<RehabilitationDetailDO> rehabilitationDetailInfo(String planId,String status,String searchTask){
        String sql = "select * from wlyy_rehabilitation_plan_detail where plan_id='"+planId+"' ";
        if(StringUtils.isNotBlank(status)){
            sql += " and status="+status;
    public List<RehabilitationDetailDO> rehabilitationDetailInfo(String planId, String status, String searchTask) {
        String sql = "select * from wlyy_rehabilitation_plan_detail where plan_id='" + planId + "' ";
        if (StringUtils.isNotBlank(status)) {
            sql += " and status=" + status;
        }
        if(StringUtils.isNotBlank(searchTask)){
            sql += " and hospital_service_item_id='"+searchTask+"' ";
        if (StringUtils.isNotBlank(searchTask)) {
            sql += " and hospital_service_item_id='" + searchTask + "' ";
        }
        sql += " order by hospital_service_item_id";
        List<RehabilitationDetailDO> detailDOList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(RehabilitationDetailDO.class));
        List<RehabilitationDetailDO> detailDOList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(RehabilitationDetailDO.class));
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, String> serviceItemMap = itemDOList.stream().collect(Collectors.toMap(RehabilitationServiceItemDO::getCode, RehabilitationServiceItemDO::getName));
        List<ServiceItemPlanDO> planDOList = serviceItemPlanDao.findByPlanId(planId);
        PatientRehabilitationPlanDO patientRehabilitationPlanDO = patientRehabilitationPlanDao.findById(planId).orElse(null);
        String patient = patientRehabilitationPlanDO.getPatient();
        Map<String,List<ServiceItemPlanDO>> planListMap = planDOList.stream().collect(Collectors.groupingBy(ServiceItemPlanDO::getRelationType));
        for (RehabilitationDetailDO detailDO:detailDOList){
        Map<String, List<ServiceItemPlanDO>> planListMap = planDOList.stream().collect(Collectors.groupingBy(ServiceItemPlanDO::getRelationType));
        for (RehabilitationDetailDO detailDO : detailDOList) {
            String key = detailDO.getHospitalServiceItemId();
            String doctor = detailDO.getDoctor();
            List<ServiceItemPlanDO> planDOS = planListMap.get(key);
            if(planDOS==null){
            if (planDOS == null) {
                planDOS = new ArrayList<>();
            }
            String completeTime = "";
            String planTime = "";
            int total = planDOS.size();
            int complete = 0;
            for (ServiceItemPlanDO planDO:planDOS){
                if("1".equals(planDO.getStatus())){
            for (ServiceItemPlanDO planDO : planDOS) {
                if ("1".equals(planDO.getStatus())) {
                    complete++;
                    if(completeTime.compareTo(planDO.getCompleteTime())<0){
                    if (completeTime.compareTo(planDO.getCompleteTime()) < 0) {
                        completeTime = planDO.getCompleteTime();
                    }
                }else {
                    if("".equals(planTime)){
                } else {
                    if ("".equals(planTime)) {
                        planTime = planDO.getPlanTime();
                    }else if(planTime.compareTo(planDO.getPlanTime())>0){
                    } else if (planTime.compareTo(planDO.getPlanTime()) > 0) {
                        planTime = planDO.getPlanTime();
                    }
                }
@ -1389,30 +1389,30 @@ public class RehabilitationManageService {
            detailDO.setCompleteTime(completeTime);
            detailDO.setPlanTime(planTime);
            detailDO.setName(serviceItemMap.get(key));
            if("2".equals(key)){
            if ("2".equals(key)) {
                //康复咨询
                String sqlTotal = "SELECT COUNT(*) from wlyy_consult_team WHERE patient='"+patient+"' and doctor='"+doctor+"' and type = '28' ";
                Integer signCount = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                String sqlTotal = "SELECT COUNT(*) from wlyy_consult_team WHERE patient='" + patient + "' and doctor='" + doctor + "' and type = '28' ";
                Integer signCount = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
                detailDO.setFinishNum(signCount);
                if(signCount>0){
                    String sqlTemp = "select DATE_FORMAT(czrq, '%Y-%m-%d %H:%i:%s') czrq from wlyy_consult_team p where p.patient ='" + patient + "' and doctor='"+doctor+"' and " +
                if (signCount > 0) {
                    String sqlTemp = "select DATE_FORMAT(czrq, '%Y-%m-%d %H:%i:%s') czrq from wlyy_consult_team p where p.patient ='" + patient + "' and doctor='" + doctor + "' and " +
                            "type = '28' order by p.czrq desc limit 0,1 ";
                    List<Map<String,Object>> indexList = jdbcTemplate.queryForList(sqlTemp);
                    if(indexList.size()>0){
                        detailDO.setCompleteTime(indexList.get(0).get("czrq")+"");
                    List<Map<String, Object>> indexList = jdbcTemplate.queryForList(sqlTemp);
                    if (indexList.size() > 0) {
                        detailDO.setCompleteTime(indexList.get(0).get("czrq") + "");
                    }
                }
            }
            if("3".equals(key)){
            if ("3".equals(key)) {
                //健康监测
                String sqlTotal = "select count(*) as total from wlyy_patient_health_index p " +
                        "where p.user ='" + patient + "' and p.type IN(1,2) ";//and p.record_date >= '"+createTime+"'
                Integer signCount = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                Integer signCount = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
                detailDO.setSignCount(signCount);
                if(signCount>0){
                if (signCount > 0) {
                    String sqlTemp = "select p.* from wlyy_patient_health_index p where p.user ='" + patient + "' and p.type IN(1,2) order by p.record_date desc limit 0,1 ";
                    List<DevicePatientHealthIndex> indexList = jdbcTemplate.query(sqlTemp,new BeanPropertyRowMapper<>(DevicePatientHealthIndex.class));
                    if(indexList.size()>0){
                    List<DevicePatientHealthIndex> indexList = jdbcTemplate.query(sqlTemp, new BeanPropertyRowMapper<>(DevicePatientHealthIndex.class));
                    if (indexList.size() > 0) {
                        DevicePatientHealthIndex index = indexList.get(0);
                        detailDO.setSignType(index.getType());
                        detailDO.setValue1(index.getValue1());
@ -1426,27 +1426,27 @@ public class RehabilitationManageService {
    }
    //电话关怀,状态更新成待补录
    public void updItemPlanStatus(String id,String doctor){
    public void updItemPlanStatus(String id, String doctor) {
        ServiceItemPlanDO planDO = serviceItemPlanDao.findById(id).orElse(null);
        if(!planDO.getDoctor().equals(doctor)){
        if (!planDO.getDoctor().equals(doctor)) {
            throw new ServiceException("不是您的任务,无法操作");
        }
        if("1".equals(planDO.getStatus())){
        if ("1".equals(planDO.getStatus())) {
            throw new ServiceException("任务已完成,请勿重复操作");
        }
        if("0".equals(planDO.getStatus())){
        if ("0".equals(planDO.getStatus())) {
            planDO.setStatus("2");
            serviceItemPlanDao.save(planDO);
        }
    }
    //确认完成服务,填写服务笔记
    public ServiceItemPlanDO completePlan(String id,String content,String appendixs,String doctor){
    public ServiceItemPlanDO completePlan(String id, String content, String appendixs, String doctor) {
        ServiceItemPlanDO planDO = serviceItemPlanDao.findById(id).orElse(null);
        if(!planDO.getDoctor().equals(doctor)){
        if (!planDO.getDoctor().equals(doctor)) {
            throw new ServiceException("不是您的任务,无法完成");
        }
        if("1".equals(planDO.getStatus())){
        if ("1".equals(planDO.getStatus())) {
            throw new ServiceException("请勿重复填写");
        }
        planDO.setAppendixs(appendixs);
@ -1455,18 +1455,28 @@ public class RehabilitationManageService {
        return planDO;
    }
    public ServiceItemPlanDO completePlan(ServiceItemPlanDO planDO){
    public ServiceItemPlanDO completePlan(ServiceItemPlanDO planDO) {
        planDO.setStatus("1");
        planDO.setCompleteTime(DateUtil.getStringDate());
        serviceItemPlanDao.save(planDO);
        updPlanStatus(planDO.getPlanId(),planDO.getPlanDetailId());
        updPlanStatus(planDO.getPlanId(), planDO.getPlanDetailId());
        return planDO;
    }
    /**
     * 进行中
     */
    public ServiceItemPlanDO planCarryOuting(ServiceItemPlanDO planDO) {
        planDO.setStatus("3");
        serviceItemPlanDao.save(planDO);
        return planDO;
    }
    //完成随访
    public ServiceItemPlanDO completePlanFollowup(Long followupId){
        ServiceItemPlanDO serviceItemPlanDO = serviceItemPlanDao.findByRelationCodeAndRelationType(followupId+"","6");
        if(serviceItemPlanDO!=null&&"0".equals(serviceItemPlanDO.getStatus())){
    public ServiceItemPlanDO completePlanFollowup(Long followupId) {
        ServiceItemPlanDO serviceItemPlanDO = serviceItemPlanDao.findByRelationCodeAndRelationType(followupId + "", "6");
        if (serviceItemPlanDO != null && "0".equals(serviceItemPlanDO.getStatus())) {
            serviceItemPlanDO = completePlan(serviceItemPlanDO);
        }
        return serviceItemPlanDO;
@ -1474,41 +1484,41 @@ public class RehabilitationManageService {
    //康复计划状态更新
    public void updPlanStatus(String planId,String planDetailId){
        List<ServiceItemPlanDO> itemPlanDOS =  serviceItemPlanDao.findByPlanDetailId(planDetailId,"0");
        if(itemPlanDOS.size()>0){
    public void updPlanStatus(String planId, String planDetailId) {
        List<ServiceItemPlanDO> itemPlanDOS = serviceItemPlanDao.findByPlanDetailId(planDetailId, "0");
        if (itemPlanDOS.size() > 0) {
            //服务项计划都完成了
            jdbcTemplate.update("update wlyy_rehabilitation_plan_detail set status=1 where id='"+planDetailId+"'");
            jdbcTemplate.update("update wlyy_rehabilitation_plan_detail set status=1 where id='" + planDetailId + "'");
            String sql = "SELECT COUNT(*) total,COUNT(if(`status`=1,1,null)) num from wlyy_rehabilitation_plan_detail  " +
                    "WHERE plan_id='"+planId+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            String total = list.get(0).get("total")+"";
            String num = list.get(0).get("num")+"";
            if(total.equals(num)){
                jdbcTemplate.update("update wlyy_patient_rehabilitation_plan set status=2 where id='"+planId+"'");
                    "WHERE plan_id='" + planId + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            String total = list.get(0).get("total") + "";
            String num = list.get(0).get("num") + "";
            if (total.equals(num)) {
                jdbcTemplate.update("update wlyy_patient_rehabilitation_plan set status=2 where id='" + planId + "'");
            }
        }
    }
    //执行计划详情
    public ServiceItemPlanDO findServiceItemPlanDetail(String id){
    public ServiceItemPlanDO findServiceItemPlanDetail(String id) {
        ServiceItemPlanDO planDO = serviceItemPlanDao.findById(id).orElse(null);
        if(planDO!=null){
            String sql = "SELECT content from wlyy_guidance_message_log WHERE plan_detail_id ='"+id+"' LIMIT 1";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            if(list.size()>0){
                planDO.setGuidanceMessage(list.get(0).get("content")+"");
        if (planDO != null) {
            String sql = "SELECT content from wlyy_guidance_message_log WHERE plan_detail_id ='" + id + "' LIMIT 1";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (list.size() > 0) {
                planDO.setGuidanceMessage(list.get(0).get("content") + "");
            }
        }
        String relationCode = planDO.getRelationCode();
        if("6".equals(planDO.getRelationType())&&StringUtils.isNotBlank(relationCode)){
        if ("6".equals(planDO.getRelationType()) && StringUtils.isNotBlank(relationCode)) {
            Followup followup = followupDao.findById(Long.parseLong(relationCode)).orElse(null);
            if(followup!=null){
            if (followup != null) {
                planDO.setFollowupStatus(followup.getStatus());
            }
        }
        PatientRehabilitationPlanDO rehabilitationPlanDO = patientRehabilitationPlanDao.findById(planDO.getPlanId()).orElse(null);
        if(rehabilitationPlanDO!=null){
        if (rehabilitationPlanDO != null) {
            planDO.setPlanDoctor(rehabilitationPlanDO.getPlanDoctor());
            planDO.setPlanDoctorName(rehabilitationPlanDO.getPlanDoctorName());
        }
@ -1516,21 +1526,21 @@ public class RehabilitationManageService {
    }
    //查询指导留言详情
    public GuidanceMessageLogDO findGuidanceMessageDetail(String itemPlanId){
        String sql = "SELECT * from wlyy_guidance_message_log WHERE plan_detail_id ='"+itemPlanId+"' LIMIT 1";
        List<GuidanceMessageLogDO> logDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(GuidanceMessageLogDO.class));
        if(logDOS.size()>0){
    public GuidanceMessageLogDO findGuidanceMessageDetail(String itemPlanId) {
        String sql = "SELECT * from wlyy_guidance_message_log WHERE plan_detail_id ='" + itemPlanId + "' LIMIT 1";
        List<GuidanceMessageLogDO> logDOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GuidanceMessageLogDO.class));
        if (logDOS.size() > 0) {
            return logDOS.get(0);
        }
        return null;
    }
    //查询最新一条指导留言
    public GuidanceMessageLogDO findLastGuidanceMessage(String planId){
        String sql = "SELECT l.* from wlyy_guidance_message_log l,base_service_item_plan p WHERE p.plan_id ='"+planId+"'" +
    public GuidanceMessageLogDO findLastGuidanceMessage(String planId) {
        String sql = "SELECT l.* from wlyy_guidance_message_log l,base_service_item_plan p WHERE p.plan_id ='" + planId + "'" +
                " and l.plan_detail_id=p.id order by l.create_time desc LIMIT 1";
        List<GuidanceMessageLogDO> logDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(GuidanceMessageLogDO.class));
        if(logDOS.size()>0){
        List<GuidanceMessageLogDO> logDOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(GuidanceMessageLogDO.class));
        if (logDOS.size() > 0) {
            return logDOS.get(0);
        }
        return null;
@ -1544,14 +1554,14 @@ public class RehabilitationManageService {
     * @param doctorType 1、专科医生,2、计划负责人
     */
    @Transactional
    public Envelop saveGuidanceMessage(String messageId, String doctor, Integer doctorType, String content,String imgs,
    public Envelop saveGuidanceMessage(String messageId, String doctor, Integer doctorType, String content, String imgs,
                                       String planDetailId, Integer contentType) {
        GuidanceMessageLogDO guidanceMessageLogDO = null;
        List<GuidanceMessageLogDO> logDOS =  guidanceMessageLogDao.findByPlanDetailId(planDetailId);
        if(logDOS.size()>0){
        List<GuidanceMessageLogDO> logDOS = guidanceMessageLogDao.findByPlanDetailId(planDetailId);
        if (logDOS.size() > 0) {
            guidanceMessageLogDO = logDOS.get(0);
            guidanceMessageLogDO.setUpdateTime(new Date());
        }else {
        } else {
            guidanceMessageLogDO = new GuidanceMessageLogDO();
            guidanceMessageLogDO.setCreateTime(new Date());
            guidanceMessageLogDO.setUpdateTime(new Date());
@ -1568,7 +1578,7 @@ public class RehabilitationManageService {
//        guidanceMessageLogDO.setAdminTeamName(adminTeamName);
        guidanceMessageLogDO.setDoctorName(doctorDO.getName());
        guidanceMessageLogDO = guidanceMessageLogDao.save(guidanceMessageLogDO);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,guidanceMessageLogDO);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, guidanceMessageLogDO);
    }
    /**
@ -1706,7 +1716,7 @@ public class RehabilitationManageService {
    public ObjEnvelop appCalendarPlanDetailList(String planId, Integer searchTask, Integer status, String executeStartTime, String executeEndTime) {
        Map<String, Object> resultMap = new HashMap<>();
        ObjEnvelop objEnvelop = calendarPlanDetailList(planId, searchTask, status, null, executeStartTime, executeEndTime, "0",null,null);
        ObjEnvelop objEnvelop = calendarPlanDetailList(planId, searchTask, status, null, executeStartTime, executeEndTime, "0", null, null);
        Integer finishCount = rehabilitationDetailDao.findByStatusAndPlanId(1, planId);
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);
        resultMap.put("planDetailList", objEnvelop.getObj());
@ -2768,7 +2778,7 @@ public class RehabilitationManageService {
        param.put("taskExecutor", taskExecutor);
        ObjEnvelop objEnvelop = calendarPlanDetailList(planIds.toString(), searchTask, status, doctorCode, executeStartTime, executeEndTime, taskExecutor,null,null);
        ObjEnvelop objEnvelop = calendarPlanDetailList(planIds.toString(), searchTask, status, doctorCode, executeStartTime, executeEndTime, taskExecutor, null, null);
        org.json.JSONObject result = new org.json.JSONObject(objEnvelop);
        if (result.getInt("status") == 200) {
@ -3024,4 +3034,14 @@ public class RehabilitationManageService {
        }
        return medicalRecordsDOS;
    }
    public void cancelPlan(String orderId) {
        String sql = "select id from base_service_item_plan where relation_code='" + orderId + "'";
        String itemId = jdbcTemplate.queryForObject(sql, String.class);
        String updateSql = "update base_service_item_plan q set q.status='0' where id='" + itemId + "'";
        jdbcTemplate.execute(updateSql);
        System.out.println("执行sql==>" + updateSql);
    }
}