Просмотр исходного кода

Merge branch 'dev' of suhaiwen/wlyy2.0 into dev

wangzhinan 4 лет назад
Родитель
Сommit
139498383f

+ 1887 - 1674
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -251,6 +251,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取居民就诊记录接口
     * 获取居民就诊记录接口
     *
     * @param patient
     * @param patient
     * @param startTime
     * @param startTime
     * @param endTime
     * @param endTime
@ -258,35 +259,36 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public  List<WlyyOutpatientVO> findOutpatientList(String patient, String startTime, String endTime, boolean demoFlag)throws Exception{
        logger.info("findOutpatientList patient:"+patient);
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
    public List<WlyyOutpatientVO> findOutpatientList(String patient, String startTime, String endTime, boolean demoFlag) throws Exception {
        logger.info("findOutpatientList patient:" + patient);
        String patNo = patientMappingService.findHisPatNoByPatient(patient);
        if (StringUtils.isBlank(patNo)) {
            return null;
            return null;
        }
        }
        logger.info("findOutpatientList patNo "+patNo);
        return entranceService.BS30025(patNo,null,startTime,endTime,demoFlag);
        logger.info("findOutpatientList patNo " + patNo);
        return entranceService.BS30025(patNo, null, startTime, endTime, demoFlag);
    }
    }
    /**
    /**
     * 查询单条门诊记录
     * 查询单条门诊记录
     *
     * @param patient
     * @param patient
     * @param conNo
     * @param conNo
     * @return
     * @return
     */
     */
    public WlyyOutpatientVO findOutpatientInfo(String patient,String conNo)throws Exception{
        logger.info("findOutpatientList patient:"+patient);
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
    public WlyyOutpatientVO findOutpatientInfo(String patient, String conNo) throws Exception {
        logger.info("findOutpatientList patient:" + patient);
        String patNo = patientMappingService.findHisPatNoByPatient(patient);
        if (StringUtils.isBlank(patNo)) {
            return null;
            return null;
        }
        }
        logger.info("findOutpatientList patNo:"+patNo);
        List<WlyyOutpatientVO> list = entranceService.BS30025(patNo,conNo,null,null,demoFlag);
        logger.info("findOutpatientList patNo:" + patNo);
        List<WlyyOutpatientVO> list = entranceService.BS30025(patNo, conNo, null, null, demoFlag);
        if(list!=null&&list.size()>0){
        if (list != null && list.size() > 0) {
            WlyyOutpatientVO outpatientVO = list.get(0);
            WlyyOutpatientVO outpatientVO = list.get(0);
            BasePatientDO patientDO = basePatientDao.findById(patient);
            BasePatientDO patientDO = basePatientDao.findById(patient);
            outpatientVO.setSex(patientDO.getSex()+"");
            outpatientVO.setSex(patientDO.getSex() + "");
            outpatientVO.setBirthday(patientDO.getBirthday());
            outpatientVO.setBirthday(patientDO.getBirthday());
            return outpatientVO;
            return outpatientVO;
        }
        }
@ -296,18 +298,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     *
     *
     */
     */
    public List<WlyyPrescriptionVO> findOriginPrescriptionList(String registerSn,String patient,String realOrder,String admNo,boolean demoFlag)throws Exception{
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
    public List<WlyyPrescriptionVO> findOriginPrescriptionList(String registerSn, String patient, String realOrder, String admNo, boolean demoFlag) throws Exception {
        String patNo = patientMappingService.findHisPatNoByPatient(patient);
        if (StringUtils.isBlank(patNo)) {
            return null;
            return null;
        }
        }
        //BS16017(String REGISTER_SN,String realOrder,String PAT_NO,String ADM_NO,boolean demoFlag) throws Exception {
        //BS16017(String REGISTER_SN,String realOrder,String PAT_NO,String ADM_NO,boolean demoFlag) throws Exception {
        logger.info("findOriginPrescriptionList: registerSn:"+registerSn+" patient"+patient+" patNo:"+patNo+" realOrder:"+realOrder+" admNo:"+admNo);
        return entranceService.BS16017(registerSn,realOrder,patNo,admNo,demoFlag);
        logger.info("findOriginPrescriptionList: registerSn:" + registerSn + " patient" + patient + " patNo:" + patNo + " realOrder:" + realOrder + " admNo:" + admNo);
        return entranceService.BS16017(registerSn, realOrder, patNo, admNo, demoFlag);
    }
    }
    /**
    /**
     * 获取单条处方记录
     * 获取单条处方记录
     *
     * @param registerSn
     * @param registerSn
     * @param patient
     * @param patient
     * @param admNo
     * @param admNo
@ -316,13 +319,13 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public WlyyPrescriptionVO findOriginPrescription(String registerSn, String patient, String admNo, String realOrder, boolean demoFlag)throws Exception{
        String patNo =patientMappingService.findHisPatNoByPatient(patient);
        if(StringUtils.isBlank(patNo)){
    public WlyyPrescriptionVO findOriginPrescription(String registerSn, String patient, String admNo, String realOrder, boolean demoFlag) throws Exception {
        String patNo = patientMappingService.findHisPatNoByPatient(patient);
        if (StringUtils.isBlank(patNo)) {
            return null;
            return null;
        }
        }
        List<WlyyPrescriptionVO> rs = entranceService.BS16017(registerSn,realOrder,patNo,admNo,demoFlag);
        if(rs!=null&&rs.size()>0){
        List<WlyyPrescriptionVO> rs = entranceService.BS16017(registerSn, realOrder, patNo, admNo, demoFlag);
        if (rs != null && rs.size() > 0) {
            return rs.get(0);
            return rs.get(0);
        }
        }
        return null;
        return null;
@ -330,32 +333,33 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取复诊记录列表
     * 获取复诊记录列表
     *
     * @param patient
     * @param patient
     * @param status
     * @param status
     * @param page
     * @param page
     * @param size
     * @param size
     * @return
     * @return
     */
     */
    public MixEnvelop findReOutpatientList(String patient,Integer status,String startTime,String endTime,Integer page,Integer size){
    public MixEnvelop findReOutpatientList(String patient, Integer status, String startTime, String endTime, Integer page, Integer size) {
        String totalSql = "SELECT " +
        String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " FROM " +
                " wlyy_outpatient o " +
                " wlyy_outpatient o " +
                " WHERE " +
                " WHERE " +
                " o.patient =:patient AND o.outpatient_type != '2' ";
                " o.patient =:patient AND o.outpatient_type != '2' ";
        Map<String,Object> totalParams = new HashedMap();
        totalParams.put("patient",patient);
        if(status!=null){
            totalSql +=  " AND o.status =:status ";
            totalParams.put("status",status);
        Map<String, Object> totalParams = new HashedMap();
        totalParams.put("patient", patient);
        if (status != null) {
            totalSql += " AND o.status =:status ";
            totalParams.put("status", status);
        }
        }
        if(StringUtils.isNotBlank(startTime)){
        if (StringUtils.isNotBlank(startTime)) {
            totalSql += " AND o.create_time >=:createTime ";
            totalSql += " AND o.create_time >=:createTime ";
            totalParams.put("createTime",DateUtil.strToDateLong(startTime+" 00:00:00"));
            totalParams.put("createTime", DateUtil.strToDateLong(startTime + " 00:00:00"));
        }
        }
        if(StringUtils.isNotBlank(endTime)){
        if (StringUtils.isNotBlank(endTime)) {
            totalSql += " AND o.create_time <=:endTime ";
            totalSql += " AND o.create_time <=:endTime ";
            totalParams.put("endTime",DateUtil.strToDateLong(endTime+" 23:59:59"));
            totalParams.put("endTime", DateUtil.strToDateLong(endTime + " 23:59:59"));
        }
        }
       /* totalParams.add(patient);
       /* totalParams.add(patient);
@ -371,18 +375,18 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            totalSql += " AND create_time <= ? ";
            totalSql += " AND create_time <= ? ";
            totalParams.add(DateUtil.strToDateLong(endTime+" 23:59:59"));
            totalParams.add(DateUtil.strToDateLong(endTime+" 23:59:59"));
        }*/
        }*/
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql,totalParams);
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql, totalParams);
        Long count = 0L;
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString()) ;
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        }
        String condition = "";
        String condition = "";
        if("xm_ykyy_wx".equals(wechatId)){
            condition= "to_char(o.register_date ,'yyyy-MM-dd hh24:mi:ss' ) AS \"registerDate\"," ;
        }else{
            condition=  "date_format(o.register_date ,'%Y-%m-%d %H:%i:%S' ) AS registerDate," ;
        if ("xm_ykyy_wx".equals(wechatId)) {
            condition = "to_char(o.register_date ,'yyyy-MM-dd hh24:mi:ss' ) AS \"registerDate\",";
        } else {
            condition = "date_format(o.register_date ,'%Y-%m-%d %H:%i:%S' ) AS registerDate,";
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                " o.id AS \"id\", " +
                " o.id AS \"id\", " +
                " o.adm_no AS \"admNo\", " +
                " o.adm_no AS \"admNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
@ -409,105 +413,106 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " o.con_date AS \"conDate\", " +
                " o.con_date AS \"conDate\", " +
                " o.description AS \"description\", " +
                " o.description AS \"description\", " +
                " o.disease_img AS \"diseaseImg\", ";
                " o.disease_img AS \"diseaseImg\", ";
        if("xm_ykyy_wx".equals(wechatId)){
            sql= sql +"to_char(o.create_time ,'yyyy-MM-dd hh24:mi:ss' ) AS \"createTime\"," ;
        }else{
            sql= sql +  "date_format(o.create_time ,'%Y-%m-%d %H:%i:%S' ) AS createTime," ;
        }
        sql= sql+    " o.status AS \"status\"," +
                condition+
              /*  " o.register_date AS \"registerDate\"," +*/
        if ("xm_ykyy_wx".equals(wechatId)) {
            sql = sql + "to_char(o.create_time ,'yyyy-MM-dd hh24:mi:ss' ) AS \"createTime\",";
        } else {
            sql = sql + "date_format(o.create_time ,'%Y-%m-%d %H:%i:%S' ) AS createTime,";
        }
        sql = sql + " o.status AS \"status\"," +
                condition +
                /*  " o.register_date AS \"registerDate\"," +*/
                " o.evaluate_status AS \"evaluateStatus\"," +
                " o.evaluate_status AS \"evaluateStatus\"," +
                " o.pay_status as \"payStatus\" "+
                " o.pay_status as \"payStatus\" " +
                " FROM " +
                " FROM " +
                " wlyy_outpatient o " +
                " wlyy_outpatient o " +
                " WHERE " +
                " WHERE " +
                " o.patient =:patient ";
                " o.patient =:patient ";
        Map<String,Object> params = new HashedMap();
        params.put("patient",patient);
        if(status!=null){
            sql +=  " AND o.status =:status ";
            params.put("status",status);
        Map<String, Object> params = new HashedMap();
        params.put("patient", patient);
        if (status != null) {
            sql += " AND o.status =:status ";
            params.put("status", status);
        }
        }
        if(StringUtils.isNotBlank(startTime)){
        if (StringUtils.isNotBlank(startTime)) {
            sql += " AND o.create_time >=:createTime ";
            sql += " AND o.create_time >=:createTime ";
            params.put("createTime",DateUtil.strToDateLong(startTime+" 00:00:00"));
            params.put("createTime", DateUtil.strToDateLong(startTime + " 00:00:00"));
        }
        }
        if(StringUtils.isNotBlank(endTime)){
        if (StringUtils.isNotBlank(endTime)) {
            sql += " AND o.create_time <=:endTime ";
            sql += " AND o.create_time <=:endTime ";
            params.put("endTime",DateUtil.strToDateLong(endTime+" 23:59:59"));
            params.put("endTime", DateUtil.strToDateLong(endTime + " 23:59:59"));
        }
        }
        sql += " AND o.outpatient_type != '2' ORDER BY o.create_time DESC ";
        sql += " AND o.outpatient_type != '2' ORDER BY o.create_time DESC ";
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,size);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, size);
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }
    }
    /**
    /**
     * 获取单条复诊记录信息
     * 获取单条复诊记录信息
     *
     * @param outpatientId
     * @param outpatientId
     * @return
     * @return
     */
     */
    public com.alibaba.fastjson.JSONObject findReOutpatientInfo(String outpatientId,String prescriptionId,String wxId) throws Exception {
    public com.alibaba.fastjson.JSONObject findReOutpatientInfo(String outpatientId, String prescriptionId, String wxId) throws Exception {
        com.alibaba.fastjson.JSONObject rs = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONObject rs = new com.alibaba.fastjson.JSONObject();
        //复诊信息
        //复诊信息
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        WlyyOutpatientDO outpatientDO = outpatientDao.findOne(outpatientId);
        rs.put("outpatient",convertToModel(outpatientDO,WlyyOutpatientVO.class));
        rs.put("doctorCancelType",outpatientDO.getDoctorCancelType());
        rs.put("doctorCancelValue",outpatientDO.getDoctorCancelValue());
        rs.put("doctorCancelRemark",outpatientDO.getDoctorCancelRemark());
        rs.put("payStatus",outpatientDO.getPayStatus());
        rs.put("patientCancelType",outpatientDO.getPatientCancelType());
        rs.put("patientCancelValue",outpatientDO.getPatientCancelValue());
        rs.put("patientCancelRemark",outpatientDO.getPatientCancelRemark());
        rs.put("operator",userAgent.getUID());
        rs.put("outpatient", convertToModel(outpatientDO, WlyyOutpatientVO.class));
        rs.put("doctorCancelType", outpatientDO.getDoctorCancelType());
        rs.put("doctorCancelValue", outpatientDO.getDoctorCancelValue());
        rs.put("doctorCancelRemark", outpatientDO.getDoctorCancelRemark());
        rs.put("payStatus", outpatientDO.getPayStatus());
        rs.put("patientCancelType", outpatientDO.getPatientCancelType());
        rs.put("patientCancelValue", outpatientDO.getPatientCancelValue());
        rs.put("patientCancelRemark", outpatientDO.getPatientCancelRemark());
        rs.put("operator", userAgent.getUID());
        //居民详情
        //居民详情
        BasePatientDO basePatientDO = basePatientDao.findById(outpatientDO.getPatient());
        BasePatientDO basePatientDO = basePatientDao.findById(outpatientDO.getPatient());
        rs.put("patientName",basePatientDO.getName());
        rs.put("photo",basePatientDO.getPhoto());
        rs.put("patientId",basePatientDO.getId());
        rs.put("idCard",basePatientDO.getIdcard());
        rs.put("patientName", basePatientDO.getName());
        rs.put("photo", basePatientDO.getPhoto());
        rs.put("patientId", basePatientDO.getId());
        rs.put("idCard", basePatientDO.getIdcard());
        rs.put("sex", basePatientDO.getSex());
        rs.put("sex", basePatientDO.getSex());
        PatientMedicareCardDO cardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel(PatientMedicareCardDO.Type.MedicareCard.getType(),outpatientDO.getPatient(),"1");
        rs.put("ssc",cardDO);
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("address",basePatientDO.getAddress());
        rs.put("mobile",basePatientDO.getMobile());
        rs.put("birthday",DateUtil.dateToStr(basePatientDO.getBirthday(),"yyyy-MM-dd"));
        PatientMedicareCardDO cardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel(PatientMedicareCardDO.Type.MedicareCard.getType(), outpatientDO.getPatient(), "1");
        rs.put("ssc", cardDO);
        rs.put("age", IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("address", basePatientDO.getAddress());
        rs.put("mobile", basePatientDO.getMobile());
        rs.put("birthday", DateUtil.dateToStr(basePatientDO.getBirthday(), "yyyy-MM-dd"));
        Long time = new Date().getTime()-outpatientDO.getCreateTime().getTime();
        rs.put("time",time);
        Long time = new Date().getTime() - outpatientDO.getCreateTime().getTime();
        rs.put("time", time);
        //获取处方信息
        //获取处方信息
        List<WlyyPrescriptionDO> prescriptionDOs = null;
        List<WlyyPrescriptionDO> prescriptionDOs = null;
        if(StringUtils.isNotBlank(prescriptionId)){
        if (StringUtils.isNotBlank(prescriptionId)) {
            prescriptionDOs = prescriptionDao.findById(prescriptionId);
            prescriptionDOs = prescriptionDao.findById(prescriptionId);
        }else{
        } else {
            prescriptionDOs = prescriptionDao.findByOutpatientId(outpatientId);
            prescriptionDOs = prescriptionDao.findByOutpatientId(outpatientId);
        }
        }
        List<WlyyPrescriptionVO> prescriptionVOs = new ArrayList<>();
        List<WlyyPrescriptionVO> prescriptionVOs = new ArrayList<>();
        if(prescriptionDOs!=null&&prescriptionDOs.size()>0){
            convertToModels(prescriptionDOs,prescriptionVOs,WlyyPrescriptionVO.class);
            for(WlyyPrescriptionVO vo:prescriptionVOs){
        if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
            convertToModels(prescriptionDOs, prescriptionVOs, WlyyPrescriptionVO.class);
            for (WlyyPrescriptionVO vo : prescriptionVOs) {
                //疾病信息
                //疾病信息
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                //药品信息
                //药品信息
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(),1),infoVOs,WlyyPrescriptionInfoVO.class));
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(), 1), infoVOs, WlyyPrescriptionInfoVO.class));
                //检查检验信息
                //检查检验信息
                List<WlyyInspectionVO> inspectionVOs = new ArrayList<>();
                List<WlyyInspectionVO> inspectionVOs = new ArrayList<>();
                vo.setInspectionVOs(convertToModels(wlyyInspectionDao.findByPrescriptionId(vo.getId(),1),inspectionVOs,WlyyInspectionVO.class));
                vo.setInspectionVOs(convertToModels(wlyyInspectionDao.findByPrescriptionId(vo.getId(), 1), inspectionVOs, WlyyInspectionVO.class));
                if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                    WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO1 = prescriptionEmrDao.findEmrByPrescriptionId(vo.getId());
                    WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO1 = prescriptionEmrDao.findEmrByPrescriptionId(vo.getId());
                    if (wlyyPrescriptionEmrDO1!=null){
                    if (wlyyPrescriptionEmrDO1 != null) {
                        vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO1);
                        vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO1);
                    }else {
                    } else {
                        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = readOutPatientXml(outpatientDO.getOriginRegisterNo());
                        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = readOutPatientXml(outpatientDO.getOriginRegisterNo());
                        //电子病历
                        //电子病历
                        vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO);
                        vo.setWlyyPrescriptionEmrDO(wlyyPrescriptionEmrDO);
@ -516,34 +521,34 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            }
            }
        }
        }
        rs.put("prescriptions",prescriptionVOs);
        rs.put("prescriptions", prescriptionVOs);
        //物流信息
        //物流信息
        List<WlyyPrescriptionExpressageDO> expressageDOs = prescriptionExpressageDao.findByOutpatientId(outpatientId);
        List<WlyyPrescriptionExpressageDO> expressageDOs = prescriptionExpressageDao.findByOutpatientId(outpatientId);
        if(expressageDOs!=null&&expressageDOs.size()>0){
            rs.put("expressage",convertToModel(expressageDOs.get(0), WlyyPrescriptionExpressageVO.class));
        }else{
            rs.put("expressage",null);
        if (expressageDOs != null && expressageDOs.size() > 0) {
            rs.put("expressage", convertToModel(expressageDOs.get(0), WlyyPrescriptionExpressageVO.class));
        } else {
            rs.put("expressage", null);
        }
        }
        if (!wechatId.equalsIgnoreCase("xm_ykyy_wx")){
        if (!wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
            //物流配送新
            //物流配送新
            List<WlyyPrescriptionExpressageLogDO>  expressageLogDOs = prescriptionExpressageLogDao.queryByOutpatientIdOrderByCreateTimeDesc(outpatientId);
            List<WlyyPrescriptionExpressageLogDO> expressageLogDOs = prescriptionExpressageLogDao.queryByOutpatientIdOrderByCreateTimeDesc(outpatientId);
            List<WlyyPrescriptionExpressageLogVO> expressageLogVOs = new ArrayList<>();
            List<WlyyPrescriptionExpressageLogVO> expressageLogVOs = new ArrayList<>();
            if(expressageLogDOs!=null&&expressageLogDOs.size()>0){
                rs.put("expressageLogs",convertToModels(expressageLogDOs,expressageLogVOs, WlyyPrescriptionExpressageLogVO.class));
            }else{
                rs.put("expressageLogs",null);
            if (expressageLogDOs != null && expressageLogDOs.size() > 0) {
                rs.put("expressageLogs", convertToModels(expressageLogDOs, expressageLogVOs, WlyyPrescriptionExpressageLogVO.class));
            } else {
                rs.put("expressageLogs", null);
            }
            }
        }
        }
        //预约记录
        //预约记录
        List<WlyyPatientRegisterTimeDO> timeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientId);
        List<WlyyPatientRegisterTimeDO> timeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientId);
        if(timeDOs!=null&&timeDOs.size()>0){
            rs.put("register",timeDOs.get(0));
        }else{
            rs.put("register",null);
        if (timeDOs != null && timeDOs.size() > 0) {
            rs.put("register", timeDOs.get(0));
        } else {
            rs.put("register", null);
        }
        }
        return rs;
        return rs;
@ -552,6 +557,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询历史
     * 查询历史
     *
     * @param patient
     * @param patient
     * @param status
     * @param status
     * @param startTime
     * @param startTime
@ -560,32 +566,32 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param size
     * @param size
     * @return
     * @return
     */
     */
    public MixEnvelop findPrescriptionList(String patient, String status,String startTime, String endTime, Integer page, Integer size,String wxId){
    public MixEnvelop findPrescriptionList(String patient, String status, String startTime, String endTime, Integer page, Integer size, String wxId) {
        String totalSql ="SELECT " +
        String totalSql = "SELECT " +
                " count(1) AS \"total\" " +
                " count(1) AS \"total\" " +
                " FROM " +
                " FROM " +
                " wlyy_prescription p ";
                " wlyy_prescription p ";
        totalSql += " WHERE 1=1 ";
        totalSql += " WHERE 1=1 ";
        if(StringUtils.isNotBlank(patient)){
            totalSql+=" AND p.patient_code ='"+patient+"'";
        if (StringUtils.isNotBlank(patient)) {
            totalSql += " AND p.patient_code ='" + patient + "'";
        }
        }
        if(StringUtils.isNotBlank(status)){
            totalSql+=" AND p.status IN ("+status+")";
        if (StringUtils.isNotBlank(status)) {
            totalSql += " AND p.status IN (" + status + ")";
        }
        }
        if(StringUtils.isNotBlank(startTime)){
            if("xm_ykyy_wx".equals(wxId)){
                totalSql +=" and create_time >= to_date('"+startTime+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                totalSql += " AND create_time >='"+startTime+" 00:00:00'";
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                totalSql += " and create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                totalSql += " AND create_time >='" + startTime + " 00:00:00'";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                totalSql +=" and create_time <= to_date('"+startTime+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
                totalSql += " AND create_time <='"+endTime+" 23:59:59'";
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                totalSql += " and create_time <= to_date('" + startTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                totalSql += " AND create_time <='" + endTime + " 23:59:59'";
            }
            }
        }
        }
@ -596,7 +602,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            count = Long.parseLong(rstotal.get(0).get("total").toString());
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                " p.id as \"id\", " +
                " p.id as \"id\", " +
                " p.real_order AS \"realOrder\"," +
                " p.real_order AS \"realOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
@ -642,82 +648,82 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " FROM " +
                " FROM " +
                " wlyy_prescription p " +
                " wlyy_prescription p " +
                " WHERE 1=1 ";
                " WHERE 1=1 ";
        if(StringUtils.isNotBlank(patient)){
            sql+=" AND p.patient_code ='"+patient+"'";
        if (StringUtils.isNotBlank(patient)) {
            sql += " AND p.patient_code ='" + patient + "'";
        }
        }
        if(StringUtils.isNotBlank(status)){
            sql+=" AND p.status IN ("+status+")";
        if (StringUtils.isNotBlank(status)) {
            sql += " AND p.status IN (" + status + ")";
        }
        }
        if(StringUtils.isNotBlank(startTime)){
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and create_time >= to_date('"+startTime+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sql += " AND create_time >='"+startTime+" 00:00:00'";
        if (StringUtils.isNotBlank(startTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND create_time >='" + startTime + " 00:00:00'";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and create_time <= to_date('"+startTime+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sql += " AND create_time <='"+endTime+" 23:59:59'";
        if (StringUtils.isNotBlank(endTime)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and create_time <= to_date('" + startTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND create_time <='" + endTime + " 23:59:59'";
            }
            }
        }
        }
        sql += " LIMIT " + (page - 1) * size + "," + size + "";
        sql += " LIMIT " + (page - 1) * size + "," + size + "";
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));
        //设置病种,药品
        //设置病种,药品
        if(list!=null&&list.size()>0){
            for(WlyyPrescriptionVO vo:list){
        if (list != null && list.size() > 0) {
            for (WlyyPrescriptionVO vo : list) {
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                vo.setDiagnosisVOs(findDiagnosisById(vo.getId()));
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                List<WlyyPrescriptionInfoVO> infoVOs = new ArrayList<>();
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(),1),infoVOs,WlyyPrescriptionInfoVO.class));
                vo.setInfoVOs(convertToModels(prescriptionInfoDao.findByPrescriptionId(vo.getId(), 1), infoVOs, WlyyPrescriptionInfoVO.class));
            }
            }
        }
        }
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }
    }
    public List<WlyyPrescriptionDiagnosisVO> findDiagnosisById(String id){
        List<WlyyPrescriptionDiagnosisDO> list = prescriptionDiagnosisDao.findByPrescriptionId(id,1);
    public List<WlyyPrescriptionDiagnosisVO> findDiagnosisById(String id) {
        List<WlyyPrescriptionDiagnosisDO> list = prescriptionDiagnosisDao.findByPrescriptionId(id, 1);
        List<WlyyPrescriptionDiagnosisVO> rs = new ArrayList<>();
        List<WlyyPrescriptionDiagnosisVO> rs = new ArrayList<>();
        if(list!=null&&list.size()>0){
            return convertToModels(list,rs,WlyyPrescriptionDiagnosisVO.class);
        if (list != null && list.size() > 0) {
            return convertToModels(list, rs, WlyyPrescriptionDiagnosisVO.class);
        }
        }
        return rs;
        return rs;
    }
    }
    public WlyyPrescriptionDO findPrescriptionDo(String prescriptionId){
    public WlyyPrescriptionDO findPrescriptionDo(String prescriptionId) {
        return prescriptionDao.findOne(prescriptionId);
        return prescriptionDao.findOne(prescriptionId);
    }
    }
    public Map<String,Object> findPrescriptionInfo(String prescriptionId){
    public Map<String, Object> findPrescriptionInfo(String prescriptionId) {
        //续方信息
        //续方信息
        Map<String,Object> rs = new HashedMap();
        Map<String, Object> rs = new HashedMap();
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        rs.put("prescription",convertToModel(wlyyPrescriptionDO,WlyyPrescriptionVO.class));
        rs.put("prescription", convertToModel(wlyyPrescriptionDO, WlyyPrescriptionVO.class));
        //居民详情
        //居民详情
        BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDO.getPatientCode());
        BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDO.getPatientCode());
        rs.put("patientName",basePatientDO.getName());
        rs.put("patientId",basePatientDO.getId());
        rs.put("idCard",basePatientDO.getIdcard());
        rs.put("patientName", basePatientDO.getName());
        rs.put("patientId", basePatientDO.getId());
        rs.put("idCard", basePatientDO.getIdcard());
        rs.put("sex", basePatientDO.getSex());
        rs.put("sex", basePatientDO.getSex());
        PatientMedicareCardDO cardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel(PatientMedicareCardDO.Type.MedicareCard.getType(),wlyyPrescriptionDO.getPatientCode(),"1");
        rs.put("ssc",cardDO);
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        PatientMedicareCardDO cardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel(PatientMedicareCardDO.Type.MedicareCard.getType(), wlyyPrescriptionDO.getPatientCode(), "1");
        rs.put("ssc", cardDO);
        rs.put("age", IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        //诊断信息
        //诊断信息
        rs.put("diagnosis",findDiagnosisById(wlyyPrescriptionDO.getId()));
        rs.put("diagnosis", findDiagnosisById(wlyyPrescriptionDO.getId()));
        //药品信息
        //药品信息
        rs.put("infos",prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(),1));
        rs.put("infos", prescriptionInfoDao.findByPrescriptionId(wlyyPrescriptionDO.getId(), 1));
        return rs;
        return rs;
    }
    }
    public Boolean checkPrescription(String patient){
    public Boolean checkPrescription(String patient) {
        List<WlyyPrescriptionDO> list = prescriptionDao.findByPatientCode(patient);
        List<WlyyPrescriptionDO> list = prescriptionDao.findByPatientCode(patient);
        if(list!=null&&list.size()>0){
        if (list != null && list.size() > 0) {
            return false;
            return false;
        }
        }
        return true;
        return true;
@ -726,15 +732,16 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 发起图文和视频复诊
     * 发起图文和视频复诊
     *
     * @param outpatientJson
     * @param outpatientJson
     * @param expressageJson
     * @param expressageJson
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public WlyyOutpatientDO appointmentRevisit(String outpatientJson,String expressageJson,String registerJson,String chargeType)throws Exception{
    public WlyyOutpatientDO appointmentRevisit(String outpatientJson, String expressageJson, String registerJson, String chargeType) throws Exception {
        //1.保存就诊实体
        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson,WlyyOutpatientDO.class);
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
@ -746,48 +753,47 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setCreateTime(new Date());
        if(outpatientDO.getRegisterDate()==null){
        if (outpatientDO.getRegisterDate() == null) {
            outpatientDO.setRegisterDate(new Date());
            outpatientDO.setRegisterDate(new Date());
        }
        }
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        WlyyOutpatientDO outpatient = outpatientDao.save(outpatientDO);
        Double price = 0.0;
        Double price = 0.0;
        if(doctorDO!=null&&StringUtils.isNoneBlank(doctorDO.getFee())){
        if (doctorDO != null && StringUtils.isNoneBlank(doctorDO.getFee())) {
            price = Double.parseDouble(doctorDO.getFee());
            price = Double.parseDouble(doctorDO.getFee());
        }
        }
        if(price==0.0){
        if (price == 0.0) {
            outpatientDO.setPayStatus(1);
            outpatientDO.setPayStatus(1);
        }else {
        } else {
            outpatientDO.setPayStatus(0);
            outpatientDO.setPayStatus(0);
        }
        }
        businessOrderService.recharge(outpatient.getId(),"复诊-诊查费","2","复诊-诊查费",patientDO.getId(),patientDO.getName(),outpatient.getDoctor(),price);
        businessOrderService.recharge(outpatient.getId(), "复诊-诊查费", "2", "复诊-诊查费", patientDO.getId(), patientDO.getName(), outpatient.getDoctor(), price);
        WlyyPatientRegisterTimeDO registerTimeDO = null;
        WlyyPatientRegisterTimeDO registerTimeDO = null;
        try {
        try {
            //如果是视频预约咨询
            //如果是视频预约咨询
            if(StringUtils.isNotBlank(registerJson)){
                registerTimeDO = objectMapper.readValue(registerJson,WlyyPatientRegisterTimeDO.class);
            if (StringUtils.isNotBlank(registerJson)) {
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                registerTimeDO.setCreateTime(new Date());
                patientRegisterTimeDao.save(registerTimeDO);
                patientRegisterTimeDao.save(registerTimeDO);
            }
            }
        }catch (Exception e){
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约,请选择其他号源");
            throw new RuntimeException("号源已经被预约,请选择其他号源");
        }
        }
        //2.物流信息
        //2.物流信息
        WlyyPrescriptionExpressageDO expressageDO = objectMapper.readValue(expressageJson,WlyyPrescriptionExpressageDO.class);
        WlyyPrescriptionExpressageDO expressageDO = objectMapper.readValue(expressageJson, WlyyPrescriptionExpressageDO.class);
        expressageDO.setDel(1);
        expressageDO.setDel(1);
        expressageDO.setCreateTime(new Date());
        expressageDO.setCreateTime(new Date());
        expressageDO.setOutpatientId(outpatient.getId());
        expressageDO.setOutpatientId(outpatient.getId());
        prescriptionExpressageDao.save(expressageDO);
        prescriptionExpressageDao.save(expressageDO);
        //3.创建候诊室
        //3.创建候诊室
        createRoom(outpatient,chargeType);
        createRoom(outpatient, chargeType);
        return outpatient;
        return outpatient;
    }
    }
@ -795,10 +801,11 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 创建候诊室
     * 创建候诊室
     *
     * @param outpatientDO
     * @param outpatientDO
     * @return
     * @return
     */
     */
    public Boolean createRoom(WlyyOutpatientDO outpatientDO,String chargeType){
    public Boolean createRoom(WlyyOutpatientDO outpatientDO, String chargeType) {
        WlyyHospitalWaitingRoomDO waitingRoom = new WlyyHospitalWaitingRoomDO();
        WlyyHospitalWaitingRoomDO waitingRoom = new WlyyHospitalWaitingRoomDO();
@ -808,7 +815,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        waitingRoom.setHospitalName(outpatientDO.getHospitalName());
        waitingRoom.setHospitalName(outpatientDO.getHospitalName());
        //是否是有协同门诊医生
        //是否是有协同门诊医生
        if(StringUtils.isNotBlank(outpatientDO.getGeneralDoctor())){
        if (StringUtils.isNotBlank(outpatientDO.getGeneralDoctor())) {
            waitingRoom.setGeneralDoctor(outpatientDO.getGeneralDoctor());
            waitingRoom.setGeneralDoctor(outpatientDO.getGeneralDoctor());
            waitingRoom.setGeneralDoctorName(outpatientDO.getGeneralDoctorName());
            waitingRoom.setGeneralDoctorName(outpatientDO.getGeneralDoctorName());
        }
        }
@ -818,18 +825,18 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        waitingRoom.setReservationTime(outpatientDO.getRegisterDate());
        waitingRoom.setReservationTime(outpatientDO.getRegisterDate());
        waitingRoom.setVisitStatus(0);
        waitingRoom.setVisitStatus(0);
        //设置复诊类型
        //设置复诊类型
        waitingRoom.setReservationType(StringUtils.isNotBlank(outpatientDO.getOutpatientType())?Integer.parseInt(outpatientDO.getOutpatientType()):1);
        waitingRoom.setReservationType(StringUtils.isNotBlank(outpatientDO.getOutpatientType()) ? Integer.parseInt(outpatientDO.getOutpatientType()) : 1);
        waitingRoom.setSort(0);
        waitingRoom.setSort(0);
        waitingRoom.setConsultType(Integer.parseInt(outpatientDO.getType()));
        waitingRoom.setConsultType(Integer.parseInt(outpatientDO.getType()));
        if(StringUtils.isNotBlank(outpatientDO.getDoctor())){
        if (StringUtils.isNotBlank(outpatientDO.getDoctor())) {
            waitingRoom.setDoctor(outpatientDO.getDoctor());
            waitingRoom.setDoctor(outpatientDO.getDoctor());
            waitingRoom.setDoctorName(outpatientDO.getDoctorName());
            waitingRoom.setDoctorName(outpatientDO.getDoctorName());
        }
        }
        waitingRoom.setOutpatientId(outpatientDO.getId());
        waitingRoom.setOutpatientId(outpatientDO.getId());
        waitingRoom.setCreateTime(new Date());
        waitingRoom.setCreateTime(new Date());
        if(StringUtils.isNotBlank(chargeType)){
        if (StringUtils.isNotBlank(chargeType)) {
            waitingRoom.setChargeType(chargeType);
            waitingRoom.setChargeType(chargeType);
        }
        }
@ -839,7 +846,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    public Boolean cancelPrescription(String prescriptionId){
    public Boolean cancelPrescription(String prescriptionId) {
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        prescriptionDO.setStatus(-2);
        prescriptionDO.setStatus(-2);
        return true;
        return true;
@ -847,18 +854,18 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     *@param admNo 门诊唯一号
     * @param admNo     门诊唯一号
     * @param realOrder 处方号
     * @param realOrder 处方号
     *  @param status 处方状态 1审方失败,2审核完成,3结算完成
     * @param status    处方状态 1审方失败,2审核完成,3结算完成
     * @return
     * @return
     */
     */
    public Map<String,Object> updatePrescriptionByHisStatu(String admNo,String realOrder,String status)throws Exception {
        Map<String,Object> rs = new HashedMap();
    public Map<String, Object> updatePrescriptionByHisStatu(String admNo, String realOrder, String status) throws Exception {
        Map<String, Object> rs = new HashedMap();
        String sql = "";
        String sql = "";
        //status 处方流程状态 ,13  开方失败/调整中,20 诊断完成/开方成功/待支付,已完成:100 已完成
        //status 处方流程状态 ,13  开方失败/调整中,20 诊断完成/开方成功/待支付,已完成:100 已完成
        //pay_status`:处方结算状态,0为未结算,1为结算成功,默认为0',
        //pay_status`:处方结算状态,0为未结算,1为结算成功,默认为0',
        String outPatientSql="";
        String outPatientSql = "";
        if ("1".equals(status)) {
        if ("1".equals(status)) {
            sql = "UPDATE base.wlyy_prescription p SET p.status='13' WHERE p.adm_no='" + admNo + "' AND p.real_order='" + realOrder + "' ";
            sql = "UPDATE base.wlyy_prescription p SET p.status='13' WHERE p.adm_no='" + admNo + "' AND p.real_order='" + realOrder + "' ";
            WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findByRealOrder(realOrder);
            WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findByRealOrder(realOrder);
@ -868,7 +875,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            //开方成功时候,先用处方号获取本地处方状态是否为开方失败,如果是则需要更新本地的处方
            //开方成功时候,先用处方号获取本地处方状态是否为开方失败,如果是则需要更新本地的处方
            sql = "UPDATE base.wlyy_prescription p SET p.status='20' WHERE p.adm_no='" + admNo + "' AND p.real_order='" + realOrder + "' ";
            sql = "UPDATE base.wlyy_prescription p SET p.status='20' WHERE p.adm_no='" + admNo + "' AND p.real_order='" + realOrder + "' ";
            //变更门诊状态
            //变更门诊状态
            outPatientSql="UPDATE base.wlyy_outpatient p SET p.`status`='2' WHERE p.adm_no='" + admNo + "'";
            outPatientSql = "UPDATE base.wlyy_outpatient p SET p.`status`='2' WHERE p.adm_no='" + admNo + "'";
            jdbcTemplate.execute(outPatientSql);
            jdbcTemplate.execute(outPatientSql);
            jdbcTemplate.execute(sql);
            jdbcTemplate.execute(sql);
@ -882,7 +889,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setStatus(100);
                wlyyPrescriptionDO.setStatus(100);
                prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(),100,2,outpatientDO.getDoctor(),outpatientDO.getDoctorName(),"",new Date());
                prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(), 100, 2, outpatientDO.getDoctor(), outpatientDO.getDoctorName(), "", new Date());
                prescriptionDao.save(wlyyPrescriptionDO);
                prescriptionDao.save(wlyyPrescriptionDO);
            } else {
            } else {
@ -890,30 +897,30 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setPayStatus(1);
                wlyyPrescriptionDO.setStatus(32);
                wlyyPrescriptionDO.setStatus(32);
                try{
                    WlyyPrescriptionVO vo = findOriginPrescription(outpatientDO.getRegisterNo(),outpatientDO.getPatient(),admNo,realOrder,demoFlag);
                try {
                    WlyyPrescriptionVO vo = findOriginPrescription(outpatientDO.getRegisterNo(), outpatientDO.getPatient(), admNo, realOrder, demoFlag);
                    wlyyPrescriptionDO.setDispUser(vo.getDispUser());
                    wlyyPrescriptionDO.setDispUser(vo.getDispUser());
                    wlyyPrescriptionDO.setDispUserName(vo.getDispUserName());
                    wlyyPrescriptionDO.setDispUserName(vo.getDispUserName());
                    wlyyPrescriptionDO.setDispDate(new Date());
                    wlyyPrescriptionDO.setDispDate(new Date());
                    prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(),32,2,vo.getDispUser(),vo.getDispUserName(),"",new Date());
                }catch (Exception e){
                    logger.error("获取处方信息异常"+e.toString());
                    prescriptionLogService.addPrescriptionLog(wlyyPrescriptionDO.getId(), 32, 2, vo.getDispUser(), vo.getDispUserName(), "", new Date());
                } catch (Exception e) {
                    logger.error("获取处方信息异常" + e.toString());
                }
                }
                prescriptionDao.save(wlyyPrescriptionDO);
                prescriptionDao.save(wlyyPrescriptionDO);
            }
            }
            //发送取药系统消息
            //发送取药系统消息
            SystemMessageDO systemMessageDO = sendPatientGetDrugMes(outpatientDO,wlyyPrescriptionDO);
            SystemMessageDO systemMessageDO = sendPatientGetDrugMes(outpatientDO, wlyyPrescriptionDO);
            rs.put("mes",systemMessageDO);
            rs.put("mes", systemMessageDO);
        }
        }
        rs.put("flag",true);
        rs.put("flag", true);
        return rs;
        return rs;
    }
    }
    public SystemMessageDO sendPatientGetDrugMes(WlyyOutpatientDO outpatient,WlyyPrescriptionDO prescriptionDO){
    public SystemMessageDO sendPatientGetDrugMes(WlyyOutpatientDO outpatient, WlyyPrescriptionDO prescriptionDO) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        try{
        try {
            systemMessageDO.setTitle("患者取药");
            systemMessageDO.setTitle("患者取药");
            systemMessageDO.setType("7");
            systemMessageDO.setType("7");
@ -925,37 +932,38 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            systemMessageDO.setRelationCode(outpatient.getId());
            systemMessageDO.setRelationCode(outpatient.getId());
            JSONObject data = new JSONObject();
            JSONObject data = new JSONObject();
            data.put("name",outpatient.getPatientName());
            data.put("age",IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
            data.put("gender",IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
            data.put("recipeType",prescriptionDO.getDispensaryType());
            data.put("message","患者已完成取药");
            data.put("name", outpatient.getPatientName());
            data.put("age", IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
            data.put("gender", IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
            data.put("recipeType", prescriptionDO.getDispensaryType());
            data.put("message", "患者已完成取药");
            systemMessageDO.setData(data.toString());
            systemMessageDO.setData(data.toString());
            systemMessageService.saveMessage(systemMessageDO);
            systemMessageService.saveMessage(systemMessageDO);
        }catch (Exception e){
            logger.error("sendPatientGetDrugMes :"+e.toString());
        } catch (Exception e) {
            logger.error("sendPatientGetDrugMes :" + e.toString());
        }
        }
        return systemMessageDO;
        return systemMessageDO;
    }
    }
    /**
    /**
     * 获取卡记录
     * 获取卡记录
     *
     * @param patient
     * @param patient
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public JSONArray findPatientCard(String patient)throws Exception{
    public JSONArray findPatientCard(String patient) throws Exception {
        BasePatientDO patientDO = basePatientDao.findById(patient);
        BasePatientDO patientDO = basePatientDao.findById(patient);
        JSONArray res = entranceService.BS15018(patientDO.getIdcard(),null,demoFlag);
        JSONArray res = entranceService.BS15018(patientDO.getIdcard(), null, demoFlag);
        JSONArray rs = new JSONArray();
        JSONArray rs = new JSONArray();
        if(res !=null){
            for (int i =0;i<res.size();i++){
        if (res != null) {
            for (int i = 0; i < res.size(); i++) {
                JSONObject card = res.getJSONObject(i);
                JSONObject card = res.getJSONObject(i);
                String cardStat = card.getString("CARD_STAT");
                String cardStat = card.getString("CARD_STAT");
                if("激活".equals(cardStat)){
                if ("激活".equals(cardStat)) {
                    rs.add(card);
                    rs.add(card);
                }
                }
            }
            }
@ -964,53 +972,54 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    public Map<String,Object> checkOutpatient(String patient)throws Exception{
    public Map<String, Object> checkOutpatient(String patient) throws Exception {
        //-1卡余额不足,,-2 存在未结束的诊断热 1成功
        //-1卡余额不足,,-2 存在未结束的诊断热 1成功
        Map<String,Object> rs = new HashedMap();
        Map<String, Object> rs = new HashedMap();
        //1.余额判断改到前端判断
        //1.余额判断改到前端判断
        //net.sf.json.JSONObject json = entranceService.qutpatientBalance(cardNo,demoFlag);
        //net.sf.json.JSONObject json = entranceService.qutpatientBalance(cardNo,demoFlag);
        //2.判断是否有未结束的
        //2.判断是否有未结束的
        List<WlyyOutpatientDO> list = outpatientDao.findByPatientList(patient);
        List<WlyyOutpatientDO> list = outpatientDao.findByPatientList(patient);
        if(list!=null&&list.size()>0){
            rs.put("outpatient",list.get(0));
            rs.put("code",-2);
            rs.put("mes","存在未结束的诊断");
        if (list != null && list.size() > 0) {
            rs.put("outpatient", list.get(0));
            rs.put("code", -2);
            rs.put("mes", "存在未结束的诊断");
            return rs;
            return rs;
        }
        }
        rs.put("code",1);
        rs.put("mes","验证通过");
        rs.put("code", 1);
        rs.put("mes", "验证通过");
        return rs;
        return rs;
    }
    }
    /**
    /**
     * 获取所有医院列表
     * 获取所有医院列表
     *
     * @return
     * @return
     */
     */
    public List<BaseOrgVO> findAllHospital(Integer level,String keyWord){
    public List<BaseOrgVO> findAllHospital(Integer level, String keyWord) {
        if (StringUtils.isNoneEmpty(keyWord)) {
        if (StringUtils.isNoneEmpty(keyWord)) {
            keyWord = "%" + keyWord + "%";
            keyWord = "%" + keyWord + "%";
            if(level!=null){
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndName(level,"1",keyWord);
            if (level != null) {
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndName(level, "1", keyWord);
                List<BaseOrgVO> rs = new ArrayList<>();
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list,rs,BaseOrgVO.class);
            }else {
                List<BaseOrgDO> list = baseOrgDao.findByDelAndName("1",keyWord);
                return convertToModels(list, rs, BaseOrgVO.class);
            } else {
                List<BaseOrgDO> list = baseOrgDao.findByDelAndName("1", keyWord);
                List<BaseOrgVO> rs = new ArrayList<>();
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list,rs,BaseOrgVO.class);
                return convertToModels(list, rs, BaseOrgVO.class);
            }
            }
        }else{
        } else {
            if(level!=null){
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndDel(level,"1");
            if (level != null) {
                List<BaseOrgDO> list = baseOrgDao.findByLevelAndDel(level, "1");
                List<BaseOrgVO> rs = new ArrayList<>();
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list,rs,BaseOrgVO.class);
            }else {
                return convertToModels(list, rs, BaseOrgVO.class);
            } else {
                List<BaseOrgDO> list = baseOrgDao.findByDel("1");
                List<BaseOrgDO> list = baseOrgDao.findByDel("1");
                List<BaseOrgVO> rs = new ArrayList<>();
                List<BaseOrgVO> rs = new ArrayList<>();
                return convertToModels(list,rs,BaseOrgVO.class);
                return convertToModels(list, rs, BaseOrgVO.class);
            }
            }
        }
        }
@ -1044,9 +1053,6 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    /**
    /**
     * 获取医生列表.
     * 获取医生列表.
     *
     *
@ -1054,8 +1060,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param dept
     * @param dept
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findDoctorByHospitalAndDept(String orgCode,String dept,String chargeType,String doctorCode,String outpatientType,String startDate,String endDate,String key,String consultStatus){
        String sql ="SELECT " +
    public List<Map<String, Object>> findDoctorByHospitalAndDept(String orgCode, String dept, String chargeType, String doctorCode, String outpatientType, String startDate, String endDate, String key, String consultStatus) {
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.name AS \"name\", " +
@ -1071,7 +1077,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " WHERE  " +
                " WHERE  " +
                " 1=1";
                " 1=1";
        Map<String,Object> params = new HashedMap();
        Map<String, Object> params = new HashedMap();
        if (StringUtils.isNotBlank(dept)) {
        if (StringUtils.isNotBlank(dept)) {
            sql += " AND h.dept_code = '" + dept + "'";
            sql += " AND h.dept_code = '" + dept + "'";
        }
        }
@ -1113,14 +1119,14 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " AND t.start_time >=:startDate" +
                    " AND t.start_time >=:startDate" +
                    " AND t.start_time <=:endDate" +
                    " AND t.start_time <=:endDate" +
                    " )";
                    " )";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-ss HH:mm:ss"));
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-ss HH:mm:ss"));
            params.put("startDate", DateUtil.stringToDate(startDate, "yyyy-MM-ss HH:mm:ss"));
            params.put("endDate", DateUtil.stringToDate(endDate, "yyyy-MM-ss HH:mm:ss"));
        }
        }
        logger.info("findDoctorByHospitalAndDept sql:" + sql);
        logger.info("findDoctorByHospitalAndDept sql:" + sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,params);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params);
        if (list != null && list.size() > 0 && StringUtils.isNotBlank(doctorCode)) {
        if (list != null && list.size() > 0 && StringUtils.isNotBlank(doctorCode)) {
            //排序
            //排序
@ -1151,7 +1157,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " WHERE  " +
                " WHERE  " +
                " 1=1 ";
                " 1=1 ";
        Map<String,Object> params = new HashedMap();
        Map<String, Object> params = new HashedMap();
        if (StringUtils.isNotBlank(dept)) {
        if (StringUtils.isNotBlank(dept)) {
            totalSql += " AND h.dept_code = '" + dept + "'";
            totalSql += " AND h.dept_code = '" + dept + "'";
        }
        }
@ -1159,9 +1165,9 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            totalSql += " AND h.org_code = '" + orgCode + "'";
            totalSql += " AND h.org_code = '" + orgCode + "'";
        }
        }
        if (StringUtils.isNotBlank(chargeType)) {
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)){
            if ("all".equalsIgnoreCase(chargeType)) {
            }else {
            } else {
                totalSql += " AND d.charge_type ='" + chargeType + "'";
                totalSql += " AND d.charge_type ='" + chargeType + "'";
            }
            }
        } else {
        } else {
@ -1202,10 +1208,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " AND t.start_time >=:startDate" +
                    " AND t.start_time >=:startDate" +
                    " AND t.start_time <=:endDate" +
                    " AND t.start_time <=:endDate" +
                    " )";
                    " )";
            params.put("startDate",DateUtil.stringToDate(startDate,"yyyy-MM-ss HH:mm:ss"));
            params.put("endDate",DateUtil.stringToDate(endDate,"yyyy-MM-ss HH:mm:ss"));
            params.put("startDate", DateUtil.stringToDate(startDate, "yyyy-MM-ss HH:mm:ss"));
            params.put("endDate", DateUtil.stringToDate(endDate, "yyyy-MM-ss HH:mm:ss"));
        }
        }
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql,params);
        List<Map<String, Object>> rstotal = hibenateUtils.createSQLQuery(totalSql, params);
        Long count = 0L;
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
        if (rstotal != null && rstotal.size() > 0) {
@ -1238,9 +1244,9 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        }
        }
        if (StringUtils.isNotBlank(chargeType)) {
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equalsIgnoreCase(chargeType)){
            if ("all".equalsIgnoreCase(chargeType)) {
            }else {
            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
            }
        } else {
        } else {
@ -1285,8 +1291,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " )";
                    " )";
        }
        }
        sql += " AND d.del='1' AND d.outpatient_type is not null ";
        sql += " AND d.del='1' AND d.outpatient_type is not null ";
        logger.info("withwork sql:" +sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,params,page,size);
        logger.info("withwork sql:" + sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, size);
        if (list != null && list.size() > 0) {
        if (list != null && list.size() > 0) {
            //获取排班
            //获取排班
            for (Map<String, Object> doctor : list) {
            for (Map<String, Object> doctor : list) {
@ -1314,22 +1320,22 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        if (list != null && list.size() > 0) {
        if (list != null && list.size() > 0) {
            WlyyHospitalWorkRuleDO rule = list.get(0);
            WlyyHospitalWorkRuleDO rule = list.get(0);
            String openTimeString = DateUtil.dateToStr(new Date(), "yyyy-MM-dd")+ " " + rule.getMaxDayOpenTime() + ":00";
            logger.info("today openTimeString :"+openTimeString);
            String openTimeString = DateUtil.dateToStr(new Date(), "yyyy-MM-dd") + " " + rule.getMaxDayOpenTime() + ":00";
            logger.info("today openTimeString :" + openTimeString);
            Date openTime = DateUtil.strToDate(openTimeString, "yyyy-MM-dd HH:mm:ss");
            Date openTime = DateUtil.strToDate(openTimeString, "yyyy-MM-dd HH:mm:ss");
            Integer openDay = rule.getMaxDay();
            Integer openDay = rule.getMaxDay();
            if (openTime.before(new Date())) {
            if (openTime.before(new Date())) {
                openDay = openDay - 1;
                openDay = openDay - 1;
            }
            }
            Date preDate =  DateUtil.getPreDays(new Date(), openDay);
            String maxDateString = DateUtil.dateToStr(preDate,"yyyy-MM-dd")+" 23:59:59";
            logger.info("maxDateString :"+maxDateString);
            Date preDate = DateUtil.getPreDays(new Date(), openDay);
            String maxDateString = DateUtil.dateToStr(preDate, "yyyy-MM-dd") + " 23:59:59";
            logger.info("maxDateString :" + maxDateString);
            Date endDate = DateUtil.stringToDate(maxDateString, "yyyy-MM-dd HH:mm:ss");
            Date endDate = DateUtil.stringToDate(maxDateString, "yyyy-MM-dd HH:mm:ss");
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            List<WlyyDoctorWorkTimeDO> timeDOs = doctorWorkTimeDao.findDoctorWorkTime(doctor, new Date(), endDate);
            List<WlyyDoctorWorkTimeDO> timeDOs = doctorWorkTimeDao.findDoctorWorkTime(doctor, new Date(), endDate);
            if(timeDOs!=null&&timeDOs.size()>0){
            if (timeDOs != null && timeDOs.size() > 0) {
                convertToModels(timeDOs, timeVOs, WlyyDoctorWorkTimeVO.class);
                convertToModels(timeDOs, timeVOs, WlyyDoctorWorkTimeVO.class);
                if (timeVOs != null && timeVOs.size() > 0) {
                if (timeVOs != null && timeVOs.size() > 0) {
                    for (WlyyDoctorWorkTimeVO timeVO : timeVOs) {
                    for (WlyyDoctorWorkTimeVO timeVO : timeVOs) {
@ -1354,7 +1360,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param size
     * @param size
     * @return
     * @return
     */
     */
    public MixEnvelop findDoctorWithMouthWork(String orgCode, String dept, String chargeType, String date, String nameKey,String iswork, Integer page, Integer size) {
    public MixEnvelop findDoctorWithMouthWork(String orgCode, String dept, String chargeType, String date, String nameKey, String iswork, Integer page, Integer size) {
        String totalSql = "SELECT " +
        String totalSql = "SELECT " +
                " count(1) AS \"total\" " +
                " count(1) AS \"total\" " +
@ -1383,24 +1389,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            totalSql += " AND d.name like '%" + nameKey + "%' ";
            totalSql += " AND d.name like '%" + nameKey + "%' ";
        }
        }
        //过滤排班
        //过滤排班
        if(StringUtils.isNotBlank(iswork)){
            if("1".equals(iswork)){
                totalSql +=" AND d.id IN ( " +
        if (StringUtils.isNotBlank(iswork)) {
            if ("1".equals(iswork)) {
                totalSql += " AND d.id IN ( " +
                        " SELECT DISTINCT " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " t.doctor " +
                        " FROM " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        " WHERE " +
                        "  t.work_date LIKE '%"+date+"%' " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
                        " )";
            }else{
                totalSql +=" AND d.id NOT IN ( " +
            } else {
                totalSql += " AND d.id NOT IN ( " +
                        " SELECT DISTINCT " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " t.doctor " +
                        " FROM " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        " WHERE " +
                        "  t.work_date LIKE '%"+date+"%' " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
                        " )";
            }
            }
@ -1447,30 +1453,30 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            sql += " AND d.name like '%" + nameKey + "%' ";
            sql += " AND d.name like '%" + nameKey + "%' ";
        }
        }
        //过滤排班
        //过滤排班
        if(StringUtils.isNotBlank(iswork)){
            if("1".equals(iswork)){
                sql +=" AND d.id IN ( " +
        if (StringUtils.isNotBlank(iswork)) {
            if ("1".equals(iswork)) {
                sql += " AND d.id IN ( " +
                        " SELECT DISTINCT " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " t.doctor " +
                        " FROM " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        " WHERE " +
                        "  t.work_date LIKE '%"+date+"%' " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
                        " )";
            }else{
                sql +=" AND d.id NOT IN ( " +
            } else {
                sql += " AND d.id NOT IN ( " +
                        " SELECT DISTINCT " +
                        " SELECT DISTINCT " +
                        " t.doctor " +
                        " t.doctor " +
                        " FROM " +
                        " FROM " +
                        "  wlyy_doctor_work_time t " +
                        "  wlyy_doctor_work_time t " +
                        " WHERE " +
                        " WHERE " +
                        "  t.work_date LIKE '%"+date+"%' " +
                        "  t.work_date LIKE '%" + date + "%' " +
                        " )";
                        " )";
            }
            }
        }
        }
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,page,size);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, size);
        if (list != null && list.size() > 0) {
        if (list != null && list.size() > 0) {
            //获取排班
            //获取排班
            for (Map<String, Object> doctor : list) {
            for (Map<String, Object> doctor : list) {
@ -1798,6 +1804,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    public JSONArray getICD10(String pyKey) throws Exception {
    public JSONArray getICD10(String pyKey) throws Exception {
        return entranceService.MS25001(pyKey, demoFlag);
        return entranceService.MS25001(pyKey, demoFlag);
    }
    }
    /**
    /**
     * 获取药品
     * 获取药品
     *
     *
@ -1927,7 +1934,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param diagnosisJson
     * @param diagnosisJson
     * @return
     * @return
     */
     */
    public Map<String, Object> makeDiagnosis(String outPatientId, String advice, String type, String infoJsons, String diagnosisJson, String inspectionJson,String emrJson) throws Exception {
    public Map<String, Object> makeDiagnosis(String outPatientId, String advice, String type, String infoJsons, String diagnosisJson, String inspectionJson, String emrJson) throws Exception {
        Map<String, Object> result = new HashedMap();
        Map<String, Object> result = new HashedMap();
@ -1955,7 +1962,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        prescriptionDO.setDoctor(outpatientDO.getDoctor());
        prescriptionDO.setDoctor(outpatientDO.getDoctor());
        prescriptionDO.setDoctorName(outpatientDO.getDoctorName());
        prescriptionDO.setDoctorName(outpatientDO.getDoctorName());
        prescriptionDO.setPayStatus(0);
        prescriptionDO.setPayStatus(0);
        if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
        if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
            prescriptionDO.setAdmNo(outpatientDO.getAdmNo());
            prescriptionDO.setAdmNo(outpatientDO.getAdmNo());
        }
        }
        WlyyPrescriptionDO prescription = prescriptionDao.save(prescriptionDO);
        WlyyPrescriptionDO prescription = prescriptionDao.save(prescriptionDO);
@ -1967,7 +1974,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //============================下诊断==============================================================
        //============================下诊断==============================================================
        //删除之前诊断
        //删除之前诊断
        List<WlyyPrescriptionDiagnosisDO> ds = prescriptionDiagnosisDao.findByPrescriptionId(prescription.getId(),1);
        List<WlyyPrescriptionDiagnosisDO> ds = prescriptionDiagnosisDao.findByPrescriptionId(prescription.getId(), 1);
        if (ds != null && ds.size() > 0) {
        if (ds != null && ds.size() > 0) {
            prescriptionDiagnosisDao.deleteByPrescriptionId(prescription.getId());
            prescriptionDiagnosisDao.deleteByPrescriptionId(prescription.getId());
        }
        }
@ -1999,7 +2006,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //=====================电子病历=================================================start
        //=====================电子病历=================================================start
        prescriptionEmrDao.deleteByPrescriptionId(prescription.getId());
        prescriptionEmrDao.deleteByPrescriptionId(prescription.getId());
        if (StringUtils.isNotBlank(emrJson)) {
        if (StringUtils.isNotBlank(emrJson)) {
            WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = com.alibaba.fastjson.JSONObject.parseObject(emrJson,WlyyPrescriptionEmrDO.class);
            WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = com.alibaba.fastjson.JSONObject.parseObject(emrJson, WlyyPrescriptionEmrDO.class);
            wlyyPrescriptionEmrDO.setDel(1);
            wlyyPrescriptionEmrDO.setDel(1);
            wlyyPrescriptionEmrDO.setPrescriptionId(prescription.getId());
            wlyyPrescriptionEmrDO.setPrescriptionId(prescription.getId());
            prescriptionEmrDao.save(wlyyPrescriptionEmrDO);
            prescriptionEmrDao.save(wlyyPrescriptionEmrDO);
@ -2007,13 +2014,13 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //=====================电子病历=================================================end
        //=====================电子病历=================================================end
        //=====================保存日志 start=========================================================
        //=====================保存日志 start=========================================================
        List<WlyyPrescriptionCheckDO> prescriptionCheckDOS = prescriptionCheckDao.findByStatus(prescription.getId(),5);
        if (prescriptionCheckDOS==null || prescriptionCheckDOS.size() ==0){
            savePrescriptionCheck(prescription.getDoctor(),"开具处方",5,prescription.getId());
        List<WlyyPrescriptionCheckDO> prescriptionCheckDOS = prescriptionCheckDao.findByStatus(prescription.getId(), 5);
        if (prescriptionCheckDOS == null || prescriptionCheckDOS.size() == 0) {
            savePrescriptionCheck(prescription.getDoctor(), "开具处方", 5, prescription.getId());
        }
        }
        if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
        if (prescriptionDOs != null && prescriptionDOs.size() > 0) {
            savePrescriptionCheck(prescription.getDoctor(),"处方修改",3,prescription.getId());
            savePrescriptionCheck(prescription.getDoctor(), "处方修改", 3, prescription.getId());
        }
        }
        //=====================保存日志 end=========================================================
        //=====================保存日志 end=========================================================
@ -2027,10 +2034,9 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            }
            }
            //===================药品操作======================================================
            //===================药品操作======================================================
            // 删除原有药品信息
            // 删除原有药品信息
            List<WlyyPrescriptionInfoDO> oldInfos = prescriptionInfoDao.findByPrescriptionId(prescription.getId(),1);
            List<WlyyPrescriptionInfoDO> oldInfos = prescriptionInfoDao.findByPrescriptionId(prescription.getId(), 1);
            if (oldInfos != null && oldInfos.size() > 0) {
            if (oldInfos != null && oldInfos.size() > 0) {
                prescriptionInfoDao.deleteByPrescriptionId(prescription.getId());
                prescriptionInfoDao.deleteByPrescriptionId(prescription.getId());
            }
            }
@ -2051,7 +2057,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                prescriptionInfoDao.save(infoDOs);
                prescriptionInfoDao.save(infoDOs);
                logger.info("123");
                logger.info("123");
                Double price = getInfoFee(infoDOs);
                Double price = getInfoFee(infoDOs);
                logger.info("12312313213"+price);
                logger.info("12312313213" + price);
                //计算药品费用
                //计算药品费用
                prescription.setDrugFee(price);
                prescription.setDrugFee(price);
            }
            }
@ -2090,7 +2096,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            prescription.setPrescribeTime(new Date());
            prescription.setPrescribeTime(new Date());
            //保存费用
            //保存费用
            prescriptionDao.save(prescription);
            prescriptionDao.save(prescription);
            if (wechatId.equalsIgnoreCase("xm_ykyy_wx")){
            if (wechatId.equalsIgnoreCase("xm_ykyy_wx")) {
                outpatientDO.setStatus("2");
                outpatientDO.setStatus("2");
                outpatientDao.save(outpatientDO);
                outpatientDao.save(outpatientDO);
                //先下单
                //先下单
@ -2098,19 +2104,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                //同步his
                //同步his
                ykyyEntranceService.findByRealOrder(prescription.getId());
                ykyyEntranceService.findByRealOrder(prescription.getId());
                List<WlyyPrescriptionDO> prescriptionDOList = prescriptionDao.findById(prescription.getId());
                List<WlyyPrescriptionDO> prescriptionDOList = prescriptionDao.findById(prescription.getId());
                if(prescriptionDOList!=null&&prescriptionDOList.size()!=0){
                if (prescriptionDOList != null && prescriptionDOList.size() != 0) {
                    WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDOList.get(0);
                    WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDOList.get(0);
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
                    BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outpatientDO.getId());
                    logger.info("cfsb",wlyyPrescriptionDO.getRealOrder());
                    ykyyService.updateDrugorderInfo(businessOrderDO.getOrderNo(),wlyyPrescriptionDO.getOrderId(),wlyyPrescriptionDO.getRealOrder());
                    logger.info("cfsb", wlyyPrescriptionDO.getRealOrder());
                    ykyyService.updateDrugorderInfo(businessOrderDO.getOrderNo(), wlyyPrescriptionDO.getOrderId(), wlyyPrescriptionDO.getRealOrder());
                }
                }
                result.put("code", 1);
                result.put("code", 1);
                result.put("mes", "诊断完成");
                result.put("mes", "诊断完成");
                return result;
                return result;
            }else if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
            } else if (wechatId.equalsIgnoreCase("xm_zsyy_wx")) {
                Double price = prescription.getDrugFee();
                Double price = prescription.getDrugFee();
                businessOrderService.recharge(prescription.getId(),"处方收费","4","处方收费",prescription.getPatientCode(),prescription.getPatientName(),prescription.getDoctor(),price);
                businessOrderService.recharge(prescription.getId(), "处方收费", "4", "处方收费", prescription.getPatientCode(), prescription.getPatientName(), prescription.getDoctor(), price);
                //上传his开方
                //上传his开方
                //sendHisDiagnosis(jsonData, outpatientDO, prescription)
                //sendHisDiagnosis(jsonData, outpatientDO, prescription)
                //zsSynHis(prescription.getId());
                //zsSynHis(prescription.getId());
@ -2118,7 +2124,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                result1.put("code", 1);
                result1.put("code", 1);
                result1.put("mes", "开方提交成功");
                result1.put("mes", "开方提交成功");
                return result1;
                return result1;
            }else {
            } else {
                result.put("code", 1);
                result.put("code", 1);
                result.put("mes", "诊断完成");
                result.put("mes", "诊断完成");
                return result;
                return result;
@ -2137,8 +2143,6 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    /**
    /**
     * 计算药品费用
     * 计算药品费用
     *
     *
@ -2151,19 +2155,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        if (infoDOs != null && infoDOs.size() > 0) {
        if (infoDOs != null && infoDOs.size() > 0) {
            for (WlyyPrescriptionInfoDO info : infoDOs) {
            for (WlyyPrescriptionInfoDO info : infoDOs) {
                logger.error("getInfoFee===========Quantity:" +info.getQuantity());
          /*      Integer quantity = Integer.parseInt(info.getQuantity());*/
                logger.error("getInfoFee===========PackRetprice:" +info.getPackRetprice());
             /*   fee += info.getPackRetprice() * quantity;*/
                logger.error("getInfoFee===========:" +fee);
                logger.error("getInfoFee===========Quantity:" + info.getQuantity());
                /*      Integer quantity = Integer.parseInt(info.getQuantity());*/
                logger.error("getInfoFee===========PackRetprice:" + info.getPackRetprice());
                /*   fee += info.getPackRetprice() * quantity;*/
                logger.error("getInfoFee===========:" + fee);
                BigDecimal total = new BigDecimal(0);
                BigDecimal total = new BigDecimal(0);
                BigDecimal quantity = new BigDecimal(info.getQuantity());
                BigDecimal quantity = new BigDecimal(info.getQuantity());
                BigDecimal price = new BigDecimal(info.getPackRetprice());
                BigDecimal price = new BigDecimal(info.getPackRetprice());
                total = total.add(quantity.multiply(price));
                total = total.add(quantity.multiply(price));
                Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                fee+=f1;
                fee += f1;
            }
            }
            logger.error("getInfoFee===========:" +fee);
            logger.error("getInfoFee===========:" + fee);
        }
        }
        return fee;
        return fee;
    }
    }
@ -2187,7 +2191,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    BigDecimal price = new BigDecimal(ins.getQuantity());
                    BigDecimal price = new BigDecimal(ins.getQuantity());
                    total = total.add(quantity.multiply(price));
                    total = total.add(quantity.multiply(price));
                    Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    Double f1 = total.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    fee+=f1;
                    fee += f1;
                }
                }
            }
            }
        } catch (Exception e) {
        } catch (Exception e) {
@ -2283,7 +2287,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            outpatientDao.save(outpatientDO);
            outpatientDao.save(outpatientDO);
            result.put("code", 1);
            result.put("code", 1);
            result.put("voucherNo",voucherNo);
            result.put("voucherNo", voucherNo);
            result.put("mes", "开方提交成功");
            result.put("mes", "开方提交成功");
            return result;
            return result;
@ -2441,7 +2445,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param size
     * @param size
     * @return
     * @return
     */
     */
    public MixEnvelop findExpressageList(String status, String oneselfPickupFlg, String nameKey, String startTime, String endTime, Integer page, Integer size,String wxId) {
    public MixEnvelop findExpressageList(String status, String oneselfPickupFlg, String nameKey, String startTime, String endTime, Integer page, Integer size, String wxId) {
        String totalSql = "SELECT " +
        String totalSql = "SELECT " +
                " COUNT(1) AS total " +
                " COUNT(1) AS total " +
                " FROM " +
                " FROM " +
@ -2460,17 +2464,17 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            totalSql += " AND e.name like '%" + nameKey + "%'";
            totalSql += " AND e.name like '%" + nameKey + "%'";
        }
        }
        if (StringUtils.isNotBlank(startTime)) {
        if (StringUtils.isNotBlank(startTime)) {
            if("xm_ykyy_wx".equals(wxId)){
                totalSql +=" and e.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
            if ("xm_ykyy_wx".equals(wxId)) {
                totalSql += " and e.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                totalSql += " AND e.create_time >='" + startTime + " 00:00:00'";
                totalSql += " AND e.create_time >='" + startTime + " 00:00:00'";
            }
            }
        }
        }
        if (StringUtils.isNotBlank(endTime)) {
        if (StringUtils.isNotBlank(endTime)) {
            if("xm_ykyy_wx".equals(wxId)){
                totalSql +=" and e.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
            if ("xm_ykyy_wx".equals(wxId)) {
                totalSql += " and e.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                totalSql += " AND e.create_time <='" + endTime + " 23:59:59'";
                totalSql += " AND e.create_time <='" + endTime + " 23:59:59'";
            }
            }
@ -2479,15 +2483,15 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        Long count = 0L;
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString()) ;
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        }
        String sql = "SELECT  " ;
        if("xm_ykyy_wx".equals(wxId)){
            sql =sql+  "to_char(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
        }else{
            sql =sql+  "date_format(e.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        String sql = "SELECT  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            sql = sql + "to_char(e.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
        } else {
            sql = sql + "date_format(e.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        }
        }
        sql=sql+" e.name as \"name\", " +
        sql = sql + " e.name as \"name\", " +
                " e.oneself_pickup_flg AS \"oneselfPickupFlg\", " +
                " e.oneself_pickup_flg AS \"oneselfPickupFlg\", " +
                " o.id AS \"outpatientId\", " +
                " o.id AS \"outpatientId\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " o.icd10_name AS \"icd10Name\", " +
@ -2510,27 +2514,27 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            sql += " AND e.name like '%" + nameKey + "%'";
            sql += " AND e.name like '%" + nameKey + "%'";
        }
        }
        if (StringUtils.isNotBlank(startTime)) {
        if (StringUtils.isNotBlank(startTime)) {
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and e.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and e.create_time >= to_date('" + startTime + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND e.create_time >='" + startTime + " 00:00:00'";
                sql += " AND e.create_time >='" + startTime + " 00:00:00'";
            }
            }
        }
        }
        if (StringUtils.isNotBlank(endTime)) {
        if (StringUtils.isNotBlank(endTime)) {
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and e.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and e.create_time <= to_date('" + endTime + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND e.create_time <='" + endTime + " 23:59:59'";
                sql += " AND e.create_time <='" + endTime + " 23:59:59'";
            }
            }
        }
        }
 /*       sql += " LIMIT " + (page - 1) * size + "," + size + "";*/
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql,page,size);
        for (Map<String,Object> map:list){
            if (map.get("prescriptionId")!=null){
                List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(map.get("prescriptionId").toString(),1);
                map.put("info",wlyyPrescriptionInfoDOS);
        /*       sql += " LIMIT " + (page - 1) * size + "," + size + "";*/
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, size);
        for (Map<String, Object> map : list) {
            if (map.get("prescriptionId") != null) {
                List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(map.get("prescriptionId").toString(), 1);
                map.put("info", wlyyPrescriptionInfoDOS);
            }
            }
        }
        }
@ -2767,58 +2771,59 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 新排班号源详情
     * 新排班号源详情
     *
     * @param id
     * @param id
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findWorkTimeInfo(String id){
    public List<Map<String, Object>> findWorkTimeInfo(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        Long ss = timeDO.getEndTime().getTime()-timeDO.getStartTime().getTime();
        Long s = ss/timeDO.getSourceNumber();
        Long ss = timeDO.getEndTime().getTime() - timeDO.getStartTime().getTime();
        Long s = ss / timeDO.getSourceNumber();
        Calendar sc = Calendar.getInstance();
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());
        sc.setTime(timeDO.getStartTime());
        List<Map<String,Object>> rs = new ArrayList<>();
        List<Map<String, Object>> rs = new ArrayList<>();
        //1.根据当前时间,去取已过时间的号源
        //1.根据当前时间,去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())){
            if(new Date().before(sc.getTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
                break;
            }
            }
            //加上时间间隔
            //加上时间间隔
            Date temp =new Date();
            temp.setTime(sc.getTime().getTime()+s);
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            sc.setTime(temp);
        }
        }
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(),id);
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);
        //2.根据时间间隔拆分号源
        //2.根据时间间隔拆分号源
        while (sc.getTime().before(timeDO.getEndTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            Map<String,Object> t = new HashedMap();
            t.put("startTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> t = new HashedMap();
            t.put("startTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //加上时间间隔
            //加上时间间隔
            Date temp =new Date();
            temp.setTime(sc.getTime().getTime()+s);
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            sc.setTime(temp);
            //如果结束时间大于排班时间则不再拆分号源
            //如果结束时间大于排班时间则不再拆分号源
            if(sc.getTime().after(timeDO.getEndTime())){
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
                break;
            }
            }
            t.put("endTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //如果号源被预约了,标记为true
            //如果号源被预约了,标记为true
            Boolean registered = false;
            Boolean registered = false;
            if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
                for(WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs){
                    if(t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(),"yyyy-MM-dd HH:mm:ss"))){
            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                for (WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs) {
                    if (t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(), "yyyy-MM-dd HH:mm:ss"))) {
                        registered = true;
                        registered = true;
                    }
                    }
                }
                }
            }
            }
            t.put("registered",registered);
            t.put("registered", registered);
            rs.add(t);
            rs.add(t);
        }
        }
@ -2827,62 +2832,63 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 计算号源数目
     * 计算号源数目
     *
     * @param id
     * @param id
     * @return
     * @return
     */
     */
    public Integer findWorkTimeInfoCout(String id){
    public Integer findWorkTimeInfoCout(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        if(timeDO.getSourceNumber()==null||timeDO.getStartTime()==null||timeDO.getEndTime()==null){
        if (timeDO.getSourceNumber() == null || timeDO.getStartTime() == null || timeDO.getEndTime() == null) {
            return 0;
            return 0;
        }
        }
        Long ss = timeDO.getEndTime().getTime()-timeDO.getStartTime().getTime();
        Long s = ss/timeDO.getSourceNumber();
        Long ss = timeDO.getEndTime().getTime() - timeDO.getStartTime().getTime();
        Long s = ss / timeDO.getSourceNumber();
        Calendar sc = Calendar.getInstance();
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());
        sc.setTime(timeDO.getStartTime());
        List<Map<String,Object>> rs = new ArrayList<>();
        List<Map<String, Object>> rs = new ArrayList<>();
        //1.根据当前时间,去取已过时间的号源
        //1.根据当前时间,去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())){
            if(new Date().before(sc.getTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
                break;
            }
            }
            //加上时间间隔
            //加上时间间隔
            Date temp =new Date();
            temp.setTime(sc.getTime().getTime()+s);
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            sc.setTime(temp);
        }
        }
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(),id);
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);
        //2.根据时间间隔拆分号源
        //2.根据时间间隔拆分号源
        while (sc.getTime().before(timeDO.getEndTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            Map<String,Object> t = new HashedMap();
            t.put("startTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> t = new HashedMap();
            t.put("startTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //加上时间间隔
            //加上时间间隔
            Date temp =new Date();
            temp.setTime(sc.getTime().getTime()+s);
            Date temp = new Date();
            temp.setTime(sc.getTime().getTime() + s);
            sc.setTime(temp);
            sc.setTime(temp);
            //如果结束时间大于排班时间则不再拆分号源
            //如果结束时间大于排班时间则不再拆分号源
            if(sc.getTime().after(timeDO.getEndTime())){
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
                break;
            }
            }
            t.put("endTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //如果号源被预约了,标记为true
            //如果号源被预约了,标记为true
            Boolean registered = false;
            Boolean registered = false;
            if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
                for(WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs){
                    if(t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(),"yyyy-MM-dd HH:mm:ss"))){
            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                for (WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs) {
                    if (t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(), "yyyy-MM-dd HH:mm:ss"))) {
                        registered = true;
                        registered = true;
                    }
                    }
                }
                }
            }
            }
            if(!registered){
            if (!registered) {
                rs.add(t);
                rs.add(t);
            }
            }
        }
        }
@ -2890,95 +2896,95 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    @Deprecated
    @Deprecated
    public List<Map<String,Object>> findWorkTimeInfoOld(String id){
    public List<Map<String, Object>> findWorkTimeInfoOld(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        Calendar sc = Calendar.getInstance();
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());
        sc.setTime(timeDO.getStartTime());
        List<Map<String,Object>> rs = new ArrayList<>();
        List<Map<String, Object>> rs = new ArrayList<>();
        //1.根据当前时间,去取已过时间的号源
        //1.根据当前时间,去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())){
            if(new Date().before(sc.getTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
                break;
            }
            }
            //加上时间间隔
            //加上时间间隔
            sc.add(Calendar.MINUTE,timeDO.getTimeInterval());
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
        }
        }
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(),id);
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);
        //2.根据时间间隔拆分号源
        //2.根据时间间隔拆分号源
        while (sc.getTime().before(timeDO.getEndTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            Map<String,Object> t = new HashedMap();
            t.put("startTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> t = new HashedMap();
            t.put("startTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //加上时间间隔
            //加上时间间隔
            sc.add(Calendar.MINUTE,timeDO.getTimeInterval());
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
            //如果结束时间大于排班时间则不再拆分号源
            //如果结束时间大于排班时间则不再拆分号源
            if(sc.getTime().after(timeDO.getEndTime())){
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
                break;
            }
            }
            t.put("endTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //如果号源被预约了,标记为true
            //如果号源被预约了,标记为true
            Boolean registered = false;
            Boolean registered = false;
            if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
                for(WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs){
                    if(t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(),"yyyy-MM-dd HH:mm:ss"))){
            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                for (WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs) {
                    if (t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(), "yyyy-MM-dd HH:mm:ss"))) {
                        registered = true;
                        registered = true;
                    }
                    }
                }
                }
            }
            }
            t.put("registered",registered);
            t.put("registered", registered);
            rs.add(t);
            rs.add(t);
        }
        }
        return rs;
        return rs;
    }
    }
    public Integer findWorkTimeCount(String id){
    public Integer findWorkTimeCount(String id) {
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        WlyyDoctorWorkTimeDO timeDO = doctorWorkTimeDao.findOne(id);
        Calendar sc = Calendar.getInstance();
        Calendar sc = Calendar.getInstance();
        sc.setTime(timeDO.getStartTime());
        sc.setTime(timeDO.getStartTime());
        List<Map<String,Object>> rs = new ArrayList<>();
        List<Map<String, Object>> rs = new ArrayList<>();
        //1.根据当前时间,去取已过时间的号源
        //1.根据当前时间,去取已过时间的号源
        while (sc.getTime().before(timeDO.getEndTime())){
            if(new Date().before(sc.getTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            if (new Date().before(sc.getTime())) {
                break;
                break;
            }
            }
            //加上时间间隔
            //加上时间间隔
            sc.add(Calendar.MINUTE,timeDO.getTimeInterval());
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
        }
        }
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(),id);
        List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctorAndWorkId(timeDO.getDoctor(), id);
        //2.根据时间间隔拆分号源
        //2.根据时间间隔拆分号源
        while (sc.getTime().before(timeDO.getEndTime())){
        while (sc.getTime().before(timeDO.getEndTime())) {
            Map<String,Object> t = new HashedMap();
            t.put("startTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> t = new HashedMap();
            t.put("startTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            //加上时间间隔
            //加上时间间隔
            sc.add(Calendar.MINUTE,timeDO.getTimeInterval());
            sc.add(Calendar.MINUTE, timeDO.getTimeInterval());
            if(sc.getTime().after(timeDO.getEndTime())){
            if (sc.getTime().after(timeDO.getEndTime())) {
                break;
                break;
            }
            }
            t.put("endTime",DateUtil.dateToStr(sc.getTime(),"yyyy-MM-dd HH:mm:ss"));
            t.put("endTime", DateUtil.dateToStr(sc.getTime(), "yyyy-MM-dd HH:mm:ss"));
            if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                Boolean registered = false;
                Boolean registered = false;
                for(WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs){
                    if(t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(),"yyyy-MM-dd HH:mm:ss"))){
                for (WlyyPatientRegisterTimeDO registerTimeDO : registerTimeDOs) {
                    if (t.get("startTime").equals(DateUtil.dateToStr(registerTimeDO.getStartTime(), "yyyy-MM-dd HH:mm:ss"))) {
                        registered = true;
                        registered = true;
                    }
                    }
                }
                }
                if(!registered){
                if (!registered) {
                    rs.add(t);
                    rs.add(t);
                }
                }
            }else {
            } else {
                rs.add(t);
                rs.add(t);
            }
            }
        }
        }
@ -2986,50 +2992,50 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        return rs.size();
        return rs.size();
    }
    }
    public Map<String,Object> findDoctorInfo(String doctor,String withWork){
    public Map<String, Object> findDoctorInfo(String doctor, String withWork) {
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        Map<String,Object> rs = new HashedMap();
        if(doctorDO!=null){
            rs.put("doctor",doctor);
            rs.put("doctorSex",doctorDO.getSex());
            if(StringUtils.isNoneBlank(doctorDO.getIdcard())){
                rs.put("doctorAge",IdCardUtil.getAgeForIdcard(doctorDO.getIdcard()));
            }else{
                rs.put("doctorAge","");
            }
            rs.put("doctor",doctorDO.getName());
            rs.put("doctorMobile",doctorDO.getMobile());
            rs.put("fee",doctorDO.getFee());
            rs.put("jobTitleCode",doctorDO.getJobTitleCode());
            rs.put("jobTitleName",doctorDO.getJobTitleName());
            rs.put("chargeType",doctorDO.getChargeType());
            rs.put("photo",doctorDO.getPhoto());
            rs.put("consultStatus",doctorDO.getConsultStatus());
            rs.put("outpatientType",doctorDO.getOutpatientType());
            rs.put("expertise",doctorDO.getExpertise());
            rs.put("introduce",doctorDO.getIntroduce());
            rs.put("consultStatus",doctorDO.getConsultStatus());// 咨询在线状态
        Map<String, Object> rs = new HashedMap();
        if (doctorDO != null) {
            rs.put("doctor", doctor);
            rs.put("doctorSex", doctorDO.getSex());
            if (StringUtils.isNoneBlank(doctorDO.getIdcard())) {
                rs.put("doctorAge", IdCardUtil.getAgeForIdcard(doctorDO.getIdcard()));
            } else {
                rs.put("doctorAge", "");
            }
            rs.put("doctor", doctorDO.getName());
            rs.put("doctorMobile", doctorDO.getMobile());
            rs.put("fee", doctorDO.getFee());
            rs.put("jobTitleCode", doctorDO.getJobTitleCode());
            rs.put("jobTitleName", doctorDO.getJobTitleName());
            rs.put("chargeType", doctorDO.getChargeType());
            rs.put("photo", doctorDO.getPhoto());
            rs.put("consultStatus", doctorDO.getConsultStatus());
            rs.put("outpatientType", doctorDO.getOutpatientType());
            rs.put("expertise", doctorDO.getExpertise());
            rs.put("introduce", doctorDO.getIntroduce());
            rs.put("consultStatus", doctorDO.getConsultStatus());// 咨询在线状态
            //机构科室信息
            //机构科室信息
            List<BaseDoctorHospitalDO> hospitalDOs =  baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            if(hospitalDOs!=null&&hospitalDOs.size()>0){
                rs.put("hospital",hospitalDOs.get(0));
            List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            if (hospitalDOs != null && hospitalDOs.size() > 0) {
                rs.put("hospital", hospitalDOs.get(0));
                BaseOrgDO org = baseOrgDao.findByCode(hospitalDOs.get(0).getOrgCode());
                BaseOrgDO org = baseOrgDao.findByCode(hospitalDOs.get(0).getOrgCode());
                rs.put("winNo",org.getWinNo());
                rs.put("deptName",hospitalDOs.get(0).getDeptName());
                rs.put("dept",hospitalDOs.get(0).getDeptCode());
                rs.put("winNo", org.getWinNo());
                rs.put("deptName", hospitalDOs.get(0).getDeptName());
                rs.put("dept", hospitalDOs.get(0).getDeptCode());
                if(StringUtils.isNotBlank(withWork)&&"1".equals(withWork)){
                    List<WlyyDoctorWorkTimeVO> times = findDoctorWorkTime(doctor,hospitalDOs.get(0).getOrgCode());
                    rs.put("workTime",times);
                if (StringUtils.isNotBlank(withWork) && "1".equals(withWork)) {
                    List<WlyyDoctorWorkTimeVO> times = findDoctorWorkTime(doctor, hospitalDOs.get(0).getOrgCode());
                    rs.put("workTime", times);
                }
                }
            }else{
                rs.put("hospital",null);
                rs.put("winNo",null);
                rs.put("deptName",null);
                rs.put("dept",null);
                rs.put("workTime",null);
            } else {
                rs.put("hospital", null);
                rs.put("winNo", null);
                rs.put("deptName", null);
                rs.put("dept", null);
                rs.put("workTime", null);
            }
            }
@ -3041,27 +3047,27 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " base_doctor_role r " +
                    " base_doctor_role r " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " WHERE " +
                    " WHERE " +
                    " r.doctor_code = '"+doctor+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
                    " r.doctor_code = '" + doctor + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if(list!=null&&list.size()>0){
                rs.put("roles",list);
            }else{
                rs.put("roles",null);
            if (list != null && list.size() > 0) {
                rs.put("roles", list);
            } else {
                rs.put("roles", null);
            }
            }
            //医生预约量
            //医生预约量
            List<WlyyPatientRegisterTimeDO>  registerTimeDOs = patientRegisterTimeDao.findByDoctor(doctor);
            if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
                rs.put("registerCount",registerTimeDOs.size());
            }else{
                rs.put("registerCount",0);
            List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByDoctor(doctor);
            if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                rs.put("registerCount", registerTimeDOs.size());
            } else {
                rs.put("registerCount", 0);
            }
            }
            //医生问诊量
            //医生问诊量
            List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByDoctorList(doctor);
            List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByDoctorList(doctor);
            if(wlyyOutpatientDOs!=null&&wlyyOutpatientDOs.size()>0){
                rs.put("outpatientCount",wlyyOutpatientDOs.size());
            }else{
                rs.put("outpatientCount",0);
            if (wlyyOutpatientDOs != null && wlyyOutpatientDOs.size() > 0) {
                rs.put("outpatientCount", wlyyOutpatientDOs.size());
            } else {
                rs.put("outpatientCount", 0);
            }
            }
//
//
//            //协同门诊量
//            //协同门诊量
@ -3069,21 +3075,21 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
//            rs.put("coordinationCout",coordinationCout);
//            rs.put("coordinationCout",coordinationCout);
            //医生关注
            //医生关注
            List<BaseDoctorPatientFollowDO> doctorPatientFollowDOS = baseOrgPatientDao.findByDoctor(doctor);
            List<BaseDoctorPatientFollowDO> doctorPatientFollowDOS = baseOrgPatientDao.findByDoctor(doctor);
            if (doctorPatientFollowDOS!=null&&doctorPatientFollowDOS.size()>0){
                rs.put("attention","1");
            }else {
                rs.put("attention","0");
            if (doctorPatientFollowDOS != null && doctorPatientFollowDOS.size() > 0) {
                rs.put("attention", "1");
            } else {
                rs.put("attention", "0");
            }
            }
            //专家咨询
            //专家咨询
            String zjCountsql = "SELECT id AS \"id\" FROM wlyy_consult_team WHERE doctor='"+doctor+"' AND (type=1 OR type=15)";
            List<Map<String,Object>> zjList = jdbcTemplate.queryForList(zjCountsql);
            String zjCountsql = "SELECT id AS \"id\" FROM wlyy_consult_team WHERE doctor='" + doctor + "' AND (type=1 OR type=15)";
            List<Map<String, Object>> zjList = jdbcTemplate.queryForList(zjCountsql);
            if(zjList!=null&&zjList.size()>0){
                rs.put("zjCount",zjList.size());
            }else{
                rs.put("zjCount",0);
            if (zjList != null && zjList.size() > 0) {
                rs.put("zjCount", zjList.size());
            } else {
                rs.put("zjCount", 0);
            }
            }
            //查询医生各项评价平均分
            //查询医生各项评价平均分
@ -3093,24 +3099,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    "FROM base_evaluate a,base_evaluate_score b " +
                    "FROM base_evaluate a,base_evaluate_score b " +
                    "WHERE " +
                    "WHERE " +
                    "a.relation_code=b.id " +
                    "a.relation_code=b.id " +
                    "AND b.doctor='"+doctor+"' " +
                    "AND b.doctor='" + doctor + "' " +
                    "GROUP BY a.score_type ORDER BY  a.score_type ASC ";
                    "GROUP BY a.score_type ORDER BY  a.score_type ASC ";
            List<Map<String,Object>> listscore = jdbcTemplate.queryForList(sqlscore);
            List<Map<String, Object>> listscore = jdbcTemplate.queryForList(sqlscore);
            Double doctorScore = new Double("0");
            Double doctorScore = new Double("0");
            if(listscore!=null&&listscore.size()>0){
                for(Map<String,Object> _listscore :listscore){
            if (listscore != null && listscore.size() > 0) {
                for (Map<String, Object> _listscore : listscore) {
                    doctorScore += Double.parseDouble(_listscore.get("score").toString());
                    doctorScore += Double.parseDouble(_listscore.get("score").toString());
                }
                }
            }
            }
            doctorScore = doctorScore/3;
            rs.put("doctorScore",doctorScore);
            doctorScore = doctorScore / 3;
            rs.put("doctorScore", doctorScore);
            if(listscore!=null&&listscore.size()>0){
                rs.put("scoreDoctor",listscore);
            }else{
                rs.put("scoreDoctor",null);
            if (listscore != null && listscore.size() > 0) {
                rs.put("scoreDoctor", listscore);
            } else {
                rs.put("scoreDoctor", null);
            }
            }
            //查询评价明细
            //查询评价明细
@ -3128,91 +3134,91 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    "FROM " +
                    "FROM " +
                    "base_evaluate a " +
                    "base_evaluate a " +
                    "LEFT JOIN base_evaluate_score b ON b.id=a.relation_code " +
                    "LEFT JOIN base_evaluate_score b ON b.id=a.relation_code " +
                    "LEFT JOIN wlyy_consult_team c ON c.consult=b.relation_code AND c.doctor='"+doctor+"' " +
                    "WHERE a.relation_code=b.id AND b.doctor='"+doctor+"' ";
            List<Map<String,Object>> scoreList = jdbcTemplate.queryForList(sqlScoreList);
                    "LEFT JOIN wlyy_consult_team c ON c.consult=b.relation_code AND c.doctor='" + doctor + "' " +
                    "WHERE a.relation_code=b.id AND b.doctor='" + doctor + "' ";
            List<Map<String, Object>> scoreList = jdbcTemplate.queryForList(sqlScoreList);
            if(scoreList!=null&&scoreList.size()>0){
            if (scoreList != null && scoreList.size() > 0) {
//                Set<String> datelist = new HashSet<>();
//                Set<String> datelist = new HashSet<>();
                HashMap<String,List<Map<String,Object>>> waitinglist = new HashMap<>();
                HashMap<String, List<Map<String, Object>>> waitinglist = new HashMap<>();
                if(scoreList!=null&&scoreList.size()>0){
                    for(Map<String,Object> scorepatient :scoreList){
                        String id = (String)scorepatient.get("id");
                if (scoreList != null && scoreList.size() > 0) {
                    for (Map<String, Object> scorepatient : scoreList) {
                        String id = (String) scorepatient.get("id");
                        if(id == null){
                        if (id == null) {
                            continue;
                            continue;
                        }
                        }
                        if(waitinglist.keySet().contains(id)){
                        if (waitinglist.keySet().contains(id)) {
                            waitinglist.get(id).add(scorepatient);
                            waitinglist.get(id).add(scorepatient);
                        }else{
                            List<Map<String,Object>> _cu = new ArrayList<>();
                        } else {
                            List<Map<String, Object>> _cu = new ArrayList<>();
                            _cu.add(scorepatient);
                            _cu.add(scorepatient);
                            waitinglist.put(id,_cu);
                            waitinglist.put(id, _cu);
                        }
                        }
                    }
                    }
                }
                }
                rs.put("scoreList",waitinglist);
            }else{
                rs.put("scoreList",null);
                rs.put("scoreList", waitinglist);
            } else {
                rs.put("scoreList", null);
            }
            }
        }
        }
        return rs;
        return rs;
    }
    }
    public Map<String,Object> findDoctorBaseInfo(String doctor){
    public Map<String, Object> findDoctorBaseInfo(String doctor) {
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        Map<String,Object> rs = new HashedMap();
        if(doctorDO!=null){
            rs.put("doctor",doctor);
            rs.put("doctor",doctorDO.getName());
            rs.put("jobTitleCode",doctorDO.getJobTitleCode());
            rs.put("jobTitleName",doctorDO.getJobTitleName());
            rs.put("chargeType",doctorDO.getChargeType());
            rs.put("photo",doctorDO.getPhoto());
            rs.put("consultStatus",doctorDO.getConsultStatus());
            rs.put("outpatientType",doctorDO.getOutpatientType());
            rs.put("expertise",doctorDO.getExpertise());
            rs.put("introduce",doctorDO.getIntroduce());
            rs.put("townCode",doctorDO.getTownCode());
            rs.put("townName",doctorDO.getTownName());
            rs.put("consultStatus",doctorDO.getConsultStatus());// 咨询在线状态
        Map<String, Object> rs = new HashedMap();
        if (doctorDO != null) {
            rs.put("doctor", doctor);
            rs.put("doctor", doctorDO.getName());
            rs.put("jobTitleCode", doctorDO.getJobTitleCode());
            rs.put("jobTitleName", doctorDO.getJobTitleName());
            rs.put("chargeType", doctorDO.getChargeType());
            rs.put("photo", doctorDO.getPhoto());
            rs.put("consultStatus", doctorDO.getConsultStatus());
            rs.put("outpatientType", doctorDO.getOutpatientType());
            rs.put("expertise", doctorDO.getExpertise());
            rs.put("introduce", doctorDO.getIntroduce());
            rs.put("townCode", doctorDO.getTownCode());
            rs.put("townName", doctorDO.getTownName());
            rs.put("consultStatus", doctorDO.getConsultStatus());// 咨询在线状态
            //机构科室信息
            //机构科室信息
            List<BaseDoctorHospitalDO> hospitalDOs =  baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByDoctorCode(doctorDO.getId());
            List<BaseDoctorHospitalDO> hospitalDOList = new ArrayList<>();
            List<BaseDoctorHospitalDO> hospitalDOList = new ArrayList<>();
            for (BaseDoctorHospitalDO doctorHospitalDO:hospitalDOs){
            for (BaseDoctorHospitalDO doctorHospitalDO : hospitalDOs) {
                String orgCode = doctorHospitalDO.getOrgCode();
                String orgCode = doctorHospitalDO.getOrgCode();
                BaseOrgDO org = baseOrgDao.findByCode(orgCode);
                BaseOrgDO org = baseOrgDao.findByCode(orgCode);
                if (org!=null){
                if (org != null) {
                    doctorHospitalDO.setWinNo(org.getWinNo());
                    doctorHospitalDO.setWinNo(org.getWinNo());
                    doctorHospitalDO.setHisId(org.getHisId());
                    doctorHospitalDO.setHisId(org.getHisId());
                    hospitalDOList.add(doctorHospitalDO);
                    hospitalDOList.add(doctorHospitalDO);
                }
                }
            }
            }
            if(hospitalDOList!=null&&hospitalDOList.size()>0){
                rs.put("hospital",hospitalDOList.get(0));
            if (hospitalDOList != null && hospitalDOList.size() > 0) {
                rs.put("hospital", hospitalDOList.get(0));
                BaseOrgDO org = baseOrgDao.findByCode(hospitalDOList.get(0).getOrgCode());
                BaseOrgDO org = baseOrgDao.findByCode(hospitalDOList.get(0).getOrgCode());
                if(org!=null){
                    rs.put("winNo",org.getWinNo());
                    rs.put("deptName",hospitalDOList.get(0).getDeptName());
                    rs.put("deptCode",hospitalDOList.get(0).getDeptCode());
                if (org != null) {
                    rs.put("winNo", org.getWinNo());
                    rs.put("deptName", hospitalDOList.get(0).getDeptName());
                    rs.put("deptCode", hospitalDOList.get(0).getDeptCode());
                }
                }
            }else{
                rs.put("hospital",null);
                rs.put("winNo",null);
                rs.put("deptName",null);
                rs.put("deptCode",null);
            } else {
                rs.put("hospital", null);
                rs.put("winNo", null);
                rs.put("deptName", null);
                rs.put("deptCode", null);
            }
            }
            //多科室兼容
            //多科室兼容
            rs.put("hospitalList",hospitalDOList);
            rs.put("hospitalList", hospitalDOList);
            //医生角色
            //医生角色
@ -3223,20 +3229,20 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " base_doctor_role r " +
                    " base_doctor_role r " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " JOIN base_doctor_role_dict t ON t.code = r.role_code " +
                    " WHERE " +
                    " WHERE " +
                    " r.doctor_code = '"+doctor+"'";
                    " r.doctor_code = '" + doctor + "'";
            logger.info(sql);
            logger.info(sql);
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if(list!=null&&list.size()>0){
                rs.put("roles",list);
            }else{
                rs.put("roles",null);
            if (list != null && list.size() > 0) {
                rs.put("roles", list);
            } else {
                rs.put("roles", null);
            }
            }
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue");
            WlyyHospitalSysDictDO wlyyHospitalSysDictDO = wlyyHospitalSysDictDao.findById("pwOverDue");
            if (wlyyHospitalSysDictDO.getPyCode().equalsIgnoreCase("open")){
            if (wlyyHospitalSysDictDO.getPyCode().equalsIgnoreCase("open")) {
                //密码过期
                //密码过期
                rs.put("authPw",baseDoctorService.findDoctorPwlimitDate(doctor));
                rs.put("authPw", baseDoctorService.findDoctorPwlimitDate(doctor));
            }
            }
        }
        }
@ -3246,25 +3252,26 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 居民取消复诊或者医生拒绝接诊
     * 居民取消复诊或者医生拒绝接诊
     *
     * @param outPatientId
     * @param outPatientId
     * @param cancelType
     * @param cancelType
     * @param cancelValue
     * @param cancelValue
     * @param cancelRemark
     * @param cancelRemark
     * @param operator 1居民 2医生
     * @param operator     1居民 2医生
     * @return
     * @return
     */
     */
    public Map<String,Object> cancelOutPatient(String outPatientId,String cancelType,String cancelValue,String cancelRemark,Integer operator,String wxId) {
    public Map<String, Object> cancelOutPatient(String outPatientId, String cancelType, String cancelValue, String cancelRemark, Integer operator, String wxId) {
        Map<String,Object> rs = new HashedMap();
        Map<String, Object> rs = new HashedMap();
        //判断医生是否接诊
        //判断医生是否接诊
        List<WlyyHospitalWaitingRoomDO> roomDOs =hospitalWaitingRoomDao.findByOutpatientId(outPatientId);
        if(roomDOs!=null&&roomDOs.size()>0){
            for(WlyyHospitalWaitingRoomDO roomDO:roomDOs){
                if(roomDO.getVisitStatus()==2){
                    rs.put("code",-1);
                    rs.put("mes","医生已经接诊,无法取消");
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outPatientId);
        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO roomDO : roomDOs) {
                if (roomDO.getVisitStatus() == 2) {
                    rs.put("code", -1);
                    rs.put("mes", "医生已经接诊,无法取消");
                    return rs;
                    return rs;
                }else{
                } else {
                    roomDO.setVisitStatus(-1);
                    roomDO.setVisitStatus(-1);
                    hospitalWaitingRoomDao.save(roomDO);
                    hospitalWaitingRoomDao.save(roomDO);
                }
                }
@ -3275,13 +3282,13 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outPatientId);
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findOne(outPatientId);
        wlyyOutpatientDO.setStatus("-1");
        wlyyOutpatientDO.setStatus("-1");
        String description = null;
        String description = null;
        if (1 == operator){
        if (1 == operator) {
            //居民取消
            //居民取消
            wlyyOutpatientDO.setPatientCancelRemark(cancelRemark);
            wlyyOutpatientDO.setPatientCancelRemark(cancelRemark);
            wlyyOutpatientDO.setPatientCancelType(cancelType);
            wlyyOutpatientDO.setPatientCancelType(cancelType);
            wlyyOutpatientDO.setPatientCancelValue(cancelValue);
            wlyyOutpatientDO.setPatientCancelValue(cancelValue);
            description = "居民取消";
            description = "居民取消";
        }else{
        } else {
            //医生拒绝接诊
            //医生拒绝接诊
            wlyyOutpatientDO.setDoctorCancelRemark(cancelRemark);
            wlyyOutpatientDO.setDoctorCancelRemark(cancelRemark);
            wlyyOutpatientDO.setDoctorCancelType(cancelType);
            wlyyOutpatientDO.setDoctorCancelType(cancelType);
@ -3301,22 +3308,22 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            try {
            try {
                data.put("name",wlyyOutpatientDO.getPatientName());
                data.put("age",IdCardUtil.getAgeForIdcard(wlyyOutpatientDO.getIdcard()));
                data.put("gender",IdCardUtil.getSexForIdcard(wlyyOutpatientDO.getIdcard()));
                data.put("question",wlyyOutpatientDO.getIcd10Name());
                String msg="";
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    data.put("type","9");
                    msg+=wlyyOutpatientDO.getPatientName()+",您好! 您有一个图文复诊已被医生取消,取消原因:"+cancelValue+"。取消说明:"+cancelRemark+"。";
                    sendWxTemplateMsg(wechatId,wlyyOutpatientDO,"9");
                data.put("name", wlyyOutpatientDO.getPatientName());
                data.put("age", IdCardUtil.getAgeForIdcard(wlyyOutpatientDO.getIdcard()));
                data.put("gender", IdCardUtil.getSexForIdcard(wlyyOutpatientDO.getIdcard()));
                data.put("question", wlyyOutpatientDO.getIcd10Name());
                String msg = "";
                if ("1".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                    data.put("type", "9");
                    msg += wlyyOutpatientDO.getPatientName() + ",您好! 您有一个图文复诊已被医生取消,取消原因:" + cancelValue + "。取消说明:" + cancelRemark + "。";
                    sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(), "9", "doctorRefuse", null);
                }
                }
                if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())){
                    data.put("type","16");
                    msg+=wlyyOutpatientDO.getPatientName()+",您好! 您有一个视频复诊已被医生取消,取消原因:"+cancelValue+"。取消说明:"+cancelRemark+"。";
                    sendWxTemplateMsg(wechatId,wlyyOutpatientDO,"16");
                if ("2".equalsIgnoreCase(wlyyOutpatientDO.getType())) {
                    data.put("type", "16");
                    msg += wlyyOutpatientDO.getPatientName() + ",您好! 您有一个视频复诊已被医生取消,取消原因:" + cancelValue + "。取消说明:" + cancelRemark + "。";
                    sendWxTemplateMsg(wechatId, wlyyOutpatientDO.getId(), "16", "doctorRefuse", null);
                }
                }
                data.put("msg",msg);
                data.put("msg", msg);
                messageDO.setData(data.toString());
                messageDO.setData(data.toString());
                systemMessageService.saveMessage(messageDO);
                systemMessageService.saveMessage(messageDO);
            } catch (Exception e) {
            } catch (Exception e) {
@ -3324,8 +3331,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            }
            }
            //推送消息到眼科通
            //推送消息到眼科通
            BasePatientDO patient = basePatientDao.findById(wlyyOutpatientDO.getPatient());
            BasePatientDO patient = basePatientDao.findById(wlyyOutpatientDO.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                ykyyService.pushNotificationToYktPatient(patient.getYktId(),messageDO.getTitle(),data.get("msg").toString());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), messageDO.getTitle(), data.get("msg").toString());
            }
            }
        }
        }
@ -3334,72 +3341,209 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //删除门诊号源
        //删除门诊号源
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        if(list!=null&&list.size()>0){
        if (list != null && list.size() > 0) {
            patientRegisterTimeDao.delete(list);
            patientRegisterTimeDao.delete(list);
        }
        }
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outPatientId);
        BusinessOrderDO businessOrderDO = businessOrderDao.selectByRelationCode(outPatientId);
        try {
        try {
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
                businessOrderService.orderRefund(wxId,wlyyOutpatientDO.getPatient(),businessOrderDO.getOrderNo(),businessOrderDO.getPayPrice(),description);
            }else if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                businessOrderService.ylzOrderRefund(wxId,wlyyOutpatientDO.getPatient(),businessOrderDO.getOrderNo(),businessOrderDO.getPayPrice(),description);
            if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                businessOrderService.orderRefund(wxId, wlyyOutpatientDO.getPatient(), businessOrderDO.getOrderNo(), businessOrderDO.getPayPrice(), description);
            } else if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                businessOrderService.ylzOrderRefund(wxId, wlyyOutpatientDO.getPatient(), businessOrderDO.getOrderNo(), businessOrderDO.getPayPrice(), description);
            }
            }
        } catch (Exception e) {
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        }
        rs.put("code",1);
        rs.put("mes","取消成功");
        return  rs;
        rs.put("code", 1);
        rs.put("mes", "取消成功");
        return rs;
    }
    }
    /**
    /**
     * 发送微信模板消息  本地无法测试消息是否发送成功
     * 发送微信模板消息  本地无法测试消息是否发送成功
     * @param wxId
     * @param wxId
     * @param outpatientDO
     * @param outpatientId
     * @param type
     * @param type
     * @param titelType
     * @param remindMsg
     */
     */
    public void sendWxTemplateMsg(String wxId,WlyyOutpatientDO outpatientDO,String type){
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
        String typeMsg="";
        String first="";
        if ("9".equals(type)){
            typeMsg="通知内容:您的图文复诊订单已被医生取消,您可重新发起。由于订单取消将不做扣费处理";
            first=outpatientDO.getPatientName() + ",您好!您的图文复诊已取消";
        }
        if ("16".equals(type)){
            typeMsg="通知内容:您的视频复诊订单已被医生取消,您可重新发起。由于订单取消将不做扣费处理";
            first=outpatientDO.getPatientName() + ",您好!您的视频复诊已取消";
        }
    public void sendWxTemplateMsg(String wxId, String outpatientId, String type, String titelType, String remindMsg) {
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
        WlyyOutpatientDO outpatientDO = outpatientDao.findById(outpatientId);
        BaseDoctorDO doctorDO = baseDoctorDao.findById(outpatientDO.getDoctor());
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        String contentMsg = "";
        String first = "";
        String remark = "";
        if ("doctorRefuseRemind".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "通知内容:您的图文复诊订单已被医生取消,您可重新发起。由于订单取消将不做扣费处理";
                first = outpatientDO.getPatientName() + ",您好!您的图文复诊已取消";
            }
            if ("16".equals(type)) {
                contentMsg = "通知内容:您的视频复诊订单已被医生取消,您可重新发起。由于订单取消将不做扣费处理";
                first = outpatientDO.getPatientName() + ",您好!您的视频复诊已取消";
            }
        } else if ("payRemind".equalsIgnoreCase(titelType)) {
            if ("9".equals(type)) {
                contentMsg = "通知内容:您有一个图文复诊订单待支付,点击完成支付,如您已支付请忽略本条信息";
                first = outpatientDO.getPatientName() + ",您好!您有一个图文复诊订单待支付,请及时支付。";
            } else if ("16".equals(type)) {
                contentMsg = "通知内容:您有一个视频复诊订单待支付,点击完成支付,如您已支付请忽略本条信息";
                first = outpatientDO.getPatientName() + ",您好!您有一个视频复诊订单待支付,请及时支付。";
            } else if ("1".equals(type)) {
                contentMsg = "通知内容:您有一个图文咨询订单待支付,点击完成支付,如您已支付请忽略本条信息";
                first = outpatientDO.getPatientName() + ",您好!您有一个图文咨询订单待支付,请及时支付。";
            } else if ("17".equals(type)) {
                contentMsg = "通知内容:您有一个视频咨询订单待支付,点击完成支付,如您已支付请忽略本条信息";
                first = outpatientDO.getPatientName() + ",您好!您有一个视频咨询订单待支付,请及时支付。";
            }
        } else if ("prescriptionPayRemind".equalsIgnoreCase(titelType)) {
            first = outpatientDO.getPatientName() + ",您好! 医生已为您开具处方,请及时支付。";
            contentMsg = "通知内容:医生已为您开具处方,请及时支付。";
            remark = "备注:点击完成支付,如您已支付请忽略本条信息";
        } else if ("msgRemind".equalsIgnoreCase(titelType)) {
            first = outpatientDO.getPatientName() + ",您好!";
            contentMsg = "通知内容:" + remindMsg;
            remark = "备注:请您尽快回复";
        } else if ("outpatientMsgRemind".equalsIgnoreCase(titelType)) {
            first = doctorDO.getName() + doctorDO.getJobTitleName() + "医生已向您发起视频通话邀请,请点击详情进入视频诊室。";
            if ("16".equals(type)) {
                contentMsg = "通知内容:您的视频复诊已开始,错过将重新排队";
                remark = "备注:点击消息进入视频诊室接听视频通话,开始视频咨询。";
            } else if ("17".equals(type)) {
                contentMsg = "通知内容:您的视频咨询已开始,错过将重新排队";
                remark = "备注:点击消息进入视频诊室接听视频通话,开始视频复诊。";
            }
        } else if ("videoOrderRemind".equalsIgnoreCase(titelType)) {
            if ("16".equals(type)) {
                first = "您的视频复诊已预约成功。";
                contentMsg = "通知内容:预计" + outpatientDO.getDoctorName() + "医生将于" + outpatientDO.getRegisterDate() + " 与您进行视频复诊。请留意微信公众号消息。";
            } else if ("17".equals(type)) {
                first = "您的视频咨询已预约成功。";
                contentMsg = "通知内容:预计" + outpatientDO.getDoctorName() + "医生将于" + outpatientDO.getRegisterDate() + " 与您进行视频咨询。请留意微信公众号消息。";
            }
            remark = "备注:咨询开始时,医生将邀请您进行视频通话,请您关注消息提醒,及时接受医生视频邀请。";
        } else if ("evaluateRemind".equalsIgnoreCase(titelType)) {
            first = outpatientDO.getPatientName() + ",您好!您有1条专家咨询已结束,请及时对咨询医生进行评价。";
            contentMsg = "通知内容:请对" + outpatientDO.getDoctorName() + "医生的服务进行评价";
        }
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wxId, outpatientDO.getPatient());
            List<BasePatientWechatDo> ps = basePatientWechatDao.findByWechatIdAndPatientId(wxId, outpatientDO.getPatient());
            if(ps.isEmpty()){
                logger.info("该用户"+outpatientDO.getPatientName()+"没有openid,无法推送模版消息,用户ID:"+outpatientDO.getPatient()+"wechatId:"+wxId);
            if (ps.isEmpty()) {
                logger.info("该用户" + outpatientDO.getPatientName() + "没有openid,无法推送模版消息,用户ID:" + outpatientDO.getPatient() + "wechatId:" + wxId);
                return;
                return;
            }
            }
            ps.stream().forEach(one->{
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId,"template_doctor_notice","ysqxjz",1);
                WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
                BeanUtils.copyProperties(config,newConfig);
                newConfig.setFirst(config.getFirst().replace("key1",outpatientDO.getPatientName()));
                if ("9".equals(type)){
                    newConfig.setFirst(newConfig.getFirst().replace("key2","图文复诊"));
            String scene = "";
            WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
            if ("doctorRefuseRemind".equalsIgnoreCase(titelType)) {
                scene = "ysqxjz";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_doctor_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getPatientName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                }
                }
                if ("16".equals(type)){
                    newConfig.setFirst(newConfig.getFirst().replace("key2","视频复诊"));
                newConfig.setKeyword1(config.getKeyword1() + outpatientDO.getHospitalName());
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getDoctorName());
                newConfig.setKeyword3(config.getKeyword3() + doctorDO.getFee());
            } else if ("payRemind".equalsIgnoreCase(titelType)) {
                scene = "zxzfts";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_pay_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getPatientName()));
                if ("9".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文复诊"));
                    newConfig.setKeyword1(config.getKeyword1() + "图文复诊支付");
                } else if ("16".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频复诊"));
                    newConfig.setKeyword1(config.getKeyword1() + "视频复诊支付");
                } else if ("1".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "图文咨询"));
                    newConfig.setKeyword1(config.getKeyword1() + "图文咨询支付");
                } else if ("17".equals(type)) {
                    newConfig.setFirst(newConfig.getFirst().replace("key2", "视频咨询"));
                    newConfig.setKeyword1(config.getKeyword1() + "视频咨询支付");
                }
                }
                newConfig.setUrl(config.getUrl()+""+outpatientDO.getId());
                newConfig.setKeyword1(config.getKeyword1()+outpatientDO.getHospitalName());
                newConfig.setKeyword2(config.getKeyword2()+outpatientDO.getDoctorName());
                newConfig.setKeyword3(config.getKeyword3()+doctorDO.getFee());
                WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
                logger.info("=======setUrl========"+newConfig.getUrl());
                weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(),one.getOpenid(),newConfig);
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getHospitalName());
                newConfig.setKeyword3(config.getKeyword3() + outpatientDO.getDoctorName());
            } else if ("prescriptionPayRemind".equalsIgnoreCase(titelType)) {
                scene = "cfzfts";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_prescription_pay_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getPatientName()));
                newConfig.setKeyword1(config.getKeyword1() + "处方支付");
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getHospitalName());
                newConfig.setKeyword3(config.getKeyword3() + outpatientDO.getDoctorName());
            } else if ("msgRemind".equalsIgnoreCase(titelType)) {
                scene = "zxxxtx";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_msg_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getPatientName()));
                newConfig.setKeyword1(config.getKeyword1() + remindMsg);
                newConfig.setKeyword2(config.getKeyword2() + DateUtil.getStringDate());
            } else if ("outpatientMsgRemind".equalsIgnoreCase(titelType)) {
                scene = "mzxxtx";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_outpatient_msg_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replace("key1", outpatientDO.getPatientName()));
                newConfig.setFirst(config.getFirst().replace("key2", doctorDO.getJobTitleName()));
                newConfig.setKeyword1(config.getKeyword1() + outpatientDO.getDoctorName());
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getAdmDate());
                newConfig.setKeyword3(config.getKeyword3() + outpatientDO.getDeptName());
                newConfig.setKeyword4(config.getKeyword4() + outpatientDO.getIcd10Name());
                if ("16".equals(type)) {
                    newConfig.setRemark(config.getRemark().replaceFirst("key1", "视频复诊"));
                } else if ("17".equals(type)) {
                    newConfig.setRemark(config.getRemark().replaceFirst("key1", "视频咨询"));
                }
            } else if ("videoOrderRemind".equalsIgnoreCase(titelType)) {
                scene = "spwzyytx";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_video_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                if ("16".equals(type)) {
                    newConfig.setFirst(config.getFirst().replaceFirst("key1", "视频复诊"));
                } else if ("17".equals(type)) {
                    newConfig.setFirst(config.getFirst().replaceFirst("key1", "视频咨询"));
                }
                newConfig.setKeyword1(config.getKeyword1() + outpatientDO.getPatientName());
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getDeptName());
                newConfig.setKeyword3(config.getKeyword3() + outpatientDO.getDoctorName());
                newConfig.setKeyword4(config.getKeyword4() + outpatientDO.getRegisterDate());
                newConfig.setKeyword5(config.getKeyword5() + generalDoctorWaitingNumber(doctorDO.getId(), wxId, outpatientId));
            } else if ("evaluateRemind".equalsIgnoreCase(titelType)) {
                scene = "fwqjtx";
                WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_evaluate_notice", scene, 1);
                BeanUtils.copyProperties(config, newConfig);
                newConfig.setFirst(config.getFirst().replaceFirst("key1", outpatientDO.getPatientName()));
                newConfig.setKeyword1(config.getKeyword1() + outpatientDO.getHospitalName());
                newConfig.setKeyword2(config.getKeyword2() + outpatientDO.getDoctorName());
            }
            //发起微信消息模板推送
            newConfig.setUrl(newConfig.getUrl() + "" + outpatientDO.getId());
            logger.info("=======setUrl========" + newConfig.getUrl());
            WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
            for (BasePatientWechatDo one : ps) {
                weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newConfig);
                //保存发送模板记录,
                //保存发送模板记录,
                WxPushLogDO wxPushLogDO = new WxPushLogDO();
                WxPushLogDO wxPushLogDO = new WxPushLogDO();
                wxPushLogDO.setCreateTime(new Date());
                wxPushLogDO.setCreateTime(new Date());
@ -3407,49 +3551,54 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                wxPushLogDO.setReceiver(outpatientDO.getPatient());
                wxPushLogDO.setReceiver(outpatientDO.getPatient());
                wxPushLogDO.setWechatId(wechatId);
                wxPushLogDO.setWechatId(wechatId);
                wxPushLogDO.setReceiverName(outpatientDO.getPatientName());
                wxPushLogDO.setReceiverName(outpatientDO.getPatientName());
                wxPushLogDO.setScene("ysqxjz");
                wxPushLogDO.setScene(scene);
                wxPushLogDao.save(wxPushLogDO);
                wxPushLogDao.save(wxPushLogDO);
            }
        } else if ("xm_xzzx_wx".equalsIgnoreCase(wxId)) {
            String MsgUrl = "https://www.xmheart.com/ims-wx/index.html#/returnVisit/record?outpatientId=" + outpatientDO.getPatient();
            });
        }else if("xm_xzzx_wx".equalsIgnoreCase(wxId)) {
            String MsgUrl="https://www.xmheart.com/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientDO.getPatient();
            String responseMsg = xzzxEntranceService.sendXCXMes(wxId,
            String responseMsg = xzzxEntranceService.sendXCXMes(wxId,
                    doctorDO.getId(),
                    doctorDO.getIdcard(),
                    patientDO.getId(),
                    patientDO.getIdcard(),
                    first,
                    first,
                    "通知时间:" + DateUtil.getStringDate(),
                    typeMsg,
                    contentMsg,
                    remark,
                    MsgUrl,
                    MsgUrl,
                    "wx53f6bb4ac081d840");
                    "wx53f6bb4ac081d840");
            logger.info("XZZX_Msg="+responseMsg);
        }else if ("xm_zsyy_wx".equalsIgnoreCase(wxId)){
            String MsgUrl="https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId="+outpatientDO.getPatient();
            String responseMsg = entranceService.ehospitalNotice(doctorDO.getName(),
                    doctorDO.getIdcard(),
                    doctorDO.getMobile(),
            logger.info("XZZX_Msg_" + titelType + "=" + responseMsg);
        } else if ("xm_zsyy_wx".equalsIgnoreCase(wxId)) {
            String MsgUrl = "https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/record?outpatientId=" + outpatientDO.getPatient();
            String responseMsg = entranceService.ehospitalNotice(patientDO.getName(),
                    patientDO.getIdcard(),
                    patientDO.getMobile(),
                    first,
                    first,
                    MsgUrl,
                    MsgUrl,
                    "通知时间:" + DateUtil.getStringDate(),
                    typeMsg
                    contentMsg,
                    remark
            );
            );
            logger.info("ZSYY_Msg="+responseMsg);
            logger.info("ZSYY_Msg" + titelType + "=" + responseMsg);
        }
        }
    }
    }
    public List<WlyyHospitalSysDictDO> findCancelReasonList(){
    public List<WlyyHospitalSysDictDO> findCancelReasonList() {
        return sysDictDao.findByDictName("PatientCancel");
        return sysDictDao.findByDictName("PatientCancel");
    }
    }
    /**
    /**
     * 獲取快速咨詢時間
     * 獲取快速咨詢時間
     *
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findFastRegisterDate(){
    public List<Map<String, Object>> findFastRegisterDate() {
        int days = 7;
        int days = 7;
        String AMStartTime ="8:00";
        String AMEndTime ="12:00";
        String PMStartTime ="14:00";
        String PMEndTime ="17:00";
        String AMStartTime = "8:00";
        String AMEndTime = "12:00";
        String PMStartTime = "14:00";
        String PMEndTime = "17:00";
        //设置上午过号时间
        //设置上午过号时间
        Calendar scTime = Calendar.getInstance();
        Calendar scTime = Calendar.getInstance();
@ -3458,45 +3607,45 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        Calendar ecTime = Calendar.getInstance();
        Calendar ecTime = Calendar.getInstance();
        ecTime.setTime(new Date());
        ecTime.setTime(new Date());
        List<Map<String,Object>> times = new ArrayList<>();
        for(int i=0;i<days;i++){
        List<Map<String, Object>> times = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            //設置上午時段
            //設置上午時段
            Map<String,Object> time = new HashedMap();
            time.put("timeType","1");
            time.put("date",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd"));
            time.put("weekDay",scTime.get(Calendar.DAY_OF_WEEK));
            Map<String, Object> time = new HashedMap();
            time.put("timeType", "1");
            time.put("date", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd"));
            time.put("weekDay", scTime.get(Calendar.DAY_OF_WEEK));
            String ts[] = AMStartTime.split(":");
            String ts[] = AMStartTime.split(":");
            scTime.set(scTime.get(Calendar.YEAR),scTime.get(Calendar.MONTH),scTime.get(Calendar.DAY_OF_MONTH),Integer.parseInt(ts[0]),Integer.parseInt(ts[1]),00);
            time.put("startTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
            scTime.set(scTime.get(Calendar.YEAR), scTime.get(Calendar.MONTH), scTime.get(Calendar.DAY_OF_MONTH), Integer.parseInt(ts[0]), Integer.parseInt(ts[1]), 00);
            time.put("startTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
            String ts2[] = AMEndTime.split(":");
            String ts2[] = AMEndTime.split(":");
            scTime.set(scTime.get(Calendar.YEAR),scTime.get(Calendar.MONTH),scTime.get(Calendar.DAY_OF_MONTH),Integer.parseInt(ts2[0]),Integer.parseInt(ts2[1]),00);
            time.put("endTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
            scTime.set(scTime.get(Calendar.YEAR), scTime.get(Calendar.MONTH), scTime.get(Calendar.DAY_OF_MONTH), Integer.parseInt(ts2[0]), Integer.parseInt(ts2[1]), 00);
            time.put("endTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
            times.add(time);
            times.add(time);
            //設置下午時段
            //設置下午時段
            Map<String,Object> time2 = new HashedMap();
            time2.put("timeType","2");
            time2.put("date",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd"));
            time2.put("weekDay",scTime.get(Calendar.DAY_OF_WEEK));
            Map<String, Object> time2 = new HashedMap();
            time2.put("timeType", "2");
            time2.put("date", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd"));
            time2.put("weekDay", scTime.get(Calendar.DAY_OF_WEEK));
            String pts[] = PMStartTime.split(":");
            String pts[] = PMStartTime.split(":");
            scTime.set(scTime.get(Calendar.YEAR),scTime.get(Calendar.MONTH),scTime.get(Calendar.DAY_OF_MONTH),Integer.parseInt(pts[0]),Integer.parseInt(pts[1]),00);
            time2.put("startTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
            scTime.set(scTime.get(Calendar.YEAR), scTime.get(Calendar.MONTH), scTime.get(Calendar.DAY_OF_MONTH), Integer.parseInt(pts[0]), Integer.parseInt(pts[1]), 00);
            time2.put("startTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
            String pts2[] = PMEndTime.split(":");
            String pts2[] = PMEndTime.split(":");
            scTime.set(scTime.get(Calendar.YEAR),scTime.get(Calendar.MONTH),scTime.get(Calendar.DAY_OF_MONTH),Integer.parseInt(pts2[0]),Integer.parseInt(pts2[1]),00);
            time2.put("endTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
            scTime.set(scTime.get(Calendar.YEAR), scTime.get(Calendar.MONTH), scTime.get(Calendar.DAY_OF_MONTH), Integer.parseInt(pts2[0]), Integer.parseInt(pts2[1]), 00);
            time2.put("endTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
            times.add(time2);
            times.add(time2);
            //生成下一天
            //生成下一天
            scTime.add(Calendar.DAY_OF_MONTH,1);
            scTime.add(Calendar.DAY_OF_MONTH, 1);
        }
        }
        if(DateUtil.strToDate(DateUtil.getTimeShort(),DateUtil.HH_MM).after(DateUtil.strToDate(AMEndTime,DateUtil.HH_MM))) {
        if (DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM).after(DateUtil.strToDate(AMEndTime, DateUtil.HH_MM))) {
            times.remove(0);
            times.remove(0);
        }
        }
        if(DateUtil.strToDate(DateUtil.getTimeShort(),DateUtil.HH_MM).after(DateUtil.strToDate(PMEndTime,DateUtil.HH_MM))) {
        if (DateUtil.strToDate(DateUtil.getTimeShort(), DateUtil.HH_MM).after(DateUtil.strToDate(PMEndTime, DateUtil.HH_MM))) {
            times.remove(0);
            times.remove(0);
        }
        }
        return times;
        return times;
@ -3504,15 +3653,16 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 医生可接单列表(图文复诊、视频复诊、协同门诊)
     * 医生可接单列表(图文复诊、视频复诊、协同门诊)
     *
     * @param doctor
     * @param doctor
     * @param type 1:图文诊室,2:视频诊室(视频复诊、协同门诊)
     * @param type   1:图文诊室,2:视频诊室(视频复诊、协同门诊)
     * @return
     * @query_status 0:图文复诊候诊 1:图文复诊抢单列表
     * @query_status 0:图文复诊候诊 1:图文复诊抢单列表
     * @dept 部门
     * @dept 部门
     * @return
     */
     */
    public List<Map<String,Object>> findWaitingRoomOutpatientByDoctor(String doctor, Integer type,Integer query_status,String dept) {
    public List<Map<String, Object>> findWaitingRoomOutpatientByDoctor(String doctor, Integer type, Integer query_status, String dept) {
        String sql ="SELECT " +
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "room.patient_name AS \"name\"," +
@ -3521,11 +3671,11 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "patient.photo AS \"photo\"," +
                "patient.photo AS \"photo\"," +
                "outpatient.mobile AS \"mobile\"," +
                "outpatient.mobile AS \"mobile\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.birthday AS \"birthday\"," +
                "room.consult_type AS \"consult_type\"," ;
        if("xm_ykyy_wx".equals(wechatId)){
            sql += "to_char(room.reservation_time ,'yyyy-MM-dd hh24:mi:ss' ) AS \"timedate_format\"," ;
        }else{
            sql +=  "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS timedate_format," ;
                "room.consult_type AS \"consult_type\",";
        if ("xm_ykyy_wx".equals(wechatId)) {
            sql += "to_char(room.reservation_time ,'yyyy-MM-dd hh24:mi:ss' ) AS \"timedate_format\",";
        } else {
            sql += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS timedate_format,";
        }
        }
        sql += "outpatient.disease_img AS \"disease_img\"," +
        sql += "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.description AS \"description\"," +
@ -3541,48 +3691,47 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.status = 0 ";
                "AND outpatient.status = 0 ";
        //视频复诊,协同门诊 医生抢单
        //视频复诊,协同门诊 医生抢单
        if(type == 2 ){
            sql +=  "AND room.doctor IS NULL ";
        }else{
        if (type == 2) {
            sql += "AND room.doctor IS NULL ";
        } else {
            //图文复诊候诊列表
            //图文复诊候诊列表
            if(0 == query_status){
                sql +=  "AND room.doctor='"+doctor+"' ";
            }else{
            if (0 == query_status) {
                sql += "AND room.doctor='" + doctor + "' ";
            } else {
                //图文复诊医生抢单列表
                //图文复诊医生抢单列表
                sql +=  "AND room.doctor IS NULL  ";
                sql += "AND room.doctor IS NULL  ";
            }
            }
        }
        }
        //协同门诊
        //协同门诊
        if(3 == type){
        if (3 == type) {
            sql += " AND room.reservation_type=2 ";
            sql += " AND room.reservation_type=2 ";
        }else{
        } else {
            //在线复诊
            //在线复诊
            sql += " AND room.reservation_type=1 AND room.consult_type="+type ;
            sql += " AND room.reservation_type=1 AND room.consult_type=" + type;
        }
        }
        if(StringUtils.isNoneBlank(dept)){
            sql += " AND outpatient.dept='"+dept+"' ";
        if (StringUtils.isNoneBlank(dept)) {
            sql += " AND outpatient.dept='" + dept + "' ";
        }
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            for(Map<String,Object> outpatient :list){
                String idcard = (String)outpatient.get("idcard");
                outpatient.put("age",DateUtil.getAgeForIdcard(idcard));
            for (Map<String, Object> outpatient : list) {
                String idcard = (String) outpatient.get("idcard");
                outpatient.put("age", DateUtil.getAgeForIdcard(idcard));
            }
            }
        }
        }
        return list;
        return list;
    }
    }
    public List<Map<String,Object>> findWaitingRoomPatient(String dept, Integer type) {
    public List<Map<String, Object>> findWaitingRoomPatient(String dept, Integer type) {
        String sql ="SELECT " +
        String sql = "SELECT " +
                "patient.id AS \"id\"," +
                "patient.id AS \"id\"," +
                "patient.name AS \"name\"," +
                "patient.name AS \"name\"," +
                "patient.sex AS \"sex\"," +
                "patient.sex AS \"sex\"," +
@ -3596,27 +3745,27 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "base_patient patient " +
                "base_patient patient " +
                "WHERE waitingroom.consult_type=2 AND doctor IS NOT NULL ";
                "WHERE waitingroom.consult_type=2 AND doctor IS NOT NULL ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            for(Map<String,Object> roompatient :list){
                String idcard = (String)roompatient.get("idcard");
                roompatient.put("age",DateUtil.getAgeForIdcard(idcard));
            for (Map<String, Object> roompatient : list) {
                String idcard = (String) roompatient.get("idcard");
                roompatient.put("age", DateUtil.getAgeForIdcard(idcard));
            }
            }
        }
        }
        return list;
        return list;
    }
    }
    public JSONObject findWaitingRoomStatusCount(String dept,String wxId) {
    public JSONObject findWaitingRoomStatusCount(String dept, String wxId) {
        String totalSql = "SELECT count(id) AS \"total\" FROM wlyy_hospital_waiting_room WHERE visit_status=1 ";
        String totalSql = "SELECT count(id) AS \"total\" FROM wlyy_hospital_waiting_room WHERE visit_status=1 ";
        if("xm_ykyy_wx".equals(wxId)){
            totalSql +=" and reservation_time >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            totalSql +=" and reservation_time <= to_date('"+DateUtil.dateToStrShort(new Date())+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
        }else {
            totalSql += " AND reservation_time >='"+DateUtil.dateToStrShort(new Date())+" 00:00:00'";
            totalSql += " AND reservation_time <='"+DateUtil.dateToStrShort(new Date())+" 23:59:59'";
        if ("xm_ykyy_wx".equals(wxId)) {
            totalSql += " and reservation_time >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            totalSql += " and reservation_time <= to_date('" + DateUtil.dateToStrShort(new Date()) + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
        } else {
            totalSql += " AND reservation_time >='" + DateUtil.dateToStrShort(new Date()) + " 00:00:00'";
            totalSql += " AND reservation_time <='" + DateUtil.dateToStrShort(new Date()) + " 23:59:59'";
        }
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        Long count = 0L;
@ -3625,100 +3774,100 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        }
        }
        JSONObject result = new JSONObject();
        JSONObject result = new JSONObject();
        result.put("waiting_count",count);
        result.put("outpatient_count",count);
        result.put("waiting_count_difference",count);
        result.put("outpatient_count_difference",count);
        result.put("yesterday_waiting_count",count);
        result.put("waiting_count", count);
        result.put("outpatient_count", count);
        result.put("waiting_count_difference", count);
        result.put("outpatient_count_difference", count);
        result.put("yesterday_waiting_count", count);
        return result;
        return result;
    }
    }
    public List<JSONObject> findClinicRoomList(String dept,String date,String consult_status,String wxId) {
        if(StringUtils.isBlank(date)){
    public List<JSONObject> findClinicRoomList(String dept, String date, String consult_status, String wxId) {
        if (StringUtils.isBlank(date)) {
            date = DateUtil.getStringDateShort();
            date = DateUtil.getStringDateShort();
        }
        }
        //获取今天的排班列表
        //获取今天的排班列表
        String doctorsql ="SELECT doctor AS \"doctor\",doctor_name as \"doctor_name\",dept as \"dept\",dept_name as \"dept_name\" FROM wlyy_doctor_work_time WHERE work_date='"+date+"'";
        String doctorsql = "SELECT doctor AS \"doctor\",doctor_name as \"doctor_name\",dept as \"dept\",dept_name as \"dept_name\" FROM wlyy_doctor_work_time WHERE work_date='" + date + "'";
        if(StringUtils.isNoneBlank(dept)){
            doctorsql = doctorsql + " and dept = '"+dept+"' ";
        if (StringUtils.isNoneBlank(dept)) {
            doctorsql = doctorsql + " and dept = '" + dept + "' ";
        }
        }
        doctorsql = doctorsql+ " GROUP BY doctor,doctor_name,dept,dept_name";
        doctorsql = doctorsql + " GROUP BY doctor,doctor_name,dept,dept_name";
        List<Map<String,Object>> doctorlist = jdbcTemplate.queryForList(doctorsql);
        List<Map<String, Object>> doctorlist = jdbcTemplate.queryForList(doctorsql);
        HashMap<String ,JSONObject> result = new HashMap<>();
        HashMap<String, JSONObject> result = new HashMap<>();
        for (int i = 0; i < doctorlist.size(); i++) {
        for (int i = 0; i < doctorlist.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",(String)doctorlist.get(0).get("doctor"));
            jsonObject.put("id", (String) doctorlist.get(0).get("doctor"));
            if(StringUtils.isNoneBlank((String)doctorlist.get(0).get("doctor_name"))){
                jsonObject.put("doctor_name",(String)doctorlist.get(0).get("doctor_name"));
                jsonObject.put("dept_name",(String)doctorlist.get(0).get("dept_name"));
                jsonObject.put("dept_code",(String)doctorlist.get(0).get("dept"));
            }else{
                jsonObject.put("doctor_name","");
                jsonObject.put("dept_name","");
                jsonObject.put("dept_code","");
            if (StringUtils.isNoneBlank((String) doctorlist.get(0).get("doctor_name"))) {
                jsonObject.put("doctor_name", (String) doctorlist.get(0).get("doctor_name"));
                jsonObject.put("dept_name", (String) doctorlist.get(0).get("dept_name"));
                jsonObject.put("dept_code", (String) doctorlist.get(0).get("dept"));
            } else {
                jsonObject.put("doctor_name", "");
                jsonObject.put("dept_name", "");
                jsonObject.put("dept_code", "");
            }
            }
            jsonObject.put("visit_status",1);
            jsonObject.put("waiting_count",0);
            jsonObject.put("patient_name","");
            jsonObject.put("time_cost",0);
            jsonObject.put("visit_status", 1);
            jsonObject.put("waiting_count", 0);
            jsonObject.put("patient_name", "");
            jsonObject.put("time_cost", 0);
            result.put((String)doctorlist.get(0).get("doctor"),jsonObject);
            result.put((String) doctorlist.get(0).get("doctor"), jsonObject);
        }
        }
        //获取预约了今天的候诊居民
        //获取预约了今天的候诊居民
        String waitingSql ="SELECT count(op.id) AS \"waitCount\"," +
        String waitingSql = "SELECT count(op.id) AS \"waitCount\"," +
                "room.doctor AS \"doctor\", " +
                "room.doctor AS \"doctor\", " +
                "room.doctor_name AS \"doctorName\" " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM wlyy_outpatient op,wlyy_hospital_waiting_room room " +
                "FROM wlyy_outpatient op,wlyy_hospital_waiting_room room " +
                "WHERE op.status=0 AND room.outpatient_id=op.id AND room.consult_type=2 " +
                "WHERE op.status=0 AND room.outpatient_id=op.id AND room.consult_type=2 " +
                "AND room.doctor IS NOT NULL ";
                "AND room.doctor IS NOT NULL ";
        if(StringUtils.isNoneBlank(dept)){
            waitingSql = waitingSql + " and op.dept = '"+dept+"' ";
        if (StringUtils.isNoneBlank(dept)) {
            waitingSql = waitingSql + " and op.dept = '" + dept + "' ";
        }
        }
        if("xm_ykyy_wx".equals(wxId)){
            waitingSql +=" AND room.reservation_time >= to_date('"+date+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            waitingSql +=" AND room.reservation_time <= to_date('"+date+" 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
        }else {
            waitingSql = waitingSql + "AND room.reservation_time>='"+date+" 00:00:00' AND room.reservation_time<='"+date+" 23:59:59' GROUP BY room.doctor,room.doctor_name; ";
        if ("xm_ykyy_wx".equals(wxId)) {
            waitingSql += " AND room.reservation_time >= to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            waitingSql += " AND room.reservation_time <= to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') GROUP BY room.doctor,room.doctor_name";
        } else {
            waitingSql = waitingSql + "AND room.reservation_time>='" + date + " 00:00:00' AND room.reservation_time<='" + date + " 23:59:59' GROUP BY room.doctor,room.doctor_name; ";
        }
        }
        List<Map<String,Object>> waitinglist = jdbcTemplate.queryForList(waitingSql);
        if(waitinglist!=null&&waitinglist.size()>0){
        List<Map<String, Object>> waitinglist = jdbcTemplate.queryForList(waitingSql);
        if (waitinglist != null && waitinglist.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            for(Map<String,Object> waitObj :waitinglist){
            for (Map<String, Object> waitObj : waitinglist) {
                String doctor = (String) waitObj.get("doctor");
                String doctor = (String) waitObj.get("doctor");
                if(StringUtils.isNoneBlank(doctor)){
                    Long waitCount = Long.parseLong(waitObj.get("waitCount").toString()) ;
                    if(result.keySet().contains(doctor)){
                        result.get(doctor).put("waiting_count",waitCount);
                    }else{
                if (StringUtils.isNoneBlank(doctor)) {
                    Long waitCount = Long.parseLong(waitObj.get("waitCount").toString());
                    if (result.keySet().contains(doctor)) {
                        result.get(doctor).put("waiting_count", waitCount);
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id",doctor);
                        jsonObject.put("visit_status",1);
                        jsonObject.put("waiting_count",waitCount);
                        if(StringUtils.isNoneBlank((String)waitObj.get("doctorName"))){
                            jsonObject.put("doctor_name",(String)waitObj.get("doctorName"));
                        }else{
                            jsonObject.put("doctor_name","");
                        jsonObject.put("id", doctor);
                        jsonObject.put("visit_status", 1);
                        jsonObject.put("waiting_count", waitCount);
                        if (StringUtils.isNoneBlank((String) waitObj.get("doctorName"))) {
                            jsonObject.put("doctor_name", (String) waitObj.get("doctorName"));
                        } else {
                            jsonObject.put("doctor_name", "");
                        }
                        }
                        jsonObject.put("patient_name","");
                        jsonObject.put("time_cost",0);
                        result.put(doctor,jsonObject);
                        jsonObject.put("patient_name", "");
                        jsonObject.put("time_cost", 0);
                        result.put(doctor, jsonObject);
                    }
                    }
                }
                }
            }
            }
        }
        }
        //获取进行中的居民
        //获取进行中的居民
        String onlineSql ="SELECT " +
        String onlineSql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"patient_name\"," +
                "room.patient_name AS \"patient_name\"," +
@ -3727,12 +3876,12 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "patient.photo AS \"photo\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.birthday AS \"birthday\"," +
                "room.consult_type AS \"consult_type\",";
                "room.consult_type AS \"consult_type\",";
        if("xm_ykyy_wx".equals(wxId)){
        if ("xm_ykyy_wx".equals(wxId)) {
            onlineSql = onlineSql + "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",ceil((sysdate-to_date(to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss'))* 24 * 60) AS \"time_cost\",";
            onlineSql = onlineSql + "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",ceil((sysdate-to_date(to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss'),'YYYY-MM-DD hh24:mi:ss'))* 24 * 60) AS \"time_cost\",";
        }else{
        } else {
            onlineSql = onlineSql + "date_format(room.reservation_time,'%Y-%m-%d %H:%i:%S' )  AS \"time\",TIMESTAMPDIFF(MINUTE, room.reservation_time,NOW()) AS \"time_cost\",";
            onlineSql = onlineSql + "date_format(room.reservation_time,'%Y-%m-%d %H:%i:%S' )  AS \"time\",TIMESTAMPDIFF(MINUTE, room.reservation_time,NOW()) AS \"time_cost\",";
        }
        }
        onlineSql=onlineSql+"room.doctor AS \"doctor\", " +
        onlineSql = onlineSql + "room.doctor AS \"doctor\", " +
                "room.doctor_name AS \"doctorName\" " +
                "room.doctor_name AS \"doctorName\" " +
                "FROM " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_hospital_waiting_room room," +
@ -3745,63 +3894,63 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND consult.relation_code=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND consult.status=0 " +
                "AND consult.status=0 " +
                "AND room.consult_type=2 ";
                "AND room.consult_type=2 ";
        if(StringUtils.isNoneBlank(dept)){
            onlineSql = onlineSql + " and outpatient.dept = '"+dept+"' ";
        if (StringUtils.isNoneBlank(dept)) {
            onlineSql = onlineSql + " and outpatient.dept = '" + dept + "' ";
        }
        }
/*
/*
        onlineSql = onlineSql+ "AND room.reservation_time>='"+date+" 00:00:00' AND room.reservation_time<='"+date+" 23:59:59' GROUP BY room.doctor";
        onlineSql = onlineSql+ "AND room.reservation_time>='"+date+" 00:00:00' AND room.reservation_time<='"+date+" 23:59:59' GROUP BY room.doctor";
*/
*/
        if("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            onlineSql +=" AND room.reservation_time >= to_date('"+date+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            onlineSql +=" AND room.reservation_time <= to_date('"+date+" 23:59:59','YYYY-MM-DD HH24:MI:SS') ";
        }else {
            onlineSql = onlineSql+ "AND room.reservation_time>='"+date+" 00:00:00' AND room.reservation_time<='"+date+" 23:59:59' ";
        }
        List<Map<String,Object>> onlinelist = jdbcTemplate.queryForList(onlineSql);
        if(onlinelist!=null&&onlinelist.size()>0){
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            onlineSql += " AND room.reservation_time >= to_date('" + date + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            onlineSql += " AND room.reservation_time <= to_date('" + date + " 23:59:59','YYYY-MM-DD HH24:MI:SS') ";
        } else {
            onlineSql = onlineSql + "AND room.reservation_time>='" + date + " 00:00:00' AND room.reservation_time<='" + date + " 23:59:59' ";
        }
        List<Map<String, Object>> onlinelist = jdbcTemplate.queryForList(onlineSql);
        if (onlinelist != null && onlinelist.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            List<String> doctors = new ArrayList<>();
            List<String> doctors = new ArrayList<>();
            List<Map<String,Object>> onlines = new ArrayList<>();
            for (Map<String,Object> onlineObj :onlinelist){
            List<Map<String, Object>> onlines = new ArrayList<>();
            for (Map<String, Object> onlineObj : onlinelist) {
                String doctor = (String) onlineObj.get("doctor");
                String doctor = (String) onlineObj.get("doctor");
                if (doctors!=null&&doctors.size()!=0){
                    if (!doctors.contains(doctor)){
                if (doctors != null && doctors.size() != 0) {
                    if (!doctors.contains(doctor)) {
                        doctors.add(doctor);
                        doctors.add(doctor);
                        onlines.add(onlineObj);
                        onlines.add(onlineObj);
                    }
                    }
                }else {
                } else {
                    doctors.add(doctor);
                    doctors.add(doctor);
                    onlines.add(onlineObj);
                    onlines.add(onlineObj);
                }
                }
            }
            }
            for(Map<String,Object> onlineObj :onlines){
            for (Map<String, Object> onlineObj : onlines) {
                String doctor = (String) onlineObj.get("doctor");
                String doctor = (String) onlineObj.get("doctor");
                if(StringUtils.isNoneBlank(doctor)){
                    if(result.keySet().contains(doctor)){
                        result.get(doctor).put("visit_status",2);
                        result.get(doctor).put("patient_name",(String) onlineObj.get("patient_name"));
                        result.get(doctor).put("time_cost",Long.parseLong(onlineObj.get("time_cost").toString()));
                    }else{
                if (StringUtils.isNoneBlank(doctor)) {
                    if (result.keySet().contains(doctor)) {
                        result.get(doctor).put("visit_status", 2);
                        result.get(doctor).put("patient_name", (String) onlineObj.get("patient_name"));
                        result.get(doctor).put("time_cost", Long.parseLong(onlineObj.get("time_cost").toString()));
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id",doctor);
                        jsonObject.put("id", doctor);
                        if(StringUtils.isNoneBlank((String) onlineObj.get("doctorName"))){
                            jsonObject.put("doctor_name",(String) onlineObj.get("doctorName"));
                        }else{
                            jsonObject.put("doctor_name","");
                        if (StringUtils.isNoneBlank((String) onlineObj.get("doctorName"))) {
                            jsonObject.put("doctor_name", (String) onlineObj.get("doctorName"));
                        } else {
                            jsonObject.put("doctor_name", "");
                        }
                        }
                        jsonObject.put("visit_status",2);
                        jsonObject.put("waiting_count",0);
                        jsonObject.put("patient_name",(String) onlineObj.get("patient_name"));
                        jsonObject.put("time_cost",Long.parseLong(onlineObj.get("time_cost").toString()));
                        result.put(doctor,jsonObject);
                        jsonObject.put("visit_status", 2);
                        jsonObject.put("waiting_count", 0);
                        jsonObject.put("patient_name", (String) onlineObj.get("patient_name"));
                        jsonObject.put("time_cost", Long.parseLong(onlineObj.get("time_cost").toString()));
                        result.put(doctor, jsonObject);
                    }
                    }
                }
                }
            }
            }
        }
        }
        List<JSONObject> finalresult  = new ArrayList<>();
        List<JSONObject> finalresult = new ArrayList<>();
        for (JSONObject jsonObject : result.values()) {
        for (JSONObject jsonObject : result.values()) {
@ -3810,30 +3959,31 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            //接诊中:在线状态=在线 and 接诊状态=接诊中
            //接诊中:在线状态=在线 and 接诊状态=接诊中
            //过滤空闲或者接诊中的居民
            //过滤空闲或者接诊中的居民
            if(StringUtils.isBlank(consult_status)){
            if (StringUtils.isBlank(consult_status)) {
                finalresult.add(jsonObject);
                finalresult.add(jsonObject);
            }else{
                if("0".equals(consult_status)){
            } else {
                if ("0".equals(consult_status)) {
                    //只显示在线
                    //只显示在线
                }else if("1".equals(consult_status) && "1".equals(jsonObject.getString("visit_status"))){
                } else if ("1".equals(consult_status) && "1".equals(jsonObject.getString("visit_status"))) {
                    //空闲
                    //空闲
                    finalresult.add(jsonObject);
                    finalresult.add(jsonObject);
                }else if("2".equals(consult_status) && "2".equals(jsonObject.getString("visit_status"))){
                } else if ("2".equals(consult_status) && "2".equals(jsonObject.getString("visit_status"))) {
                    //接诊
                    //接诊
                    finalresult.add(jsonObject);
                    finalresult.add(jsonObject);
                }else{}
                } else {
                }
            }
            }
        }
        }
        Integer room_no = 1;
        Integer room_no = 1;
        for(JSONObject jsonObject :finalresult){
        for (JSONObject jsonObject : finalresult) {
            String roomname = "";
            String roomname = "";
            if(room_no < 10){
                roomname = "0"+room_no+"诊室";
            }else{
                roomname = room_no+"诊室";
            if (room_no < 10) {
                roomname = "0" + room_no + "诊室";
            } else {
                roomname = room_no + "诊室";
            }
            }
            jsonObject.put("room_name",roomname);
            room_no ++;
            jsonObject.put("room_name", roomname);
            room_no++;
        }
        }
        return finalresult;
        return finalresult;
@ -3845,29 +3995,30 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取快速咨询时间分段
     * 获取快速咨询时间分段
     *
     * @param startTime
     * @param startTime
     * @param endTime
     * @param endTime
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findByTimeSlot(String startTime,String endTime){
    public List<Map<String, Object>> findByTimeSlot(String startTime, String endTime) {
        int interval = 30;
        int interval = 30;
        List<Map<String,Object>> times = new ArrayList<>();
        List<Map<String, Object>> times = new ArrayList<>();
        //设置上午过号时间
        //设置上午过号时间
        Calendar scTime = Calendar.getInstance();
        Calendar scTime = Calendar.getInstance();
        scTime.setTime(DateUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss"));
        scTime.setTime(DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss"));
        Calendar ecTime = Calendar.getInstance();
        Calendar ecTime = Calendar.getInstance();
        ecTime.setTime(DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss"));
        while (scTime.getTime().before(ecTime.getTime())){
            if(new Date().before(scTime.getTime())){
                Map<String,Object> time = new HashedMap();
                time.put("startTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
                scTime.add(Calendar.MINUTE,interval);
                time.put("endTime",DateUtil.dateToStr(scTime.getTime(),"yyyy-MM-dd HH:mm:ss"));
        ecTime.setTime(DateUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss"));
        while (scTime.getTime().before(ecTime.getTime())) {
            if (new Date().before(scTime.getTime())) {
                Map<String, Object> time = new HashedMap();
                time.put("startTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
                scTime.add(Calendar.MINUTE, interval);
                time.put("endTime", DateUtil.dateToStr(scTime.getTime(), "yyyy-MM-dd HH:mm:ss"));
                times.add(time);
                times.add(time);
            }else{
                scTime.add(Calendar.MINUTE,interval);
            } else {
                scTime.add(Calendar.MINUTE, interval);
            }
            }
        }
        }
        return times;
        return times;
@ -3875,9 +4026,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 根据疾病名称,热门部门查询医生
     * 根据疾病名称,热门部门查询医生
     * @param orgCode 机构码
     * @param dept 部门CODE
     * @param diseaseKey 疾病名称
     *
     * @param orgCode         机构码
     * @param dept            部门CODE
     * @param diseaseKey      疾病名称
     * @param jobTitleNameKey
     * @param jobTitleNameKey
     * @param outpatientType
     * @param outpatientType
     * @param keyName
     * @param keyName
@ -3885,10 +4037,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param consutlSort
     * @param consutlSort
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findDoctorByHospitalAndDiseaseAndDept(String iswork,String patientid,String orgCode, String dept,
                                                                          String diseaseKey, String doctorNameKey,
                                                                          String jobTitleNameKey, String outpatientType,
                                                                          String keyName, String workingTime, String consultStatus,String chargType,String consutlSort,String isAttention,Integer page,Integer pagesize) {
    public List<Map<String, Object>> findDoctorByHospitalAndDiseaseAndDept(String iswork, String patientid, String orgCode, String dept,
                                                                           String diseaseKey, String doctorNameKey,
                                                                           String jobTitleNameKey, String outpatientType,
                                                                           String keyName, String workingTime, String consultStatus, String chargType, String consutlSort, String isAttention, Integer page, Integer pagesize) {
      /*  if(page >=1){
      /*  if(page >=1){
            page --;
            page --;
@ -3898,7 +4050,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            pagesize = 10;
            pagesize = 10;
        }*/
        }*/
        String sql ="SELECT " +
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.id AS \"id\", " +
                " d.photo AS \"photo\", " +
                " d.photo AS \"photo\", " +
                " d.name AS \"name\", " +
                " d.name AS \"name\", " +
@ -3913,50 +4065,50 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " a.total AS \"consultTotal\"," +
                " a.total AS \"consultTotal\"," +
                " h.org_name AS \"orgName\"," +
                " h.org_name AS \"orgName\"," +
                " h.org_code AS \"orgCode\"," +
                " h.org_code AS \"orgCode\"," +
                " follow.id AS \"followid\" "+
                " follow.id AS \"followid\" " +
                " FROM " +
                " FROM " +
                " base_doctor d " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id "+
                " JOIN base_doctor_hospital h ON h.doctor_code = d.id " +
                " Left join ( select count(id) as total,doctor from wlyy_outpatient where status = 2 GROUP BY doctor ) a on a.doctor = d.id ";
                " Left join ( select count(id) as total,doctor from wlyy_outpatient where status = 2 GROUP BY doctor ) a on a.doctor = d.id ";
        if ("1".equalsIgnoreCase(isAttention)){
            sql+=" join base_doctor_patient_follow follow on follow.doctor = d.id and follow.patient ='"+patientid+"' ";
        if ("1".equalsIgnoreCase(isAttention)) {
            sql += " join base_doctor_patient_follow follow on follow.doctor = d.id and follow.patient ='" + patientid + "' ";
        }
        }
        if ("0".equalsIgnoreCase(isAttention)) {
        if ("0".equalsIgnoreCase(isAttention)) {
            sql += " join base_doctor_patient_follow follow on follow.doctor = d.id and follow.patient !='" + patientid + "' ";
            sql += " join base_doctor_patient_follow follow on follow.doctor = d.id and follow.patient !='" + patientid + "' ";
        }
        }
        if (StringUtils.isEmpty(isAttention)){
            sql+=" LEFT  JOIN base_doctor_patient_follow follow ON follow.patient='"+patientid+"' AND follow.doctor = d.id ";
        if (StringUtils.isEmpty(isAttention)) {
            sql += " LEFT  JOIN base_doctor_patient_follow follow ON follow.patient='" + patientid + "' AND follow.doctor = d.id ";
        }
        }
        if(StringUtils.isNotBlank(diseaseKey)){
            sql+=" left join wlyy_doctor_special_disease sp on d.id = sp.doctor_code ";
        if (StringUtils.isNotBlank(diseaseKey)) {
            sql += " left join wlyy_doctor_special_disease sp on d.id = sp.doctor_code ";
        }
        }
        if(StringUtils.isNotBlank(workingTime)){
            sql+=" JOIN wlyy_doctor_work_time wk on wk.doctor = d.id ";
        if (StringUtils.isNotBlank(workingTime)) {
            sql += " JOIN wlyy_doctor_work_time wk on wk.doctor = d.id ";
        }
        }
        sql +=  " WHERE  1=1 ";
        sql += " WHERE  1=1 ";
        Map<String, Object> params = new HashedMap();
        Map<String, Object> params = new HashedMap();
        if(StringUtils.isBlank(chargType)){
            sql +=" AND d.charge_type is not null ";
        if (StringUtils.isBlank(chargType)) {
            sql += " AND d.charge_type is not null ";
        }
        }
        if(StringUtils.isNotBlank(chargType)){
            if("all".equals(chargType)){
        if (StringUtils.isNotBlank(chargType)) {
            if ("all".equals(chargType)) {
                //不过滤
                //不过滤
            }else{
                sql+=" AND d.charge_type = :chargType";
                params.put("chargType",chargType);
            } else {
                sql += " AND d.charge_type = :chargType";
                params.put("chargType", chargType);
            }
            }
        }
        }
        if(StringUtils.isNotBlank(iswork)&&"1".equals(iswork)){
            logger.info("iswork:"+iswork);
        if (StringUtils.isNotBlank(iswork) && "1".equals(iswork)) {
            logger.info("iswork:" + iswork);
            Date date = new Date();
            Date date = new Date();
            sql+=" AND (" +
            sql += " AND (" +
                    " EXISTS ( " +
                    " EXISTS ( " +
                    " SELECT " +
                    " SELECT " +
                    "  1 " +
                    "  1 " +
@ -3965,84 +4117,85 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " WHERE " +
                    " WHERE " +
                    "  t.doctor = d.id " +
                    "  t.doctor = d.id " +
                    " AND t.start_time <=:startTime" +
                    " AND t.start_time <=:startTime" +
                    " AND t.end_time >=:endTime"+
                    " AND t.end_time >=:endTime" +
                    " ) OR " +
                    " ) OR " +
                    " d.consult_status = '1') ";
                    " d.consult_status = '1') ";
            params.put("startTime",date);
            params.put("endTime",date);
            params.put("startTime", date);
            params.put("endTime", date);
        }
        }
        if(StringUtils.isNotBlank(orgCode)){
        if (StringUtils.isNotBlank(orgCode)) {
            sql += " AND  h.org_code = :orgCode";
            sql += " AND  h.org_code = :orgCode";
            params.put("orgCode",orgCode);
            params.put("orgCode", orgCode);
        }
        }
        if(StringUtils.isNotBlank(diseaseKey)){
            sql+=" AND sp.disease_name like :diseaseKey";
            params.put("diseaseKey","%"+diseaseKey+"%");
        if (StringUtils.isNotBlank(diseaseKey)) {
            sql += " AND sp.disease_name like :diseaseKey";
            params.put("diseaseKey", "%" + diseaseKey + "%");
        }
        }
        if(StringUtils.isNotBlank(doctorNameKey)){
            sql+=" AND d.name like :doctorNameKey";
            params.put("doctorNameKey","%"+doctorNameKey+"%");
        if (StringUtils.isNotBlank(doctorNameKey)) {
            sql += " AND d.name like :doctorNameKey";
            params.put("doctorNameKey", "%" + doctorNameKey + "%");
        }
        }
        if(StringUtils.isNotBlank(dept)){
            sql+=" AND h.dept_code = :dept ";
            params.put("dept",dept);
        if (StringUtils.isNotBlank(dept)) {
            sql += " AND h.dept_code = :dept ";
            params.put("dept", dept);
        }
        }
        if(StringUtils.isNotBlank(jobTitleNameKey)){
            sql+=" AND d.job_title_name  = :jobTitleNameKey ";
            params.put("jobTitleNameKey",jobTitleNameKey);
        if (StringUtils.isNotBlank(jobTitleNameKey)) {
            sql += " AND d.job_title_name  = :jobTitleNameKey ";
            params.put("jobTitleNameKey", jobTitleNameKey);
        }
        }
        if(StringUtils.isNotBlank(outpatientType)){
            if(outpatientType.contains("or")){
        if (StringUtils.isNotBlank(outpatientType)) {
            if (outpatientType.contains("or")) {
                String[] outpatientTypeArray = outpatientType.split("or");
                String[] outpatientTypeArray = outpatientType.split("or");
                sql+= " AND ( ";
                sql += " AND ( ";
                for (int i = 0; i < outpatientTypeArray.length; i++) {
                for (int i = 0; i < outpatientTypeArray.length; i++) {
                    sql +=" d.outpatient_type like'%"+outpatientTypeArray[i]+"%'";
                    if(i != outpatientTypeArray.length -1){
                    sql += " d.outpatient_type like'%" + outpatientTypeArray[i] + "%'";
                    if (i != outpatientTypeArray.length - 1) {
                        sql += " or ";
                        sql += " or ";
                    }
                    }
                }
                }
                sql+= " ) ";
            }else{
                sql+= " AND d.outpatient_type like'%"+outpatientType+"%'";
                sql += " ) ";
            } else {
                sql += " AND d.outpatient_type like'%" + outpatientType + "%'";
            }
            }
        }else{
            sql+=" AND d.outpatient_type is not null ";
        } else {
            sql += " AND d.outpatient_type is not null ";
        }
        }
        if(StringUtils.isNotBlank(keyName)){
            sql+=" AND (h.dept_name like '%"+keyName+"%' or d.name like '%"+keyName+"%' or d.expertise like '%"+keyName+"%' )";
        if (StringUtils.isNotBlank(keyName)) {
            sql += " AND (h.dept_name like '%" + keyName + "%' or d.name like '%" + keyName + "%' or d.expertise like '%" + keyName + "%' )";
        }
        }
        if(StringUtils.isNotBlank(workingTime)){
            sql+=" AND wk.work_date = :workingTime ";
            params.put("workingTime",workingTime);
        if (StringUtils.isNotBlank(workingTime)) {
            sql += " AND wk.work_date = :workingTime ";
            params.put("workingTime", workingTime);
        }
        }
        if(StringUtils.isNotBlank(consultStatus)){
            sql+=" AND d.consult_status = :consultStatus ";
            params.put("consultStatus",consultStatus);
        if (StringUtils.isNotBlank(consultStatus)) {
            sql += " AND d.consult_status = :consultStatus ";
            params.put("consultStatus", consultStatus);
        }
        }
        sql += " and d.del='1' order by a.total "+ consutlSort;
        sql += " and d.del='1' order by a.total " + consutlSort;
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,params,page,pagesize);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, params, page, pagesize);
        logger.info("findDoctorByHospitalAndDiseaseAndDept end:"+DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss:SSS"));
        logger.info("sql:"+sql);
        logger.info("findDoctorByHospitalAndDiseaseAndDept end:" + DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss:SSS"));
        logger.info("sql:" + sql);
        return list;
        return list;
    }
    }
    /**
    /**
     * 获取常见疾病、热门部门、医生拒绝接诊原因 字典
     * 获取常见疾病、热门部门、医生拒绝接诊原因 字典
     *
     * @param dictName 字典名称
     * @param dictName 字典名称
     * @return
     * @return
     */
     */
@ -4057,22 +4210,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询排班规则
     * 查询排班规则
     *
     * @return
     * @return
     */
     */
    public List<WlyyHospitalSysDictVO> findWorkRule(String dictName,String hospital){
        List<WlyyHospitalSysDictDO> list = sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital,dictName);
    public List<WlyyHospitalSysDictVO> findWorkRule(String dictName, String hospital) {
        List<WlyyHospitalSysDictDO> list = sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital, dictName);
        List<WlyyHospitalSysDictVO> vos = new ArrayList<>();
        List<WlyyHospitalSysDictVO> vos = new ArrayList<>();
        return convertToModels(list,vos,WlyyHospitalSysDictVO.class);
        return convertToModels(list, vos, WlyyHospitalSysDictVO.class);
    }
    }
    /**
    /**
     * 保存排班规则
     * 保存排班规则
     *
     * @param workRoleJsons
     * @param workRoleJsons
     * @return
     * @return
     */
     */
    public Boolean updateWorkRule(String workRoleJsons){
    public Boolean updateWorkRule(String workRoleJsons) {
        List<WlyyHospitalSysDictDO> sysDicts = (List<WlyyHospitalSysDictDO>) com.alibaba.fastjson.JSONArray.parseArray(workRoleJsons, WlyyHospitalSysDictDO.class);
        List<WlyyHospitalSysDictDO> sysDicts = (List<WlyyHospitalSysDictDO>) com.alibaba.fastjson.JSONArray.parseArray(workRoleJsons, WlyyHospitalSysDictDO.class);
        List<WlyyHospitalSysDictDO> list = sysDictDao.findByHospitalAndDictNameOrderBySortAsc(sysDicts.get(0).getHospital(),sysDicts.get(0).getDictName());
        List<WlyyHospitalSysDictDO> list = sysDictDao.findByHospitalAndDictNameOrderBySortAsc(sysDicts.get(0).getHospital(), sysDicts.get(0).getDictName());
        sysDictDao.delete(list);
        sysDictDao.delete(list);
        sysDictDao.save(sysDicts);
        sysDictDao.save(sysDicts);
        return true;
        return true;
@ -4085,19 +4240,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Boolean saveDoctorWorkTimeJson(String type,String codes,String workTimeJson,String date)throws Exception{
    public Boolean saveDoctorWorkTimeJson(String type, String codes, String workTimeJson, String date) throws Exception {
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        for(int i=0;i<works.size();i++){
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject)works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(),WlyyDoctorWorkTimeDO.class);
        for (int i = 0; i < works.size(); i++) {
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject) works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(), WlyyDoctorWorkTimeDO.class);
            wlyyDoctorWorkTimeDOs.add(timeDO);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }
        }
        //全院医生
        //全院医生
        if("1".equals(type)){
            String sql ="SELECT " +
        if ("1".equals(type)) {
            String sql = "SELECT " +
                    " DISTINCT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " d.name AS \"name\", " +
@ -4107,14 +4262,14 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " base_doctor d " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " WHERE  " +
                    " WHERE  " +
                    " h.org_code ='"+codes+"'";
            List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs =makeDoctorWorkTimeDOList(doctors,wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs,date,doctors);
                    " h.org_code ='" + codes + "'";
            List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs, date, doctors);
            //科室
            //科室
        }else if("2".equals(type)){
        } else if ("2".equals(type)) {
            String sql ="SELECT " +
            String sql = "SELECT " +
                    " DISTINCT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " d.name AS \"name\", " +
@ -4124,13 +4279,13 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " base_doctor d " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " WHERE  " +
                    " WHERE  " +
                    " h.dept_code in ("+sqlCode(codes)+")";
            List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs =makeDoctorWorkTimeDOList(doctors,wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs,date,doctors);
                    " h.dept_code in (" + sqlCode(codes) + ")";
            List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs, date, doctors);
            //医生批量
            //医生批量
        }else if("3".equals(type)){
            String sql ="SELECT " +
        } else if ("3".equals(type)) {
            String sql = "SELECT " +
                    " DISTINCT " +
                    " DISTINCT " +
                    " d.id AS \"id\", " +
                    " d.id AS \"id\", " +
                    " d.name AS \"name\", " +
                    " d.name AS \"name\", " +
@ -4140,10 +4295,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    " base_doctor d " +
                    " base_doctor d " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                    " WHERE  " +
                    " WHERE  " +
                    " d.id in ("+sqlCode(codes)+")";
            List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs =makeDoctorWorkTimeDOList(doctors,wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs,date,doctors);
                    " d.id in (" + sqlCode(codes) + ")";
            List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
            List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
            saveDoctorWorkTime(workTimeDOs, date, doctors);
        }
        }
        return true;
        return true;
@ -4151,23 +4306,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 医生自主保存排班
     * 医生自主保存排班
     *
     * @param codes
     * @param codes
     * @param workTimeJson
     * @param workTimeJson
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Boolean doctorSaveWorkTimeJson(String codes,String workTimeJson,String date)throws Exception{
    public Boolean doctorSaveWorkTimeJson(String codes, String workTimeJson, String date) throws Exception {
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        for(int i=0;i<works.size();i++){
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject)works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(),WlyyDoctorWorkTimeDO.class);
        for (int i = 0; i < works.size(); i++) {
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject) works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(), WlyyDoctorWorkTimeDO.class);
            wlyyDoctorWorkTimeDOs.add(timeDO);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }
        }
        //医生自主排班
        //医生自主排班
        String sql ="SELECT " +
        String sql = "SELECT " +
                " DISTINCT " +
                " DISTINCT " +
                " d.id AS \"id\", " +
                " d.id AS \"id\", " +
                " d.name AS \"name\", " +
                " d.name AS \"name\", " +
@ -4177,10 +4333,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " base_doctor d " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " WHERE  " +
                " WHERE  " +
                " d.id in ("+sqlCode(codes)+")";
        List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs =makeDoctorWorkTimeDOList(doctors,wlyyDoctorWorkTimeDOs);
        return doctorSaveWorkTime(workTimeDOs,date,doctors);
                " d.id in (" + sqlCode(codes) + ")";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
        return doctorSaveWorkTime(workTimeDOs);
    }
    }
    /**
    /**
@ -4191,18 +4347,18 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Boolean doctorUpdateWorkTimeJson(String workTimeJson,String codes)throws Exception{
    public Boolean doctorUpdateWorkTimeJson(String workTimeJson, String codes) throws Exception {
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        com.alibaba.fastjson.JSONArray works = JSON.parseArray(workTimeJson);
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs = new ArrayList<>();
        for(int i=0;i<works.size();i++){
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject)works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(),WlyyDoctorWorkTimeDO.class);
        for (int i = 0; i < works.size(); i++) {
            com.alibaba.fastjson.JSONObject work = (com.alibaba.fastjson.JSONObject) works.get(i);
            WlyyDoctorWorkTimeDO timeDO = objectMapper.readValue(work.toJSONString(), WlyyDoctorWorkTimeDO.class);
            wlyyDoctorWorkTimeDOs.add(timeDO);
            wlyyDoctorWorkTimeDOs.add(timeDO);
        }
        }
        //医生自主排班
        //医生自主排班
        String sql ="SELECT " +
        String sql = "SELECT " +
                " DISTINCT " +
                " DISTINCT " +
                " d.id AS \"id\", " +
                " d.id AS \"id\", " +
                " d.name AS \"name\", " +
                " d.name AS \"name\", " +
@ -4212,18 +4368,11 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " base_doctor d " +
                " base_doctor d " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " JOIN base_doctor_hospital h ON d.id= h.doctor_code " +
                " WHERE  " +
                " WHERE  " +
                " d.id in ("+sqlCode(codes)+")";
        List<Map<String,Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs =makeDoctorWorkTimeDOList(doctors,wlyyDoctorWorkTimeDOs);
        for (WlyyDoctorWorkTimeDO workTimeDO:workTimeDOs){
            List<WlyyDoctorWorkTimeDO> workTimeDOList = doctorWorkTimeDao.findDoctorWorkTimeByDate(workTimeDO.getDoctor(),workTimeDO.getStartTime(),workTimeDO.getEndTime());
            if (workTimeDOList!=null&&workTimeDOList.size()!=0){
                throw new Exception("您选择的时间与“开始时间-结束时间”的医院排班/自己排班冲突,请重新选择!");
            }else {
                doctorWorkTimeDao.save(workTimeDO);
            }
        }
        return true;
                " d.id in (" + sqlCode(codes) + ")";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql);
        List<WlyyDoctorWorkTimeDO> workTimeDOs = makeDoctorWorkTimeDOList(doctors, wlyyDoctorWorkTimeDOs);
        return doctorSaveWorkTime(workTimeDOs);
    }
    }
@ -4234,34 +4383,34 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Boolean deleteWorkTime(String code)throws Exception{
    public Boolean deleteWorkTime(String code) throws Exception {
        doctorWorkTimeDao.delete(code);
        doctorWorkTimeDao.delete(code);
        return true;
        return true;
    }
    }
    public String sqlCode(String codes){
    public String sqlCode(String codes) {
        String code[] = codes.split(",");
        String code[] = codes.split(",");
        String rs = "";
        String rs = "";
        for(String c:code){
            rs+="'"+c+"',";
        for (String c : code) {
            rs += "'" + c + "',";
        }
        }
        rs = rs.substring(0,rs.length()-1);
        rs = rs.substring(0, rs.length() - 1);
        return rs;
        return rs;
    }
    }
    public List<WlyyDoctorWorkTimeDO> makeDoctorWorkTimeDOList(List<Map<String,Object>> doctors,List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs){
    public List<WlyyDoctorWorkTimeDO> makeDoctorWorkTimeDOList(List<Map<String, Object>> doctors, List<WlyyDoctorWorkTimeDO> wlyyDoctorWorkTimeDOs) {
        List<WlyyDoctorWorkTimeDO> rs = new ArrayList<>();
        List<WlyyDoctorWorkTimeDO> rs = new ArrayList<>();
        if(doctors!=null&&doctors.size()>0){
        if (doctors != null && doctors.size() > 0) {
            //构建医生排班
            //构建医生排班
            for(Map<String,Object> doctor:doctors){
                for(WlyyDoctorWorkTimeDO time:wlyyDoctorWorkTimeDOs){
            for (Map<String, Object> doctor : doctors) {
                for (WlyyDoctorWorkTimeDO time : wlyyDoctorWorkTimeDOs) {
                    WlyyDoctorWorkTimeDO t = new WlyyDoctorWorkTimeDO();
                    WlyyDoctorWorkTimeDO t = new WlyyDoctorWorkTimeDO();
                    t.setDoctor((String)doctor.get("id"));
                    t.setDoctorName((String)doctor.get("name"));
                    t.setDoctor((String) doctor.get("id"));
                    t.setDoctorName((String) doctor.get("name"));
//                    t.setDept((String)doctor.get("dept_code"));
//                    t.setDept((String)doctor.get("dept_code"));
//                    t.setDeptName((String)doctor.get("dept_name"));
//                    t.setDeptName((String)doctor.get("dept_name"));
                    t.setHospital((String)doctor.get("org_code"));
                    t.setHospitalName((String)doctor.get("org_name"));
                    t.setHospital((String) doctor.get("org_code"));
                    t.setHospitalName((String) doctor.get("org_name"));
                    t.setCreateTime(new Date());
                    t.setCreateTime(new Date());
                    t.setType(time.getType());
                    t.setType(time.getType());
@ -4276,7 +4425,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    t.setId(time.getId());
                    t.setId(time.getId());
                    rs.add(t);
                    rs.add(t);
                }
                }
                logger.info(rs.size()+"");
                logger.info(rs.size() + "");
            }
            }
        }
        }
        return rs;
        return rs;
@ -4284,33 +4433,34 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 批量更新医生多月份排班数据
     * 批量更新医生多月份排班数据
     *
     * @param workTimeDOs
     * @param workTimeDOs
     * @return
     * @return
     */
     */
    public Boolean saveDoctorWorkTime(List<WlyyDoctorWorkTimeDO> workTimeDOs,String date,List<Map<String,Object>> doctors){
    public Boolean saveDoctorWorkTime(List<WlyyDoctorWorkTimeDO> workTimeDOs, String date, List<Map<String, Object>> doctors) {
        if(workTimeDOs!=null&&workTimeDOs.size()>0){
        if (workTimeDOs != null && workTimeDOs.size() > 0) {
            //按月按医生分组标记排班数据
            //按月按医生分组标记排班数据
            List<String> workMonths = new ArrayList<>();
            List<String> workMonths = new ArrayList<>();
            for(WlyyDoctorWorkTimeDO time : workTimeDOs){
            for (WlyyDoctorWorkTimeDO time : workTimeDOs) {
                //医生工作月份
                //医生工作月份
                String workMonth = time.getDoctor()+","+time.getDate().substring(0,7);
                String workMonth = time.getDoctor() + "," + time.getDate().substring(0, 7);
                //判断是否是首次插入医生月份数据,如果是首次,则删除该医生当前月份排班数据数据
                //判断是否是首次插入医生月份数据,如果是首次,则删除该医生当前月份排班数据数据
                if(!workMonths.contains(workMonth)){
                if (!workMonths.contains(workMonth)) {
                    workMonths.add(workMonth);
                    workMonths.add(workMonth);
                    List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth(time.getDoctor(),"%"+time.getDate().substring(0,7)+"%");
                    List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth(time.getDoctor(), "%" + time.getDate().substring(0, 7) + "%");
                    doctorWorkTimeDao.delete(oldTimes);
                    doctorWorkTimeDao.delete(oldTimes);
                }
                }
            }
            }
            doctorWorkTimeDao.save(workTimeDOs);
            doctorWorkTimeDao.save(workTimeDOs);
        }else{
        } else {
            //如果排班数据为空,删除医生月份下排班数据
            //如果排班数据为空,删除医生月份下排班数据
            if(StringUtils.isNotBlank(date)){
            if (StringUtils.isNotBlank(date)) {
                String d[] = date.split(",");
                String d[] = date.split(",");
                for(String dt:d){
                    for(Map<String,Object> doc:doctors){
                        List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth((String)doc.get("id"),"%"+dt+"%");
                for (String dt : d) {
                    for (Map<String, Object> doc : doctors) {
                        List<WlyyDoctorWorkTimeDO> oldTimes = doctorWorkTimeDao.findDoctorWorkTimeByMonth((String) doc.get("id"), "%" + dt + "%");
                        doctorWorkTimeDao.delete(oldTimes);
                        doctorWorkTimeDao.delete(oldTimes);
                    }
                    }
                }
                }
@ -4322,168 +4472,197 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 更新医生
     * 更新医生
     *
     * @param workTimeDOs
     * @param workTimeDOs
     * @return
     * @return
     */
     */
    public boolean doctorSaveWorkTime(List<WlyyDoctorWorkTimeDO> workTimeDOs,String date,List<Map<String,Object>> doctors) throws Exception {
        for (WlyyDoctorWorkTimeDO workTimeDO:workTimeDOs){
            List<WlyyDoctorWorkTimeDO> workTimeDOList = doctorWorkTimeDao.findDoctorWorkTimeByDate(workTimeDO.getDoctor(),workTimeDO.getStartTime(),workTimeDO.getEndTime());
            if (workTimeDOList!=null&&workTimeDOList.size()!=0){
                    throw new Exception("您选择的时间与“开始时间-结束时间”的医院排班/自己排班冲突,请重新选择!");
            }else {
                doctorWorkTimeDao.save(workTimeDO);
    public boolean doctorSaveWorkTime(List<WlyyDoctorWorkTimeDO> workTimeDOs) throws Exception {
        for (WlyyDoctorWorkTimeDO workTimeDO : workTimeDOs) {
            if (workTimeDO.getStartTime().before(DateUtil.getNowDate()) || workTimeDO.getEndTime().before(DateUtil.getNowDate())) {
                throw new Exception("您选择的时间小于系统时间,请重新选择!");
            }
            }
            String dateShort = DateUtil.dateToStrShort(workTimeDO.getStartTime());
//            StringBuilder sql=new StringBuilder("SELECT * FROM wlyy_doctor_work_time c WHERE ");
//            sql.append(" c.start_time >=  '"+dateShort+" 00:00:00 '").append(" and c.end_time <= '").append(dateShort+" 59:59:59 '");
//            sql.append(" AND c.doctor= '").append(workTimeDO.getDoctor());
//            sql.append("' order by c.start_time asc");
//            logger.info("sql="+sql.toString());
//            List<WlyyDoctorWorkTimeDO> workTimeDOList = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyDoctorWorkTimeDO.class));
            List<WlyyDoctorWorkTimeDO> workTimeDOList = doctorWorkTimeDao.findDoctorWorkTimeByTime(workTimeDO.getDoctor(), DateUtil.stringToDate(dateShort + " 00:00:00", "yyyy-MM-dd HH:mm:ss"), DateUtil.stringToDate(dateShort + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
            for (WlyyDoctorWorkTimeDO one : workTimeDOList) {
                if (one.getId().equalsIgnoreCase(workTimeDO.getId())) {
                    continue;
                }
                try {
                    //与医院与自己排班比较  是否冲突  第一组最后时间小于等于第二组最前时间 || 第一组最前时间大于等于第二组最后时间
                    if (one.getEndTime().before(workTimeDO.getStartTime()) || one.getStartTime().after(workTimeDO.getEndTime())) {
                    } else {
                        throw new Exception("您选择的时间与“开始时间-结束时间”的医院排班/自己排班冲突,请重新选择!");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
            doctorWorkTimeDao.save(workTimeDO);
        }
        }
        return true;
        return true;
    }
    }
    /**
    /**
     * 查询某个医生某个月份排班记录
     * 查询某个医生某个月份排班记录
     *
     * @param doctor
     * @param doctor
     * @param date
     * @param date
     * @return
     * @return
     */
     */
    public List<WlyyDoctorWorkTimeVO> findDoctorWorkTimeByMonth(String doctor,String date,String startDate,String endDate){
    public List<WlyyDoctorWorkTimeVO> findDoctorWorkTimeByMonth(String doctor, String date, String startDate, String endDate) {
        if(StringUtils.isNotBlank(date)){
            List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTimeByMonth(doctor,"%"+date+"%");
        if (StringUtils.isNotBlank(date)) {
            List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTimeByMonth(doctor, "%" + date + "%");
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            return convertToModels(times,timeVOs,WlyyDoctorWorkTimeVO.class);
        }else{
            List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTimeByTime(doctor,DateUtil.stringToDate(startDate+" 00:00:00","yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate+" 23:59:59","yyyy-MM-dd HH:mm:ss"));
            return convertToModels(times, timeVOs, WlyyDoctorWorkTimeVO.class);
        } else {
            List<WlyyDoctorWorkTimeDO> times = doctorWorkTimeDao.findDoctorWorkTimeByTime(doctor, DateUtil.stringToDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss"), DateUtil.stringToDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            List<WlyyDoctorWorkTimeVO> timeVOs = new ArrayList<>();
            return convertToModels(times,timeVOs,WlyyDoctorWorkTimeVO.class);
            return convertToModels(times, timeVOs, WlyyDoctorWorkTimeVO.class);
        }
        }
    }
    }
    public Map<String,Object> findPatientInfo(String patient){
        Map<String,Object> rs = new HashedMap();
    public Map<String, Object> findPatientInfo(String patient) {
        Map<String, Object> rs = new HashedMap();
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        rs.put("id",patient);
        rs.put("name",basePatientDO.getName());
        rs.put("sex",basePatientDO.getSex());
        rs.put("provinceCode",basePatientDO.getProvinceCode());
        rs.put("provinceName",basePatientDO.getProvinceName());
        rs.put("cityCode",basePatientDO.getCityCode());
        rs.put("cityName",basePatientDO.getCityName());
        rs.put("townCode",basePatientDO.getTownCode());
        rs.put("townName",basePatientDO.getTownName());
        rs.put("idcard",basePatientDO.getIdcard());
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile",basePatientDO.getMobile());
        rs.put("photo",basePatientDO.getPhoto());
        rs.put("address",basePatientDO.getAddress());
        if (patientMedicareCardDO!=null){
            rs.put("ssc",patientMedicareCardDO.getCode());
        }else {
            rs.put("ssc","");
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01", patient, "1");
        rs.put("id", patient);
        rs.put("name", basePatientDO.getName());
        rs.put("sex", basePatientDO.getSex());
        rs.put("provinceCode", basePatientDO.getProvinceCode());
        rs.put("provinceName", basePatientDO.getProvinceName());
        rs.put("cityCode", basePatientDO.getCityCode());
        rs.put("cityName", basePatientDO.getCityName());
        rs.put("townCode", basePatientDO.getTownCode());
        rs.put("townName", basePatientDO.getTownName());
        rs.put("idcard", basePatientDO.getIdcard());
        rs.put("age", IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile", basePatientDO.getMobile());
        rs.put("photo", basePatientDO.getPhoto());
        rs.put("address", basePatientDO.getAddress());
        if (patientMedicareCardDO != null) {
            rs.put("ssc", patientMedicareCardDO.getCode());
        } else {
            rs.put("ssc", "");
        }
        }
        return rs;
        return rs;
    }
    }
    public Map<String,Object> updatePatientInfo(String patient,String name,String idcard,String ssc,Integer sex,String townCode,String townName,String committeeCode,String committeeName,String address,String photo,String mobile,String province,String provinceName,String city,String cityName){
        Map<String,Object> rs = new HashedMap();
    public Map<String, Object> updatePatientInfo(String patient, String name, String idcard, String ssc, Integer sex, String townCode, String townName, String committeeCode, String committeeName, String address, String photo, String mobile, String province, String provinceName, String city, String cityName) {
        Map<String, Object> rs = new HashedMap();
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        BasePatientDO basePatientDO = basePatientDao.findById(patient);
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patient,"1");
        if (StringUtils.isNoneBlank(name)){
        PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01", patient, "1");
        if (StringUtils.isNoneBlank(name)) {
            basePatientDO.setName(name);
            basePatientDO.setName(name);
        }
        }
        if (StringUtils.isNoneBlank(idcard)){
        if (StringUtils.isNoneBlank(idcard)) {
            basePatientDO.setIdcard(idcard);
            basePatientDO.setIdcard(idcard);
        }
        }
        if (sex!=null){
        if (sex != null) {
            basePatientDO.setSex(sex);
            basePatientDO.setSex(sex);
        }
        }
        if (StringUtils.isNoneBlank(province)){
        if (StringUtils.isNoneBlank(province)) {
            basePatientDO.setProvinceCode(province);
            basePatientDO.setProvinceCode(province);
        }
        }
        if (StringUtils.isNoneBlank(provinceName)){
        if (StringUtils.isNoneBlank(provinceName)) {
            basePatientDO.setProvinceName(provinceName);
            basePatientDO.setProvinceName(provinceName);
        }
        }
        if (StringUtils.isNoneBlank(city)){
        if (StringUtils.isNoneBlank(city)) {
            basePatientDO.setCityCode(city);
            basePatientDO.setCityCode(city);
        }
        }
        if (StringUtils.isNoneBlank(cityName)){
        if (StringUtils.isNoneBlank(cityName)) {
            basePatientDO.setCityName(cityName);
            basePatientDO.setCityName(cityName);
        }
        }
        if (StringUtils.isNoneBlank(townCode)){
        if (StringUtils.isNoneBlank(townCode)) {
            basePatientDO.setTownCode(townCode);
            basePatientDO.setTownCode(townCode);
        }
        }
        if (StringUtils.isNoneBlank(townName)){
        if (StringUtils.isNoneBlank(townName)) {
            basePatientDO.setTownName(townName);
            basePatientDO.setTownName(townName);
        }
        }
        if (StringUtils.isNoneBlank(committeeCode)){
        if (StringUtils.isNoneBlank(committeeCode)) {
            basePatientDO.setCommitteeCode(committeeCode);
            basePatientDO.setCommitteeCode(committeeCode);
        }
        }
        if (StringUtils.isNoneBlank(committeeName)){
        if (StringUtils.isNoneBlank(committeeName)) {
            basePatientDO.setCommitteeName(committeeName);
            basePatientDO.setCommitteeName(committeeName);
        }
        }
        if (StringUtils.isNoneBlank(address)){
        if (StringUtils.isNoneBlank(address)) {
            basePatientDO.setAddress(address);
            basePatientDO.setAddress(address);
        }
        }
        if (StringUtils.isNoneBlank(photo)){
        if (StringUtils.isNoneBlank(photo)) {
            basePatientDO.setPhoto(photo);
            basePatientDO.setPhoto(photo);
        }
        }
        if (StringUtils.isNoneBlank(mobile)){
        if (StringUtils.isNoneBlank(mobile)) {
            basePatientDO.setMobile(mobile);
            basePatientDO.setMobile(mobile);
        }
        }
        basePatientDO = basePatientDao.save(basePatientDO);
        basePatientDO = basePatientDao.save(basePatientDO);
        if (patientMedicareCardDO!=null){
        if (patientMedicareCardDO != null) {
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO=basePatientMedicareCardDao.save(patientMedicareCardDO);
        }else {
            patientMedicareCardDO = basePatientMedicareCardDao.save(patientMedicareCardDO);
        } else {
            patientMedicareCardDO = new PatientMedicareCardDO();
            patientMedicareCardDO = new PatientMedicareCardDO();
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO.setCode(ssc);
            patientMedicareCardDO.setType("A_01");
            patientMedicareCardDO.setType("A_01");
            patientMedicareCardDO.setParentType("A");
            patientMedicareCardDO.setParentType("A");
            patientMedicareCardDO.setDel("1");
            patientMedicareCardDO.setDel("1");
            patientMedicareCardDO.setPatientCode(patient);
            patientMedicareCardDO.setPatientCode(patient);
            patientMedicareCardDO=basePatientMedicareCardDao.save(patientMedicareCardDO);
        }
        rs.put("id",patient);
        rs.put("name",basePatientDO.getName());
        rs.put("sex",basePatientDO.getSex());
        rs.put("provinceCode",basePatientDO.getProvinceCode());
        rs.put("provinceName",basePatientDO.getProvinceName());
        rs.put("cityCode",basePatientDO.getCityCode());
        rs.put("cityName",basePatientDO.getCityName());
        rs.put("townCode",basePatientDO.getTownCode());
        rs.put("townName",basePatientDO.getTownName());
        rs.put("idcard",basePatientDO.getIdcard());
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile",basePatientDO.getMobile());
        rs.put("photo",basePatientDO.getPhoto());
        rs.put("address",basePatientDO.getAddress());
        if (patientMedicareCardDO!=null){
            rs.put("ssc",patientMedicareCardDO.getCode());
        }else {
            rs.put("ssc","");
            patientMedicareCardDO = basePatientMedicareCardDao.save(patientMedicareCardDO);
        }
        rs.put("id", patient);
        rs.put("name", basePatientDO.getName());
        rs.put("sex", basePatientDO.getSex());
        rs.put("provinceCode", basePatientDO.getProvinceCode());
        rs.put("provinceName", basePatientDO.getProvinceName());
        rs.put("cityCode", basePatientDO.getCityCode());
        rs.put("cityName", basePatientDO.getCityName());
        rs.put("townCode", basePatientDO.getTownCode());
        rs.put("townName", basePatientDO.getTownName());
        rs.put("idcard", basePatientDO.getIdcard());
        rs.put("age", IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile", basePatientDO.getMobile());
        rs.put("photo", basePatientDO.getPhoto());
        rs.put("address", basePatientDO.getAddress());
        if (patientMedicareCardDO != null) {
            rs.put("ssc", patientMedicareCardDO.getCode());
        } else {
            rs.put("ssc", "");
        }
        }
        return rs;
        return rs;
    }
    }
    public Map<String,Object> getPatientInfoMap(BasePatientDO basePatientDO){
        Map<String,Object> rs = new HashedMap();
        rs.put("id",basePatientDO.getId());
        rs.put("name",basePatientDO.getName());
        rs.put("sex",basePatientDO.getSex());
        rs.put("provinceCode",basePatientDO.getProvinceCode());
        rs.put("provinceName",basePatientDO.getProvinceName());
        rs.put("cityCode",basePatientDO.getCityCode());
        rs.put("cityName",basePatientDO.getCityName());
        rs.put("townCode",basePatientDO.getTownCode());
        rs.put("townName",basePatientDO.getTownName());
        rs.put("idcard",basePatientDO.getIdcard());
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile",basePatientDO.getMobile());
    public Map<String, Object> getPatientInfoMap(BasePatientDO basePatientDO) {
        Map<String, Object> rs = new HashedMap();
        rs.put("id", basePatientDO.getId());
        rs.put("name", basePatientDO.getName());
        rs.put("sex", basePatientDO.getSex());
        rs.put("provinceCode", basePatientDO.getProvinceCode());
        rs.put("provinceName", basePatientDO.getProvinceName());
        rs.put("cityCode", basePatientDO.getCityCode());
        rs.put("cityName", basePatientDO.getCityName());
        rs.put("townCode", basePatientDO.getTownCode());
        rs.put("townName", basePatientDO.getTownName());
        rs.put("idcard", basePatientDO.getIdcard());
        rs.put("age", IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile", basePatientDO.getMobile());
        return rs;
        return rs;
    }
    }
@ -4491,18 +4670,18 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    @Autowired
    @Autowired
    private FileUploadService fileUploadService;
    private FileUploadService fileUploadService;
    public Map<String,Object> test() throws Exception{
    public Map<String, Object> test() throws Exception {
        entranceService.MS02014(false);
        entranceService.MS02014(false);
        return null;
        return null;
    }
    }
    public String test2(String no) throws Exception{
    public String test2(String no) throws Exception {
        TransRequest e = new TransRequest();
        TransRequest e = new TransRequest();
        e.setMethod("ehc.ehealthcard.auth.query");
        e.setMethod("ehc.ehealthcard.auth.query");
        e.setApp_id("1BQA48ETK000A718A8C000001FFAA482");
        e.setApp_id("1BQA48ETK000A718A8C000001FFAA482");
        e.setTerm_id("35020010001");
        e.setTerm_id("35020010001");
        e.setVersion("X.M.0.1");
        e.setVersion("X.M.0.1");
        e.setTimestamp(DateUtil.dateToStr(new Date(),"yyyyMMddHHmmss"));
        e.setTimestamp(DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss"));
        e.setSign_type("MD5");
        e.setSign_type("MD5");
        e.setEnc_type("AES");
        e.setEnc_type("AES");
        com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
@ -4516,21 +4695,21 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    /**
    /**
     * 获取正在进行中的视频复诊/协同门诊
     * 获取正在进行中的视频复诊/协同门诊
     *
     * @param doctor
     * @param doctor
     * @param general_doctor
     * @param general_doctor
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> getVideoPrescriptionByDoctor(String doctor,String general_doctor,String wxId) {
    public List<Map<String, Object>> getVideoPrescriptionByDoctor(String doctor, String general_doctor, String wxId) {
        String condition = "";
        String condition = "";
        if("xm_ykyy_wx".equals(wxId)){
            condition+= "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
        }else{
        if ("xm_ykyy_wx".equals(wxId)) {
            condition += "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
        } else {
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "room.patient_name AS \"name\"," +
@ -4539,7 +4718,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "patient.photo AS \"photo\"," +
                "patient.photo AS \"photo\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "patient.mobile AS \"mobile\"," +
                "room.consult_type AS \"consult_type\"," +condition +
                "room.consult_type AS \"consult_type\"," + condition +
                "room.reservation_type AS \"reservation_type\"," +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.description AS \"description\"," +
@ -4556,48 +4735,49 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND consult.relation_code=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND outpatient.pay_status=1 " +
                "AND outpatient.pay_status=1 " +
                "AND consult.status = 0 ";
                "AND consult.status = 0 ";
        if(StringUtils.isNoneBlank(doctor)){
            sql = sql +"AND room.doctor='"+doctor+"' " +
        if (StringUtils.isNoneBlank(doctor)) {
            sql = sql + "AND room.doctor='" + doctor + "' " +
                    "AND room.consult_type= 2";
                    "AND room.consult_type= 2";
        }else if(StringUtils.isNoneBlank(general_doctor)){
            sql = sql +"AND room.general_doctor='"+general_doctor+"' " +
        } else if (StringUtils.isNoneBlank(general_doctor)) {
            sql = sql + "AND room.general_doctor='" + general_doctor + "' " +
                    "AND room.consult_type= 2";
                    "AND room.consult_type= 2";
        }else{}
        } else {
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list != null && list.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            for(Map<String,Object> outpatient :list){
                String idcard = (String)outpatient.get("idcard");
                String patient_id = (String)outpatient.get("patient_id");
                outpatient.put("age",DateUtil.getAgeForIdcard(idcard));
                String outpatient_id = (String)outpatient.get("id");
                String isAlert = redisTemplate.opsForValue().get("patient_alert_"+patient_id);
                if(StringUtils.isBlank(isAlert)){
                    outpatient.put("alert_tag",0);//已提醒
                }else{
                    outpatient.put("alert_tag",1);//未提醒
            for (Map<String, Object> outpatient : list) {
                String idcard = (String) outpatient.get("idcard");
                String patient_id = (String) outpatient.get("patient_id");
                outpatient.put("age", DateUtil.getAgeForIdcard(idcard));
                String outpatient_id = (String) outpatient.get("id");
                String isAlert = redisTemplate.opsForValue().get("patient_alert_" + patient_id);
                if (StringUtils.isBlank(isAlert)) {
                    outpatient.put("alert_tag", 0);//已提醒
                } else {
                    outpatient.put("alert_tag", 1);//未提醒
                }
                }
                outpatient.put("online_tag",1);//未提醒
                outpatient.put("online_tag", 1);//未提醒
            }
            }
        }
        }
        return list;
        return list;
    }
    }
    public String generalDoctorWaitingNumber(String doctor,String wxId,String outpatientId){
    public String generalDoctorWaitingNumber(String doctor, String wxId, String outpatientId) {
        String condition = "";
        String condition = "";
        if("xm_ykyy_wx".equals(wxId)){
            condition+= "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            condition+= "to_char(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
        }else{
        if ("xm_ykyy_wx".equals(wxId)) {
            condition += "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            condition += "to_char(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
        } else {
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d' ) AS \"group_date\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d' ) AS \"group_date\",";
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "room.patient_name AS \"name\"," +
@ -4607,7 +4787,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "patient.birthday AS \"birthday\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "patient.mobile AS \"mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "room.consult_type AS \"consult_type\"," +condition+
                "room.consult_type AS \"consult_type\"," + condition +
                "room.reservation_type AS \"reservation_type\"," +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.description AS \"description\"," +
@ -4622,40 +4802,40 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND room.outpatient_id=outpatient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 " +
                "AND outpatient.status = 0 " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.pay_status = 1 " +
                "AND room.doctor='"+doctor+"' " +
                "AND room.doctor='" + doctor + "' " +
                "AND room.reservation_time is not null " +
                "AND room.reservation_time is not null " +
                "AND room.consult_type= 2 ";/* +
                "AND room.consult_type= 2 ";/* +
                "AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' order by room.reservation_time ASC ";
                "AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' order by room.reservation_time ASC ";
//                "AND room.reservation_time>='"+DateUtil.getStringDate("yyyy-MM-dd")+" 00:00:00"+"' ";*/
//                "AND room.reservation_time>='"+DateUtil.getStringDate("yyyy-MM-dd")+" 00:00:00"+"' ";*/
        if("xm_ykyy_wx".equals(wxId)){
            sql+=" AND room.reservation_time >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
        }else {
            sql +=" AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
        }
        sql+=" order by room.reservation_time ASC ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Integer waitCount =1;
        for (Map<String,Object> map:list){
            if (!map.get("id").toString().equalsIgnoreCase(outpatientId)){
                waitCount+=1;
            }else{
        if ("xm_ykyy_wx".equals(wxId)) {
            sql += " AND room.reservation_time >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
        } else {
            sql += " AND room.reservation_time >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
        }
        sql += " order by room.reservation_time ASC ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Integer waitCount = 1;
        for (Map<String, Object> map : list) {
            if (!map.get("id").toString().equalsIgnoreCase(outpatientId)) {
                waitCount += 1;
            } else {
                break;
                break;
            }
            }
        }
        }
        return waitCount.toString();
        return waitCount.toString();
    }
    }
    public com.alibaba.fastjson.JSONArray getWaitingForVisitVideoPrescriptionByDoctor(String doctor,String wxId) {
    public com.alibaba.fastjson.JSONArray getWaitingForVisitVideoPrescriptionByDoctor(String doctor, String wxId) {
        String condition = "";
        String condition = "";
        if("xm_ykyy_wx".equals(wxId)){
            condition+= "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            condition+= "to_char(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
        }else{
        if ("xm_ykyy_wx".equals(wxId)) {
            condition += "to_char(room.reservation_time,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            condition += "to_char(room.reservation_time,'YYYY-MM-DD')  AS \"group_date\",";
        } else {
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d %H:%i:%S' ) AS \"time\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d' ) AS \"group_date\",";
            condition += "date_format(room.reservation_time ,'%Y-%m-%d' ) AS \"group_date\",";
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                "room.outpatient_id AS \"id\"," +
                "room.outpatient_id AS \"id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_id AS \"patient_id\"," +
                "room.patient_name AS \"name\"," +
                "room.patient_name AS \"name\"," +
@ -4665,7 +4845,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "patient.birthday AS \"birthday\"," +
                "patient.birthday AS \"birthday\"," +
                "patient.mobile AS \"mobile\"," +
                "patient.mobile AS \"mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "outpatient.mobile AS \"outpatient_mobile\"," +
                "room.consult_type AS \"consult_type\"," +condition+
                "room.consult_type AS \"consult_type\"," + condition +
                "room.reservation_type AS \"reservation_type\"," +
                "room.reservation_type AS \"reservation_type\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.disease_img AS \"disease_img\"," +
                "outpatient.description AS \"description\"," +
                "outpatient.description AS \"description\"," +
@ -4680,61 +4860,61 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND room.outpatient_id=outpatient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 " +
                "AND outpatient.status = 0 " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.pay_status = 1 " +
                "AND room.doctor='"+doctor+"' " +
                "AND room.doctor='" + doctor + "' " +
                "AND room.reservation_time is not null " +
                "AND room.reservation_time is not null " +
                "AND room.consult_type= 2 ";/* +
                "AND room.consult_type= 2 ";/* +
                "AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' order by room.reservation_time ASC ";
                "AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' order by room.reservation_time ASC ";
//                "AND room.reservation_time>='"+DateUtil.getStringDate("yyyy-MM-dd")+" 00:00:00"+"' ";*/
//                "AND room.reservation_time>='"+DateUtil.getStringDate("yyyy-MM-dd")+" 00:00:00"+"' ";*/
        if("xm_ykyy_wx".equals(wxId)){
            sql+=" AND room.reservation_time >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
        }else {
            sql +=" AND room.reservation_time >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
        if ("xm_ykyy_wx".equals(wxId)) {
            sql += " AND room.reservation_time >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
        } else {
            sql += " AND room.reservation_time >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
        }
        }
        sql+=" order by room.reservation_time ASC ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        sql += " order by room.reservation_time ASC ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        Set<String> datelist = new HashSet<>();
        Set<String> datelist = new HashSet<>();
        HashMap<String,List<Map<String,Object>>> waitinglist = new HashMap<>();
        HashMap<String, List<Map<String, Object>>> waitinglist = new HashMap<>();
        if(list!=null&&list.size()>0){
        if (list != null && list.size() > 0) {
            //根据身份证计算年龄
            //根据身份证计算年龄
            for(Map<String,Object> outpatient :list){
                String idcard = (String)outpatient.get("idcard");
                String patient_id = (String)outpatient.get("patient_id");
                outpatient.put("age",DateUtil.getAgeForIdcard(idcard));
            for (Map<String, Object> outpatient : list) {
                String idcard = (String) outpatient.get("idcard");
                String patient_id = (String) outpatient.get("patient_id");
                outpatient.put("age", DateUtil.getAgeForIdcard(idcard));
                String group_date = (String)outpatient.get("group_date");
                String group_date = (String) outpatient.get("group_date");
                if(waitinglist.keySet().contains(group_date)){
                if (waitinglist.keySet().contains(group_date)) {
                    waitinglist.get(group_date).add(outpatient);
                    waitinglist.get(group_date).add(outpatient);
                }else{
                    List<Map<String,Object>> _cu = new ArrayList<>();
                } else {
                    List<Map<String, Object>> _cu = new ArrayList<>();
                    _cu.add(outpatient);
                    _cu.add(outpatient);
                    waitinglist.put(group_date,_cu);
                    waitinglist.put(group_date, _cu);
                }
                }
                //全科医生来源
                //全科医生来源
                outpatient.put("general_doctor_info","");//全科医生名字
                outpatient.put("general_doctor_hospital","");//全科医生社区
                String isAlert = redisTemplate.opsForValue().get("patient_alert_"+patient_id);
                if(StringUtils.isBlank(isAlert)){
                    outpatient.put("alert_tag",0);//已提醒
                }else{
                    outpatient.put("alert_tag",1);//未提醒
                outpatient.put("general_doctor_info", "");//全科医生名字
                outpatient.put("general_doctor_hospital", "");//全科医生社区
                String isAlert = redisTemplate.opsForValue().get("patient_alert_" + patient_id);
                if (StringUtils.isBlank(isAlert)) {
                    outpatient.put("alert_tag", 0);//已提醒
                } else {
                    outpatient.put("alert_tag", 1);//未提醒
                }
                }
                outpatient.put("online_tag",1);//在线状态
                outpatient.put("online_tag", 1);//在线状态
                String outpatient_mobile = (String)outpatient.get("outpatient_mobile");
                if(StringUtils.isNoneBlank(outpatient_mobile)){
                    outpatient.put("mobile",outpatient_mobile);//复诊有手机号,传递复诊手机号
                String outpatient_mobile = (String) outpatient.get("outpatient_mobile");
                if (StringUtils.isNoneBlank(outpatient_mobile)) {
                    outpatient.put("mobile", outpatient_mobile);//复诊有手机号,传递复诊手机号
                }
                }
            }
            }
        }
        }
        Collection<String> keyset= waitinglist.keySet();
        Collection<String> keyset = waitinglist.keySet();
        List<String> _list = new ArrayList<String>(keyset);
        List<String> _list = new ArrayList<String>(keyset);
        //对key键值按字典升序排序
        //对key键值按字典升序排序
@ -4744,12 +4924,12 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        for (int i = 0; i < _list.size(); i++) {
        for (int i = 0; i < _list.size(); i++) {
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            if(_list.get(i).equals(DateUtil.getStringDateShort())){
                object.put("day","today");
            }else{
                object.put("day",_list.get(i));
            if (_list.get(i).equals(DateUtil.getStringDateShort())) {
                object.put("day", "today");
            } else {
                object.put("day", _list.get(i));
            }
            }
            object.put("data",waitinglist.get(_list.get(i)));
            object.put("data", waitinglist.get(_list.get(i)));
            result.add(object);
            result.add(object);
        }
        }
        return result;
        return result;
@ -4757,14 +4937,15 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 医生抢单(视频)
     * 医生抢单(视频)
     *
     * @param outpatientCode
     * @param outpatientCode
     * @param doctor
     * @param doctor
     */
     */
    public void pickVideoPrescripitonWaitingPeople(String outpatientCode, String doctor) throws Exception{
    public void pickVideoPrescripitonWaitingPeople(String outpatientCode, String doctor) throws Exception {
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        List<WlyyHospitalWaitingRoomDO> roomDOs =hospitalWaitingRoomDao.findByOutpatientId(outpatientCode);
        if(roomDOs!=null&&roomDOs.size()>0){
            for(WlyyHospitalWaitingRoomDO roomDO:roomDOs){
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientCode);
        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO roomDO : roomDOs) {
                roomDO.setDoctor(doctor);
                roomDO.setDoctor(doctor);
                roomDO.setDoctorName(baseDoctorDO.getName());
                roomDO.setDoctorName(baseDoctorDO.getName());
                hospitalWaitingRoomDao.save(roomDO);
                hospitalWaitingRoomDao.save(roomDO);
@ -4779,14 +4960,15 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 复诊视频咨询人数, 协同门诊人数
     * 复诊视频咨询人数, 协同门诊人数
     *
     * @param doctor
     * @param doctor
     * @param outpatient_type 1复诊 2协同
     * @param outpatient_type 1复诊 2协同
     * @return
     * @return
     */
     */
    public Long doctorIndexConsultCount(String doctor,String outpatient_type) {
    public Long doctorIndexConsultCount(String doctor, String outpatient_type) {
        String sql ="SELECT " +
        String sql = "SELECT " +
                "count(room.outpatient_id) AS total " +
                "count(room.outpatient_id) AS total " +
                "FROM " +
                "FROM " +
                "wlyy_hospital_waiting_room room," +
                "wlyy_hospital_waiting_room room," +
@ -4798,18 +4980,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "AND room.outpatient_id=outpatient.id " +
                "AND room.outpatient_id=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND consult.relation_code=outpatient.id " +
                "AND consult.status = 0 " +
                "AND consult.status = 0 " +
                "AND outpatient_type.doctor='"+outpatient_type+"'" +
                "AND room.doctor='"+doctor+"' ";
        if("1".equals(outpatient_type)){
                "AND outpatient_type.doctor='" + outpatient_type + "'" +
                "AND room.doctor='" + doctor + "' ";
        if ("1".equals(outpatient_type)) {
            sql = sql + " AND room.consult_type= 2 ";
            sql = sql + " AND room.consult_type= 2 ";
        }else if("2".equals(outpatient_type)){
        }else{}
        } else if ("2".equals(outpatient_type)) {
        } else {
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long videoOnlineCount = 0l;
        Long videoOnlineCount = 0l;
        if (rstotal != null && rstotal.size() > 0) {
        if (rstotal != null && rstotal.size() > 0) {
            videoOnlineCount = Long.parseLong(rstotal.get(0).get("total").toString()) ;
            videoOnlineCount = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        }
        return videoOnlineCount;
        return videoOnlineCount;
@ -4819,37 +5002,38 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 根据门诊唯一号,处方号,到顺丰下单,下单成功返回面单信息
     * 根据门诊唯一号,处方号,到顺丰下单,下单成功返回面单信息
     * @param admNo 门诊唯一号
     *
     * @param admNo     门诊唯一号
     * @param realOrder 处方号
     * @param realOrder 处方号
     * @return
     * @return
     */
     */
    public Object getSFExpressInfo(String admNo,String realOrder,String wxId)throws Exception {
    public Object getSFExpressInfo(String admNo, String realOrder, String wxId) throws Exception {
        //根据门诊唯一号取就诊记录
        //根据门诊唯一号取就诊记录
//        List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByAdmNo(admNo);
//        List<WlyyOutpatientDO> wlyyOutpatientDOs = outpatientDao.findByAdmNo(admNo);
        WlyyPrescriptionDO wlyyPrescriptionDOS = prescriptionDao.findByAdmNoAndRealOrder(admNo,realOrder);
        WlyyPrescriptionDO wlyyPrescriptionDOS = prescriptionDao.findByAdmNoAndRealOrder(admNo, realOrder);
        Object result = "";
        Object result = "";
        System.out.println("获取顺丰物流面单信息:wlyyPrescriptionDOS != null="+wlyyPrescriptionDOS != null);
        if(wlyyPrescriptionDOS != null){
            List<WlyyPrescriptionExpressageDO> expressageDOList = sfexpressService.findByField("outpatientId",wlyyPrescriptionDOS.getOutpatientId());
        System.out.println("获取顺丰物流面单信息:wlyyPrescriptionDOS != null=" + wlyyPrescriptionDOS != null);
        if (wlyyPrescriptionDOS != null) {
            List<WlyyPrescriptionExpressageDO> expressageDOList = sfexpressService.findByField("outpatientId", wlyyPrescriptionDOS.getOutpatientId());
            WlyyPrescriptionExpressageDO sfexpress_obj = null;
            WlyyPrescriptionExpressageDO sfexpress_obj = null;
            System.out.println("获取顺丰物流面单信息:CollectionUtils.isEmpty(expressageDOList)="+CollectionUtils.isEmpty(expressageDOList));
            if(CollectionUtils.isEmpty(expressageDOList)){
            System.out.println("获取顺丰物流面单信息:CollectionUtils.isEmpty(expressageDOList)=" + CollectionUtils.isEmpty(expressageDOList));
            if (CollectionUtils.isEmpty(expressageDOList)) {
                throw new Exception("顺丰快递下单失败,未找到该处方的派送地址!");
                throw new Exception("顺丰快递下单失败,未找到该处方的派送地址!");
            }else{
            } else {
                System.out.println("获取顺丰物流面单信息:1");
                System.out.println("获取顺丰物流面单信息:1");
                sfexpress_obj = expressageDOList.get(0);
                sfexpress_obj = expressageDOList.get(0);
                System.out.println("获取顺丰物流面单信息:2");
                System.out.println("获取顺丰物流面单信息:2");
                BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDOS.getPatientCode());
                BasePatientDO basePatientDO = basePatientDao.findById(wlyyPrescriptionDOS.getPatientCode());
                //如果该处方的快递单号已生成,则说明已经下单成功,不需要重复下单,直接返回面单信息
                //如果该处方的快递单号已生成,则说明已经下单成功,不需要重复下单,直接返回面单信息
                System.out.println("获取顺丰物流面单信息:3");
                System.out.println("获取顺丰物流面单信息:3");
                if(org.apache.commons.lang.StringUtils.isNotBlank(sfexpress_obj.getMailno())){
                if (org.apache.commons.lang.StringUtils.isNotBlank(sfexpress_obj.getMailno())) {
                    //处方已下单成功
                    //处方已下单成功
                    System.out.println("获取顺丰物流面单信息:4");
                    System.out.println("获取顺丰物流面单信息:4");
                }else{
                } else {
                    //如果该处方的快递单号未生成,则继续下单
                    //如果该处方的快递单号未生成,则继续下单
                    //根据业务订单号判断是否已经下单成功
                    //根据业务订单号判断是否已经下单成功
                    //--2020.05.20--顺丰V2.0接口已不提供查询接口,直接单下单--START
                    //--2020.05.20--顺丰V2.0接口已不提供查询接口,直接单下单--START
@ -4873,19 +5057,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                }
                }
                if(sfexpress_obj != null && StringUtils.isNoneBlank(sfexpress_obj.getMailno())){
                if (sfexpress_obj != null && StringUtils.isNoneBlank(sfexpress_obj.getMailno())) {
                    System.out.println("获取顺丰物流面单信息:7");
                    System.out.println("获取顺丰物流面单信息:7");
                    com.alibaba.fastjson.JSONObject sfJsonObject = new com.alibaba.fastjson.JSONObject();
                    com.alibaba.fastjson.JSONObject sfJsonObject = new com.alibaba.fastjson.JSONObject();
                    sfJsonObject.put("mailno", sfexpress_obj.getMailno());
                    sfJsonObject.put("mailno", sfexpress_obj.getMailno());
                    sfJsonObject.put("mailtype", "标准快递");
                    sfJsonObject.put("mailtype", "标准快递");
                    sfJsonObject.put("destcode", "592");
                    sfJsonObject.put("destcode", "592");
                    if(wxId.equalsIgnoreCase("xm_zsyy_wx")){
                    if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                        sfJsonObject.put("j_address", "湖滨南路201-209号");
                    }else if (wxId.equalsIgnoreCase("xm_ykyy_wx")){
                    } else if (wxId.equalsIgnoreCase("xm_ykyy_wx")) {
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_name", "厦门大学附属中山医院");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_phone", "4003008888");
                        sfJsonObject.put("j_townName", "思明区");
                        sfJsonObject.put("j_townName", "思明区");
@ -4899,11 +5083,11 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    sfJsonObject.put("d_cityName", sfexpress_obj.getCityName());
                    sfJsonObject.put("d_cityName", sfexpress_obj.getCityName());
                    sfJsonObject.put("d_townName", sfexpress_obj.getTownName());
                    sfJsonObject.put("d_townName", sfexpress_obj.getTownName());
                    sfJsonObject.put("d_address", sfexpress_obj.getAddress());
                    sfJsonObject.put("d_address", sfexpress_obj.getAddress());
                    sfJsonObject.put("d_phone",sfexpress_obj.getMobile());
                    sfJsonObject.put("express_type",11);
                    sfJsonObject.put("pay_method",2);
                    sfJsonObject.put("receive_time","");
                    sfJsonObject.put("dispensaryType",2);
                    sfJsonObject.put("d_phone", sfexpress_obj.getMobile());
                    sfJsonObject.put("express_type", 11);
                    sfJsonObject.put("pay_method", 2);
                    sfJsonObject.put("receive_time", "");
                    sfJsonObject.put("dispensaryType", 2);
                    result = sfJsonObject;
                    result = sfJsonObject;
                    System.out.println("获取顺丰物流面单信息:8");
                    System.out.println("获取顺丰物流面单信息:8");
                }
                }
@ -4915,13 +5099,14 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 根据类型获取候诊居民数量
     * 根据类型获取候诊居民数量
     *
     * @param doctor
     * @param doctor
     * @param outpatient_type 1复诊  2协同
     * @param outpatient_type 1复诊  2协同
     * @param type 1图文 2视频
     * @param type            1图文 2视频
     * @return
     * @return
     */
     */
    public Long getWaitVideoCount(String doctor,String type,String outpatient_type,String wxId) {
        String sql ="SELECT " +
    public Long getWaitVideoCount(String doctor, String type, String outpatient_type, String wxId) {
        String sql = "SELECT " +
                "count(outpatient.id) AS \"total\" " +
                "count(outpatient.id) AS \"total\" " +
                "FROM " +
                "FROM " +
                "wlyy_outpatient outpatient," +
                "wlyy_outpatient outpatient," +
@ -4929,24 +5114,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "WHERE " +
                "WHERE " +
                "outpatient.patient=patient.id " +
                "outpatient.patient=patient.id " +
                "AND outpatient.status in (0,1) " +
                "AND outpatient.status in (0,1) " +
                "AND outpatient.doctor='"+doctor+"' " +
                "AND outpatient.doctor='" + doctor + "' " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.pay_status = 1 " +
                "AND outpatient.outpatient_type= '"+outpatient_type+"'  ";
        if("1".equals(outpatient_type)){//复诊
            sql =  sql + " AND outpatient.type= '"+type+"' ";
            if("2".equals(type)){//视频复诊才需要判断时间,
                if("xm_ykyy_wx".equals(wxId)){
                    sql +=" AND outpatient.register_date is not null and outpatient.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                }else {
                    sql =  sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
                "AND outpatient.outpatient_type= '" + outpatient_type + "'  ";
        if ("1".equals(outpatient_type)) {//复诊
            sql = sql + " AND outpatient.type= '" + type + "' ";
            if ("2".equals(type)) {//视频复诊才需要判断时间,
                if ("xm_ykyy_wx".equals(wxId)) {
                    sql += " AND outpatient.register_date is not null and outpatient.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
                } else {
                    sql = sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
                }
                }
            }
            }
        }else if("2".equals(outpatient_type)){
        } else if ("2".equals(outpatient_type)) {
            //协同门诊也需要判断时间
            //协同门诊也需要判断时间
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" AND outpatient.register_date is not null and outpatient.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sql =  sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' ";
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " AND outpatient.register_date is not null and outpatient.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql = sql + " AND outpatient.register_date is not null AND  outpatient.register_date >= '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' ";
            }
            }
        }
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
@ -4961,15 +5146,16 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 保存在线排班
     * 保存在线排班
     *
     * @param onlineWorkJson
     * @param onlineWorkJson
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Envelop saveDoctorOnlineWork(String onlineWorkJson)throws Exception{
        WlyyDoctorOnlineTimeDO timeDO = objectMapper.readValue(onlineWorkJson,WlyyDoctorOnlineTimeDO.class);
        List<WlyyDoctorOnlineTimeDO> list = wlyyDoctorOnlineTimeDao.findWorkExistList(timeDO.getDoctor(),timeDO.getStartTime(),timeDO.getEndTime());
        if(list!=null&&list.size()>0){
            return Envelop.getError("排班已存在",-1);
    public Envelop saveDoctorOnlineWork(String onlineWorkJson) throws Exception {
        WlyyDoctorOnlineTimeDO timeDO = objectMapper.readValue(onlineWorkJson, WlyyDoctorOnlineTimeDO.class);
        List<WlyyDoctorOnlineTimeDO> list = wlyyDoctorOnlineTimeDao.findWorkExistList(timeDO.getDoctor(), timeDO.getStartTime(), timeDO.getEndTime());
        if (list != null && list.size() > 0) {
            return Envelop.getError("排班已存在", -1);
        }
        }
        timeDO.setCreateTime(new Date());
        timeDO.setCreateTime(new Date());
        return Envelop.getSuccess("保存成功");
        return Envelop.getSuccess("保存成功");
@ -4977,36 +5163,39 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 删除在线排班
     * 删除在线排班
     *
     * @param id
     * @param id
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public Envelop delDoctorOnlineWork(String id)throws Exception{
    public Envelop delDoctorOnlineWork(String id) throws Exception {
        wlyyDoctorOnlineTimeDao.delete(id);
        wlyyDoctorOnlineTimeDao.delete(id);
        return Envelop.getSuccess("删除成功");
        return Envelop.getSuccess("删除成功");
    }
    }
    /**
    /**
     * 查询医生在线排班
     * 查询医生在线排班
     *
     * @param doctor
     * @param doctor
     * @param startDate
     * @param startDate
     * @param endDate
     * @param endDate
     * @return
     * @return
     */
     */
    public List<WlyyDoctorOnlineTimeDO> findDoctorOnlineWorkList(String doctor,String startDate,String endDate){
        return wlyyDoctorOnlineTimeDao.findWorkList(doctor,DateUtil.stringToDate(startDate+" 00:00:00","yyyy-MM-dd HH:mm:ss"),DateUtil.stringToDate(endDate+" 23:59:59","yyyy-MM-dd HH:mm:ss"));
    public List<WlyyDoctorOnlineTimeDO> findDoctorOnlineWorkList(String doctor, String startDate, String endDate) {
        return wlyyDoctorOnlineTimeDao.findWorkList(doctor, DateUtil.stringToDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss"), DateUtil.stringToDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
    }
    }
    /**
    /**
     * 发起图文和视频协同门诊复诊
     * 发起图文和视频协同门诊复诊
     *
     * @param outpatientJson
     * @param outpatientJson
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public WlyyOutpatientDO cooperativeOutpatient(String outpatientJson,String registerJson,String chargeType)throws Exception{
    public WlyyOutpatientDO cooperativeOutpatient(String outpatientJson, String registerJson, String chargeType) throws Exception {
        //1.保存就诊实体
        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson,WlyyOutpatientDO.class);
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        BasePatientDO patientDO = basePatientDao.findById(outpatientDO.getPatient());
        outpatientDO.setMjz("mz");
        outpatientDO.setMjz("mz");
@ -5016,7 +5205,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        outpatientDO.setOutpatientType("2");
        outpatientDO.setOutpatientType("2");
        outpatientDO.setCreateTime(new Date());
        outpatientDO.setCreateTime(new Date());
        if(outpatientDO.getRegisterDate()==null){
        if (outpatientDO.getRegisterDate() == null) {
            outpatientDO.setRegisterDate(new Date());
            outpatientDO.setRegisterDate(new Date());
        }
        }
@ -5026,48 +5215,49 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        try {
        try {
            //如果是视频预约咨询
            //如果是视频预约咨询
            if(StringUtils.isNotBlank(registerJson)){
                registerTimeDO = objectMapper.readValue(registerJson,WlyyPatientRegisterTimeDO.class);
            if (StringUtils.isNotBlank(registerJson)) {
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                registerTimeDO.setCreateTime(new Date());
                patientRegisterTimeDao.save(registerTimeDO);
                patientRegisterTimeDao.save(registerTimeDO);
            }
            }
        }catch (Exception e){
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约,请选择其他号源");
            throw new RuntimeException("号源已经被预约,请选择其他号源");
        }
        }
        //3.创建候诊室
        //3.创建候诊室
        createRoom(outpatient,chargeType);
        createRoom(outpatient, chargeType);
        return outpatient;
        return outpatient;
    }
    }
    /**
    /**
     * 发送新增门诊信息
     * 发送新增门诊信息
     *
     * @param outpatient
     * @param outpatient
     * @return
     * @return
     */
     */
    public SystemMessageDO sendOutPatientMes(WlyyOutpatientDO outpatient){
    public SystemMessageDO sendOutPatientMes(WlyyOutpatientDO outpatient) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        String msg="";
        String msg = "";
        JSONObject data = new JSONObject();
        JSONObject data = new JSONObject();
        try{
        try {
            //1.在线复诊2.协同门诊
            //1.在线复诊2.协同门诊
            if("2".equals(outpatient.getOutpatientType())){
            if ("2".equals(outpatient.getOutpatientType())) {
                systemMessageDO.setTitle("协同门诊");
                systemMessageDO.setTitle("协同门诊");
                systemMessageDO.setType("3");
                systemMessageDO.setType("3");
            }else{
            } else {
                //1.图文 2.视频
                //1.图文 2.视频
                if("1".equals(outpatient.getType())){
                if ("1".equals(outpatient.getType())) {
                    systemMessageDO.setTitle("图文复诊");
                    systemMessageDO.setTitle("图文复诊");
                    systemMessageDO.setType("1");
                    systemMessageDO.setType("1");
                    saveInquirySystemMessage(outpatient);
                    saveInquirySystemMessage(outpatient);
                }else {
                } else {
                    systemMessageDO.setTitle("视频复诊预约成功");
                    systemMessageDO.setTitle("视频复诊预约成功");
                    systemMessageDO.setType("2");
                    systemMessageDO.setType("2");
                    saveInquirySystemMessage(outpatient);
                    saveInquirySystemMessage(outpatient);
                    msg="您的视频复诊已预约成功。\n" +
                            "预计"+outpatient.getDoctorName()+"医生将于"+outpatient.getRegisterDate()+" 与您进行视频咨询。请留意系统消息或微信公众号消息。咨询开始时,医生将邀请您进行视频通话,请您关注消息提醒,及时接受医生视频邀请。";
                    msg = "您的视频复诊已预约成功。\n" +
                            "预计" + outpatient.getDoctorName() + "医生将于" + outpatient.getRegisterDate() + " 与您进行视频咨询。请留意系统消息或微信公众号消息。咨询开始时,医生将邀请您进行视频通话,请您关注消息提醒,及时接受医生视频邀请。";
                    systemMessageDO.setReceiver(outpatient.getDoctor());
                    systemMessageDO.setReceiver(outpatient.getDoctor());
                    systemMessageDO.setReceiverName(outpatient.getDoctorName());
                    systemMessageDO.setReceiverName(outpatient.getDoctorName());
                    systemMessageDO.setRelationCode(outpatient.getId());
                    systemMessageDO.setRelationCode(outpatient.getId());
@ -5076,39 +5266,39 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    systemMessageDO.setRelationCode(outpatient.getId());
                    systemMessageDO.setRelationCode(outpatient.getId());
                    data.put("name",outpatient.getPatientName());
                    data.put("age",IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
                    data.put("gender",IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
                    data.put("question",outpatient.getDescription());
                    data.put("msg",msg);
                    data.put("name", outpatient.getPatientName());
                    data.put("age", IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
                    data.put("gender", IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
                    data.put("question", outpatient.getDescription());
                    data.put("msg", msg);
                    systemMessageDO.setData(data.toString());
                    systemMessageDO.setData(data.toString());
                    systemMessageService.saveMessage(systemMessageDO);
                    systemMessageService.saveMessage(systemMessageDO);
                    sendWxTemplateMsg(wechatId, outpatient.getId(), "17", "videoOrderRemind", null);
                }
                }
            }
            }
            BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
            BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                ykyyService.pushNotificationToYktPatient(patient.getYktId(),systemMessageDO.getTitle(),data.get("msg").toString());
            if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
            }
            }
        }catch (Exception e){
            logger.error("sendOutPatientMes :"+e.toString());
        } catch (Exception e) {
            logger.error("sendOutPatientMes :" + e.toString());
            return null;
            return null;
        }
        }
        return systemMessageDO;
        return systemMessageDO;
    }
    }
    public void saveInquirySystemMessage(WlyyOutpatientDO outpatient){
    public void saveInquirySystemMessage(WlyyOutpatientDO outpatient) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        String msg="";
        String type="";
        if("1".equals(outpatient.getType())){
            type="9";
            msg=outpatient.getPatientName()+",您好!您有一个图文复诊订单待支付,请及时支付。点击完成支付,如您已支付请忽略本条信息。";
        }else {
            type="16";
            msg=outpatient.getPatientName()+",您好!您有一个视频复诊订单待支付,请及时支付。点击完成支付,如您已支付请忽略本条信息。";
        String msg = "";
        String type = "";
        if ("1".equals(outpatient.getType())) {
            type = "9";
            msg = outpatient.getPatientName() + ",您好!您有一个图文复诊订单待支付,请及时支付。点击完成支付,如您已支付请忽略本条信息。";
        } else {
            type = "16";
            msg = outpatient.getPatientName() + ",您好!您有一个视频复诊订单待支付,请及时支付。点击完成支付,如您已支付请忽略本条信息。";
        }
        }
        systemMessageDO.setTitle("支付提醒");
        systemMessageDO.setTitle("支付提醒");
@ -5121,37 +5311,39 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        JSONObject data = new JSONObject();
        JSONObject data = new JSONObject();
        try {
        try {
            data.put("name",outpatient.getPatientName());
            data.put("age",IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
            data.put("gender",IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
            data.put("question",outpatient.getDescription());
            data.put("msg",msg);
            data.put("type",type);
            data.put("name", outpatient.getPatientName());
            data.put("age", IdCardUtil.getAgeForIdcard(outpatient.getIdcard()));
            data.put("gender", IdCardUtil.getSexForIdcard_new(outpatient.getIdcard()));
            data.put("question", outpatient.getDescription());
            data.put("msg", msg);
            data.put("type", type);
            systemMessageDO.setData(data.toString());
            systemMessageDO.setData(data.toString());
            systemMessageService.saveMessage(systemMessageDO);
            systemMessageService.saveMessage(systemMessageDO);
        } catch (Exception e) {
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        }
        BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
        BasePatientDO patient = basePatientDao.findById(outpatient.getPatient());
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            ykyyService.pushNotificationToYktPatient(patient.getYktId(),systemMessageDO.getTitle(),data.get("msg").toString());
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            ykyyService.pushNotificationToYktPatient(patient.getYktId(), systemMessageDO.getTitle(), data.get("msg").toString());
        }
        }
        sendWxTemplateMsg(wechatId, outpatient.getId(), type, "payRemind", null);
    }
    }
    /**
    /**
     * 指定门诊医生医生
     * 指定门诊医生医生
     *
     * @param outpatientJson
     * @param outpatientJson
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public WlyyOutpatientDO saveOutpatientDoctor(String outpatientJson,String registerJson,String chargeType)throws Exception{
    public WlyyOutpatientDO saveOutpatientDoctor(String outpatientJson, String registerJson, String chargeType) throws Exception {
        //1.保存就诊实体
        //1.保存就诊实体
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson,WlyyOutpatientDO.class);
        WlyyOutpatientDO outpatientDO = objectMapper.readValue(outpatientJson, WlyyOutpatientDO.class);
        WlyyOutpatientDO one = outpatientDao.findOne(outpatientDO.getId());
        WlyyOutpatientDO one = outpatientDao.findOne(outpatientDO.getId());
        if(StringUtils.isNotBlank(one.getDoctor())){
        if (StringUtils.isNotBlank(one.getDoctor())) {
            throw new RuntimeException("已有医生接诊");
            throw new RuntimeException("已有医生接诊");
        }
        }
        one.setDoctor(outpatientDO.getDoctor());
        one.setDoctor(outpatientDO.getDoctor());
@ -5166,27 +5358,27 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        try {
        try {
            //如果是视频预约咨询
            //如果是视频预约咨询
            if(StringUtils.isNotBlank(registerJson)){
            if (StringUtils.isNotBlank(registerJson)) {
                //删除预约记录
                //删除预约记录
                List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientDO.getId());
                List<WlyyPatientRegisterTimeDO> registerTimeDOs = patientRegisterTimeDao.findByOutpatientId(outpatientDO.getId());
                if(registerTimeDOs!=null&&registerTimeDOs.size()>0){
                if (registerTimeDOs != null && registerTimeDOs.size() > 0) {
                    patientRegisterTimeDao.delete(registerTimeDOs);
                    patientRegisterTimeDao.delete(registerTimeDOs);
                }
                }
                registerTimeDO = objectMapper.readValue(registerJson,WlyyPatientRegisterTimeDO.class);
                registerTimeDO = objectMapper.readValue(registerJson, WlyyPatientRegisterTimeDO.class);
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setOutpatientId(outpatient.getId());
                registerTimeDO.setCreateTime(new Date());
                registerTimeDO.setCreateTime(new Date());
                patientRegisterTimeDao.save(registerTimeDO);
                patientRegisterTimeDao.save(registerTimeDO);
            }
            }
        }catch (Exception e){
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约,请选择其他号源");
            throw new RuntimeException("号源已经被预约,请选择其他号源");
        }
        }
        //更新候诊室
        //更新候诊室
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientDO.getId());
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outpatientDO.getId());
        if(roomDOs!=null&&roomDOs.size()>0){
            for(WlyyHospitalWaitingRoomDO room:roomDOs){
        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO room : roomDOs) {
                room.setDept(outpatientDO.getDept());
                room.setDept(outpatientDO.getDept());
                room.setDeptName(outpatientDO.getDeptName());
                room.setDeptName(outpatientDO.getDeptName());
                room.setDoctor(outpatientDO.getDoctor());
                room.setDoctor(outpatientDO.getDoctor());
@ -5201,12 +5393,13 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 验证电子健康卡授权
     * 验证电子健康卡授权
     *
     * @param authorizeNo
     * @param authorizeNo
     * @return
     * @return
     */
     */
    public Map<String,Object> checkOauthQRCode(String authorizeNo){
    public Map<String, Object> checkOauthQRCode(String authorizeNo) {
        Map<String,Object> rsMap = new HashedMap();
        Map<String, Object> rsMap = new HashedMap();
        OauthYlzConfigDO oauthYlzConfigDO = oauthYlzConfigDao.findOne("ylz_config");
        OauthYlzConfigDO oauthYlzConfigDO = oauthYlzConfigDao.findOne("ylz_config");
        try {
        try {
            TransRequest e = new TransRequest();
            TransRequest e = new TransRequest();
@ -5214,7 +5407,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            e.setApp_id(oauthYlzConfigDO.getAppId());
            e.setApp_id(oauthYlzConfigDO.getAppId());
            e.setTerm_id(oauthYlzConfigDO.getTermId());
            e.setTerm_id(oauthYlzConfigDO.getTermId());
            e.setVersion(oauthYlzConfigDO.getVersion());
            e.setVersion(oauthYlzConfigDO.getVersion());
            e.setTimestamp(DateUtil.dateToStr(new Date(),"yyyyMMddHHmmss"));
            e.setTimestamp(DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss"));
            e.setSign_type(oauthYlzConfigDO.getSignType());
            e.setSign_type(oauthYlzConfigDO.getSignType());
            e.setEnc_type(oauthYlzConfigDO.getEncType());
            e.setEnc_type(oauthYlzConfigDO.getEncType());
            com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
            com.alibaba.fastjson.JSONObject bizContent = new com.alibaba.fastjson.JSONObject();
@ -5225,23 +5418,23 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            TransResponse re = ehcHandler.execute(e);
            TransResponse re = ehcHandler.execute(e);
            String rs = com.alibaba.fastjson.JSONObject.toJSONString(re);
            String rs = com.alibaba.fastjson.JSONObject.toJSONString(re);
            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.parse(rs);
            com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.parse(rs);
            logger.info("checkOauthQRCode:"+rs);
            logger.info("checkOauthQRCode:" + rs);
            String ret_code = json.getString("ret_code");
            String ret_code = json.getString("ret_code");
            if("0000".equals(ret_code)){
                logger.info("biz_content: "+json.getString("biz_content"));
            if ("0000".equals(ret_code)) {
                logger.info("biz_content: " + json.getString("biz_content"));
                String strBiz = json.getString("biz_content");
                String strBiz = json.getString("biz_content");
                com.alibaba.fastjson.JSONObject biz = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.parse(strBiz);
                com.alibaba.fastjson.JSONObject biz = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.parse(strBiz);
//                com.alibaba.fastjson.JSONObject biz = json.getJSONObject("biz_content");
//                com.alibaba.fastjson.JSONObject biz = json.getJSONObject("biz_content");
                String  auth_status = biz.getString("auth_status");
                if("succ".equals(auth_status)){
                String auth_status = biz.getString("auth_status");
                if ("succ".equals(auth_status)) {
                    String idcard = biz.getString("id_no");
                    String idcard = biz.getString("id_no");
                    BasePatientDO patientDO =  basePatientDao.findByIdcardAndDel(idcard,"1");
                    if(patientDO == null){
                    BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(idcard, "1");
                    if (patientDO == null) {
                        BasePatientDO patient = new BasePatientDO();
                        BasePatientDO patient = new BasePatientDO();
                        String salt = UUID.randomUUID().toString().substring(0,5);
                        String salt = UUID.randomUUID().toString().substring(0, 5);
                        String mobile = biz.getString("mobile_phone");
                        String mobile = biz.getString("mobile_phone");
                        String pw = mobile.substring(mobile.length()-6);
                        String pw = mobile.substring(mobile.length() - 6);
                        patient.setIdcard(idcard);
                        patient.setIdcard(idcard);
                        patient.setName(biz.getString("user_name"));
                        patient.setName(biz.getString("user_name"));
@ -5253,79 +5446,80 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                        patient.setLocked(0);
                        patient.setLocked(0);
                        patient.setCreateTime(new Date());
                        patient.setCreateTime(new Date());
                        patient.setUpdateTime(new Date());
                        patient.setUpdateTime(new Date());
                        patient.setBirthday(DateUtil.strToDate(biz.getString("birthday"),"yyyyMMdd"));
                        patient.setBirthday(DateUtil.strToDate(biz.getString("birthday"), "yyyyMMdd"));
                        basePatientDao.save(patient);
                        basePatientDao.save(patient);
                        rsMap.put("sCode",auth_status);
                        rsMap.put("sMes","success");
                        rsMap.put("patient",getPatientInfoMap(patient));
                        rsMap.put("sCode", auth_status);
                        rsMap.put("sMes", "success");
                        rsMap.put("patient", getPatientInfoMap(patient));
                        return rsMap;
                        return rsMap;
                    }else{
                        rsMap.put("sCode",auth_status);
                        rsMap.put("sMes","success");
                        rsMap.put("patient",getPatientInfoMap(patientDO));
                    } else {
                        rsMap.put("sCode", auth_status);
                        rsMap.put("sMes", "success");
                        rsMap.put("patient", getPatientInfoMap(patientDO));
                        return rsMap;
                        return rsMap;
                    }
                    }
                }else if("ing".equals(auth_status)){
                    rsMap.put("sCode",auth_status);
                    rsMap.put("sMes","正在授权");
                } else if ("ing".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "正在授权");
                    return rsMap;
                    return rsMap;
                }else if("fail".equals(auth_status)){
                    rsMap.put("sCode",auth_status);
                    rsMap.put("sMes","授权失败");
                } else if ("fail".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "授权失败");
                    return rsMap;
                    return rsMap;
                }else if("cancel".equals(auth_status)){
                    rsMap.put("sCode",auth_status);
                    rsMap.put("sMes","取消授权");
                } else if ("cancel".equals(auth_status)) {
                    rsMap.put("sCode", auth_status);
                    rsMap.put("sMes", "取消授权");
                    return rsMap;
                    return rsMap;
                }
                }
            }
            }
            rsMap.put("sCode","err");
            rsMap.put("sMes","请求失败");
            rsMap.put("sCode", "err");
            rsMap.put("sMes", "请求失败");
            return rsMap;
            return rsMap;
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
        }
        }
        rsMap.put("sCode","err");
        rsMap.put("sMes","请求失败");
        rsMap.put("sCode", "err");
        rsMap.put("sMes", "请求失败");
        return rsMap;
        return rsMap;
    }
    }
    /**
    /**
     * 查询协同门诊记录
     * 查询协同门诊记录
     *
     * @param generalDoctor
     * @param generalDoctor
     * @param startDate
     * @param startDate
     * @param endDate
     * @param endDate
     * @param status
     * @param status
     * @return
     * @return
     */
     */
    public Envelop findByGeneralDoctor(String generalDoctor,String startDate,String endDate,String status,String sort,Integer page,Integer size,String wxId){
    public Envelop findByGeneralDoctor(String generalDoctor, String startDate, String endDate, String status, String sort, Integer page, Integer size, String wxId) {
        String sqlTotal ="SELECT " +
                " count(1) AS total "+
        String sqlTotal = "SELECT " +
                " count(1) AS total " +
                " FROM " +
                " FROM " +
                " wlyy_outpatient o " +
                " wlyy_outpatient o " +
                " WHERE " +
                " WHERE " +
                " o.general_doctor = '"+generalDoctor+"'";
        if(StringUtils.isNotBlank(startDate)){
                " o.general_doctor = '" + generalDoctor + "'";
        if (StringUtils.isNotBlank(startDate)) {
            if("xm_ykyy_wx".equals(wxId)){
                sqlTotal +=" and o.register_date >= to_date('"+startDate+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sqlTotal += " AND o.register_date >='"+startDate+" 00:00:00' ";
            if ("xm_ykyy_wx".equals(wxId)) {
                sqlTotal += " and o.register_date >= to_date('" + startDate + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sqlTotal += " AND o.register_date >='" + startDate + " 00:00:00' ";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(endDate)){
            if("xm_ykyy_wx".equals(wxId)){
                sqlTotal +=" and o.register_date <= to_date('"+endDate+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sqlTotal += " AND o.register_date <='"+endDate+" 23:59:59' ";
        if (StringUtils.isNotBlank(endDate)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                sqlTotal += " and o.register_date <= to_date('" + endDate + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sqlTotal += " AND o.register_date <='" + endDate + " 23:59:59' ";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(status)){
            sqlTotal += " AND o.status ='"+status+"'";
        if (StringUtils.isNotBlank(status)) {
            sqlTotal += " AND o.status ='" + status + "'";
        }
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlTotal);
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlTotal);
@ -5334,7 +5528,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        if (rstotal != null && rstotal.size() > 0) {
        if (rstotal != null && rstotal.size() > 0) {
            total = Long.parseLong(rstotal.get(0).get("total").toString());
            total = Long.parseLong(rstotal.get(0).get("total").toString());
        }
        }
        String sql ="SELECT " +
        String sql = "SELECT " +
                " o.id AS \"id\", " +
                " o.id AS \"id\", " +
                " o.adm_no AS \"admNo\", " +
                " o.adm_no AS \"admNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
                " o.origin_adm_no AS \"originAdmNo\", " +
@ -5358,7 +5552,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " o.idcard AS \"idcard\", " +
                " o.idcard AS \"idcard\", " +
                " o.card_no AS \"cardNo\", " +
                " o.card_no AS \"cardNo\", " +
                " o.mjz AS \"mjz\", " +
                " o.mjz AS \"mjz\", " +
                " o.icd10 AS \"icd10\", "+
                " o.icd10 AS \"icd10\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " o.icd10_name AS \"icd10Name\", " +
                " o.advice AS \"advice\", " +
                " o.advice AS \"advice\", " +
                " o.adm_date AS \"admDate\", " +
                " o.adm_date AS \"admDate\", " +
@ -5375,65 +5569,66 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " FROM " +
                " FROM " +
                " wlyy_outpatient o " +
                " wlyy_outpatient o " +
                " WHERE " +
                " WHERE " +
                " o.general_doctor = '"+generalDoctor+"'";
        if(StringUtils.isNotBlank(startDate)){
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and o.register_date >= to_date('"+startDate+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sql += " AND o.register_date >='"+startDate+" 00:00:00' ";
                " o.general_doctor = '" + generalDoctor + "'";
        if (StringUtils.isNotBlank(startDate)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and o.register_date >= to_date('" + startDate + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND o.register_date >='" + startDate + " 00:00:00' ";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(endDate)){
            if("xm_ykyy_wx".equals(wxId)){
                sql +=" and o.register_date <= to_date('"+endDate+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            }else {
                sql += " AND o.register_date <='"+endDate+" 23:59:59' ";
        if (StringUtils.isNotBlank(endDate)) {
            if ("xm_ykyy_wx".equals(wxId)) {
                sql += " and o.register_date <= to_date('" + endDate + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
            } else {
                sql += " AND o.register_date <='" + endDate + " 23:59:59' ";
            }
            }
        }
        }
        if(StringUtils.isNotBlank(status)){
            sql+=" AND o.status ='"+status+"'";
        if (StringUtils.isNotBlank(status)) {
            sql += " AND o.status ='" + status + "'";
        }
        }
        if(StringUtils.isNotBlank(sort)){
            sql += " ORDER BY o.register_date "+sort;
        }else{
        if (StringUtils.isNotBlank(sort)) {
            sql += " ORDER BY o.register_date " + sort;
        } else {
            sql += " ORDER BY o.register_date ASC ";
            sql += " ORDER BY o.register_date ASC ";
        }
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,size);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, size);
        //List<WlyyOutpatientDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyOutpatientDO.class));
        //List<WlyyOutpatientDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyOutpatientDO.class));
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, total);
        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, total);
    }
    }
    /**
    /**
     * 全科医生首页协同门诊统计列表.
     * 全科医生首页协同门诊统计列表.
     *
     * @param generalDoctor
     * @param generalDoctor
     * @return
     * @return
     */
     */
    public Map<String,Object> findGeneralDoctorInfo(String generalDoctor){
    public Map<String, Object> findGeneralDoctorInfo(String generalDoctor) {
        Map<String,Object> rs = new HashedMap();
        Date startTime = DateUtil.strToDate(DateUtil.dateToStr(new Date(),"yyyy-MM-dd")+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        Date endTime = DateUtil.strToDate(DateUtil.dateToStr(new Date(),"yyyy-MM-dd")+" 23:59:59","yyyy-MM-dd HH:mm:ss");
        Map<String, Object> rs = new HashedMap();
        Date startTime = DateUtil.strToDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endTime = DateUtil.strToDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd") + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        //今天协同门诊列表
        //今天协同门诊列表
        List<WlyyOutpatientDO> todayList = outpatientDao.findByGeneralDoctor(generalDoctor,startTime,endTime,"0");
        List<WlyyOutpatientDO> todayList = outpatientDao.findByGeneralDoctor(generalDoctor, startTime, endTime, "0");
        rs.put("todayList",todayList);
        rs.put("todayList", todayList);
        List<WlyyOutpatientDO> todayBeginList = outpatientDao.findByGeneralDoctor(generalDoctor,startTime,endTime,"1");
        List<WlyyOutpatientDO> todayBeginList = outpatientDao.findByGeneralDoctor(generalDoctor, startTime, endTime, "1");
        rs.put("todayBeginList",todayBeginList);
        rs.put("todayBeginList", todayBeginList);
        Calendar tomorrowTime = Calendar.getInstance();
        Calendar tomorrowTime = Calendar.getInstance();
        tomorrowTime.setTime(startTime);
        tomorrowTime.setTime(startTime);
        tomorrowTime.add(Calendar.DATE,1);
        tomorrowTime.add(Calendar.DATE, 1);
        Calendar tomorrowEndtime = Calendar.getInstance();
        Calendar tomorrowEndtime = Calendar.getInstance();
        tomorrowEndtime.setTime(endTime);
        tomorrowEndtime.setTime(endTime);
        tomorrowEndtime.add(Calendar.DATE,1);
        tomorrowEndtime.add(Calendar.DATE, 1);
        //明天协同门诊列表
        //明天协同门诊列表
        List<WlyyOutpatientDO> tomorrowList = outpatientDao.findByGeneralDoctor(generalDoctor,tomorrowTime.getTime(),tomorrowEndtime.getTime(),"0");
        rs.put("tomorrowList",tomorrowList);
        List<WlyyOutpatientDO> tomorrowList = outpatientDao.findByGeneralDoctor(generalDoctor, tomorrowTime.getTime(), tomorrowEndtime.getTime(), "0");
        rs.put("tomorrowList", tomorrowList);
        //统计科预约医生
        //统计科预约医生
        String sql = "SELECT " +
        String sql = "SELECT " +
@ -5452,10 +5647,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            doctorTotal = (Long) rstotal.get(0).get("total");
            doctorTotal = (Long) rstotal.get(0).get("total");
        }
        }
        rs.put("doctorTotal",doctorTotal);
        rs.put("doctorTotal", doctorTotal);
        //统计在线医生
        //统计在线医生
        String onlineSql="SELECT " +
        String onlineSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " FROM " +
                " base_doctor d " +
                " base_doctor d " +
@ -5472,22 +5667,20 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            onlineTotal = Long.parseLong(oltotal.get(0).get("total").toString());
            onlineTotal = Long.parseLong(oltotal.get(0).get("total").toString());
        }
        }
        rs.put("onlineTotal",onlineTotal);
        rs.put("onlineTotal", onlineTotal);
        return rs;
        return rs;
    }
    }
    /**
    /**
     * 查询医生所有可抢单的数量
     * 查询医生所有可抢单的数量
     *
     * @param doctor
     * @param doctor
     * @param dept
     * @param dept
     * @return
     * @return
     */
     */
    public com.alibaba.fastjson.JSONObject findWaitingRoomOutpatientNumberByDoctor(String doctor,String dept) {
    public com.alibaba.fastjson.JSONObject findWaitingRoomOutpatientNumberByDoctor(String doctor, String dept) {
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
@ -5500,7 +5693,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "wlyy_outpatient outpatient " +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.dept='"+dept+"' ";
                "AND outpatient.status = 0 AND room.doctor IS NULL AND outpatient.dept='" + dept + "' ";
        List<Map<String, Object>> alltotal = jdbcTemplate.queryForList(sqlAll);
        List<Map<String, Object>> alltotal = jdbcTemplate.queryForList(sqlAll);
@ -5509,7 +5702,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            totalsqlAll = Long.parseLong(alltotal.get(0).get("total").toString());
            totalsqlAll = Long.parseLong(alltotal.get(0).get("total").toString());
        }
        }
        object.put("all",totalsqlAll);
        object.put("all", totalsqlAll);
        //图文复诊
        //图文复诊
        String imgAll = "SELECT " +
        String imgAll = "SELECT " +
@ -5519,7 +5712,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "wlyy_outpatient outpatient " +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=1 AND room.consult_type=1 AND outpatient.dept='"+dept+"' ";
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=1 AND room.consult_type=1 AND outpatient.dept='" + dept + "' ";
        List<Map<String, Object>> imgtotal = jdbcTemplate.queryForList(imgAll);
        List<Map<String, Object>> imgtotal = jdbcTemplate.queryForList(imgAll);
@ -5528,7 +5721,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            twCount = Long.parseLong(imgtotal.get(0).get("total").toString());
            twCount = Long.parseLong(imgtotal.get(0).get("total").toString());
        }
        }
        object.put("twCount",twCount);
        object.put("twCount", twCount);
        //视频复诊
        //视频复诊
        String spsql = "SELECT " +
        String spsql = "SELECT " +
@ -5538,7 +5731,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "wlyy_outpatient outpatient " +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=1 AND room.consult_type=2 AND outpatient.dept='"+dept+"' ";
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=1 AND room.consult_type=2 AND outpatient.dept='" + dept + "' ";
        List<Map<String, Object>> sptotal = jdbcTemplate.queryForList(spsql);
        List<Map<String, Object>> sptotal = jdbcTemplate.queryForList(spsql);
@ -5547,7 +5740,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            spcount = Long.parseLong(sptotal.get(0).get("total").toString());
            spcount = Long.parseLong(sptotal.get(0).get("total").toString());
        }
        }
        object.put("spCount",spcount);
        object.put("spCount", spcount);
        //协同门诊
        //协同门诊
@ -5558,7 +5751,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "wlyy_outpatient outpatient " +
                "wlyy_outpatient outpatient " +
                "WHERE " +
                "WHERE " +
                " room.outpatient_id=outpatient.id " +
                " room.outpatient_id=outpatient.id " +
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=2 AND outpatient.dept='"+dept+"' ";
                "AND outpatient.status = 0 AND room.doctor IS NULL AND room.reservation_type=2 AND outpatient.dept='" + dept + "' ";
        List<Map<String, Object>> xttotal = jdbcTemplate.queryForList(xtsql);
        List<Map<String, Object>> xttotal = jdbcTemplate.queryForList(xtsql);
@ -5567,23 +5760,23 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            xtcount = Long.parseLong(xttotal.get(0).get("total").toString());
            xtcount = Long.parseLong(xttotal.get(0).get("total").toString());
        }
        }
        object.put("xtCount",xtcount);
        object.put("xtCount", xtcount);
        return object;
        return object;
    }
    }
    public Map<String,Object> refuseOutpatientByDoctor(String outPatientId, String cancelType, String cancelValue, String cancelRemark) {
        Map<String,Object> rs = new HashedMap();
    public Map<String, Object> refuseOutpatientByDoctor(String outPatientId, String cancelType, String cancelValue, String cancelRemark) {
        Map<String, Object> rs = new HashedMap();
        //判断医生是否接诊
        //判断医生是否接诊
        List<WlyyHospitalWaitingRoomDO> roomDOs =hospitalWaitingRoomDao.findByOutpatientId(outPatientId);
        if(roomDOs!=null&&roomDOs.size()>0){
            for(WlyyHospitalWaitingRoomDO roomDO:roomDOs){
                if(roomDO.getVisitStatus()==2){
                    rs.put("code",-1);
                    rs.put("mes","医生已经接诊,无法取消");
        List<WlyyHospitalWaitingRoomDO> roomDOs = hospitalWaitingRoomDao.findByOutpatientId(outPatientId);
        if (roomDOs != null && roomDOs.size() > 0) {
            for (WlyyHospitalWaitingRoomDO roomDO : roomDOs) {
                if (roomDO.getVisitStatus() == 2) {
                    rs.put("code", -1);
                    rs.put("mes", "医生已经接诊,无法取消");
                    return rs;
                    return rs;
                }else{
                } else {
                    roomDO.setVisitStatus(-1);
                    roomDO.setVisitStatus(-1);
                    hospitalWaitingRoomDao.save(roomDO);
                    hospitalWaitingRoomDao.save(roomDO);
                }
                }
@ -5600,111 +5793,115 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //删除门诊号源
        //删除门诊号源
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        List<WlyyPatientRegisterTimeDO> list = patientRegisterTimeDao.findByOutpatientId(wlyyOutpatientDO.getId());
        if(list!=null&&list.size()>0){
        if (list != null && list.size() > 0) {
            patientRegisterTimeDao.delete(list);
            patientRegisterTimeDao.delete(list);
        }
        }
        rs.put("code",1);
        rs.put("mes","取消成功");
        return  rs;
        rs.put("code", 1);
        rs.put("mes", "取消成功");
        return rs;
    }
    }
    /**
    /**
     * 获取居民当日就诊列表
     * 获取居民当日就诊列表
     *
     * @param patient
     * @param patient
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> getTodayOutpatinetList(String patient,String wxId) {
    public List<Map<String, Object>> getTodayOutpatinetList(String patient, String wxId) {
        String condition = "";
        String condition = "";
        if("xm_ykyy_wx".equals(wxId)){
        if ("xm_ykyy_wx".equals(wxId)) {
            condition = "to_char(p.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
            condition = "to_char(p.register_date,'YYYY-MM-DD hh24:mi:ss')  AS \"time\",";
        }else{
            condition ="date_format(p.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"time\",";
        } else {
            condition = "date_format(p.register_date,'%Y-%m-%d %H:%i:%S' )  AS \"time\",";
        }
        }
        String sql ="SELECT "+condition+"d.NAME as \"doctorName\",d.job_title_name as \"job_title_name\",d.photo AS \"photo\",p.id as \"outpatientid\" FROM wlyy_outpatient p,base_doctor d " +
                "WHERE p.patient='"+patient+"' AND p.doctor=d.id AND p.status=0 ";
        if("xm_ykyy_wx".equals(wxId)){
        String sql = "SELECT " + condition + "d.NAME as \"doctorName\",d.job_title_name as \"job_title_name\",d.photo AS \"photo\",p.id as \"outpatientid\" FROM wlyy_outpatient p,base_doctor d " +
                "WHERE p.patient='" + patient + "' AND p.doctor=d.id AND p.status=0 ";
        if ("xm_ykyy_wx".equals(wxId)) {
            sql +=" AND p.register_date >= to_date('"+DateUtil.dateToStrShort(new Date())+" 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            sql +=" AND p.register_date <= to_date('"+DateUtil.dateToStrShort(new Date())+" 23:59:59','YYYY-MM-DD HH24:MI:SS')";
        }else {
            sql +=" BETWEEN '"+DateUtil.dateToStrShort(new Date())+" 00:00:00' AND '"+DateUtil.dateToStrShort(new Date())+" 23:59:59' ";
            sql += " AND p.register_date >= to_date('" + DateUtil.dateToStrShort(new Date()) + " 00:00:00','YYYY-MM-DD HH24:MI:SS')";
            sql += " AND p.register_date <= to_date('" + DateUtil.dateToStrShort(new Date()) + " 23:59:59','YYYY-MM-DD HH24:MI:SS')";
        } else {
            sql += " BETWEEN '" + DateUtil.dateToStrShort(new Date()) + " 00:00:00' AND '" + DateUtil.dateToStrShort(new Date()) + " 23:59:59' ";
        }
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
        return list;
    }
    }
    /**
    /**
     * 获取doctormappingcode
     * 获取doctormappingcode
     *
     * @param doctor
     * @param doctor
     * @param orgCode
     * @param orgCode
     * @return
     * @return
     */
     */
    public DoctorMappingDO getDoctorMapping(String doctor,String orgCode){
        return doctorMappingService.findMappingCode(doctor,orgCode);
    public DoctorMappingDO getDoctorMapping(String doctor, String orgCode) {
        return doctorMappingService.findMappingCode(doctor, orgCode);
    }
    }
    /**
    /**
     * 获取医生简介
     * 获取医生简介
     *
     * @param doctorCode
     * @param doctorCode
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public net.sf.json.JSON getDoctorIntroduction(String doctorCode) throws Exception {
    public net.sf.json.JSON getDoctorIntroduction(String doctorCode) throws Exception {
        DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(doctorCode,"350211A1002");
        if(doctorMappingDO==null){
        DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(doctorCode, "350211A1002");
        if (doctorMappingDO == null) {
            throw new RuntimeException("未找到医生映射信息");
            throw new RuntimeException("未找到医生映射信息");
        }
        }
        return entranceService.BS16010(doctorMappingDO.getMappingCode(),demoFlag);
        return entranceService.BS16010(doctorMappingDO.getMappingCode(), demoFlag);
    }
    }
    /**
    /**
     *
     * @param name
     * @param name
     * @param hospital
     * @param hospital
     * @return
     * @return
     */
     */
    public List<WlyyHospitalSysDictDO> findByDict(String name,String hospital){
        return sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital,name);
    public List<WlyyHospitalSysDictDO> findByDict(String name, String hospital) {
        return sysDictDao.findByHospitalAndDictNameOrderBySortAsc(hospital, name);
    }
    }
    /**
    /**
     * 建立档案
     * 建立档案
     *
     * @param json
     * @param json
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public net.sf.json.JSONObject setRecord(String json,String type)throws Exception{
    public net.sf.json.JSONObject setRecord(String json, String type) throws Exception {
        net.sf.json.JSONObject rs = new JSONObject();
        net.sf.json.JSONObject rs = new JSONObject();
        ArchiveVO archiveVO = objectMapper.readValue(json,ArchiveVO.class);
        if(archiveVO!=null){
            if(StringUtils.isBlank(archiveVO.getBrnl00())){
                archiveVO.setBrnl00(IdCardUtil.getAgeForIdcard(archiveVO.getSfzhao())+"");
        ArchiveVO archiveVO = objectMapper.readValue(json, ArchiveVO.class);
        if (archiveVO != null) {
            if (StringUtils.isBlank(archiveVO.getBrnl00())) {
                archiveVO.setBrnl00(IdCardUtil.getAgeForIdcard(archiveVO.getSfzhao()) + "");
            }
            }
            if(StringUtils.isBlank(archiveVO.getCsrq00())){
                archiveVO.setCsrq00(DateUtil.dateToStr(IdCardUtil.getBirthdayForIdcard(archiveVO.getSfzhao()),"yyyyMMdd"));
            if (StringUtils.isBlank(archiveVO.getCsrq00())) {
                archiveVO.setCsrq00(DateUtil.dateToStr(IdCardUtil.getBirthdayForIdcard(archiveVO.getSfzhao()), "yyyyMMdd"));
            }
            }
            //1为需要同步建档
            //1为需要同步建档
            if("1".equals(type)){
                rs = entranceService.BS16018(archiveVO,demoFlag);
            if ("1".equals(type)) {
                rs = entranceService.BS16018(archiveVO, demoFlag);
            }
            }
            //保存互联网医院居民账户
            //保存互联网医院居民账户
            BasePatientDO patientDO = savePatient(archiveVO);
            BasePatientDO patientDO = savePatient(archiveVO);
            rs.put("patient",patientDO.getId());
            rs.put("patient", patientDO.getId());
        }
        }
        return rs;
        return rs;
    }
    }
    /**
    /**
     * 存储居民
     * 存储居民
     *
     * @param archiveVO
     * @param archiveVO
     * @return
     * @return
     */
     */
    public BasePatientDO savePatient(ArchiveVO archiveVO)throws Exception{
        BasePatientDO patientDO =  basePatientDao.findByIdcardAndDel(archiveVO.getSfzhao(),"1");
        if(patientDO == null) {
    public BasePatientDO savePatient(ArchiveVO archiveVO) throws Exception {
        BasePatientDO patientDO = basePatientDao.findByIdcardAndDel(archiveVO.getSfzhao(), "1");
        if (patientDO == null) {
            BasePatientDO patient = new BasePatientDO();
            BasePatientDO patient = new BasePatientDO();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            String salt = UUID.randomUUID().toString().substring(0, 5);
@ -5730,25 +5927,26 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取HIIS居民档案信息
     * 获取HIIS居民档案信息
     *
     * @param idcard
     * @param idcard
     * @param patient
     * @param patient
     * @param admitNum
     * @param admitNum
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public JSONArray findPatientRecord(String idcard,String patient,String admitNum,String ybcard)throws Exception{
    public JSONArray findPatientRecord(String idcard, String patient, String admitNum, String ybcard) throws Exception {
        String patientId = null;
        String patientId = null;
        if(StringUtils.isNotBlank(patient)){
        if (StringUtils.isNotBlank(patient)) {
            patientId = patientMappingService.findHisPatNoByPatient(patient);
            patientId = patientMappingService.findHisPatNoByPatient(patient);
        }
        }
        return entranceService.BS10008(idcard,patientId,admitNum,ybcard,demoFlag);
        return entranceService.BS10008(idcard, patientId, admitNum, ybcard, demoFlag);
    }
    }
    /**
    /**
     * 查找未配送处方订单
     * 查找未配送处方订单
     */
     */
    public List<WlyyPrescriptionVO> findUndeliveredList(){
        String sql ="SELECT " +
    public List<WlyyPrescriptionVO> findUndeliveredList() {
        String sql = "SELECT " +
                " p.id AS \"id\", " +
                " p.id AS \"id\", " +
                " p.real_order AS \"realOrder\"," +
                " p.real_order AS \"realOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
                " p.origin_real_order AS \"originRealOrder\"," +
@ -5795,7 +5993,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " wlyy_prescription p " +
                " wlyy_prescription p " +
                " WHERE status = 60 or status = 50 ";
                " WHERE status = 60 or status = 50 ";
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));
        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyyPrescriptionVO.class));
        if(list!=null){
        if (list != null) {
            return list;
            return list;
        }
        }
        return new ArrayList<>();
        return new ArrayList<>();
@ -5803,73 +6001,74 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取医生信息
     * 获取医生信息
     *
     * @param hospital
     * @param hospital
     * @param name
     * @param name
     * @return
     * @return
     */
     */
    public List<Map<String,Object>> findDoctorByName(String hospital, String name,String chargeType){
        String sql ="SELECT " +
    public List<Map<String, Object>> findDoctorByName(String hospital, String name, String chargeType) {
        String sql = "SELECT " +
                " d.id AS \"id\", " +
                " d.id AS \"id\", " +
                " d.name AS \"name\"" +
                " d.name AS \"name\"" +
                " FROM " +
                " FROM " +
                " base_doctor d ";
                " base_doctor d ";
        if(StringUtils.isNotBlank(hospital)){
            sql +=" JOIN base_doctor_hospital h ON h.doctor_code = d.id";
        if (StringUtils.isNotBlank(hospital)) {
            sql += " JOIN base_doctor_hospital h ON h.doctor_code = d.id";
        }
        }
        sql +=" JOIN base_doctor_role r ON r.doctor_code = d.id ";
        sql +=" WHERE " +
                " d. NAME LIKE '%"+name+"%'";
        if(StringUtils.isNotBlank(hospital)){
            sql +=" AND h.org_code ='"+hospital+"'";
        sql += " JOIN base_doctor_role r ON r.doctor_code = d.id ";
        sql += " WHERE " +
                " d. NAME LIKE '%" + name + "%'";
        if (StringUtils.isNotBlank(hospital)) {
            sql += " AND h.org_code ='" + hospital + "'";
        }
        }
        if(StringUtils.isNotBlank(chargeType)){
            if("all".equals(chargeType)){
        if (StringUtils.isNotBlank(chargeType)) {
            if ("all".equals(chargeType)) {
                //查询全部号源
                //查询全部号源
            }else{
                sql+=" AND d.charge_type ='"+chargeType+"'";
            } else {
                sql += " AND d.charge_type ='" + chargeType + "'";
            }
            }
        }else{
            sql+=" AND d.charge_type is not null ";
        } else {
            sql += " AND d.charge_type is not null ";
        }
        }
        sql += " AND r.role_code ='specialist'";
        sql += " AND r.role_code ='specialist'";
        logger.info("findDoctorByName :"+sql);
        logger.info("findDoctorByName :" + sql);
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                Map<String,Object> d = list.get(i);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> d = list.get(i);
                List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(d.get("id").toString());
                List<BaseDoctorHospitalDO> depts = baseDoctorHospitalDao.findByDoctorCode(d.get("id").toString());
                d.put("depts",depts);
                d.put("depts", depts);
            }
            }
        }
        }
        return list;
        return list;
    }
    }
    public void followOrgByPatient(String patientid, String doctorid, String type) {
    public void followOrgByPatient(String patientid, String doctorid, String type) {
        List<BaseDoctorPatientFollowDO> list =baseOrgPatientDao.findByDoctorAndPatient(doctorid,patientid);
        if("1".equals(type)){//关注
            if(list.isEmpty()){
        List<BaseDoctorPatientFollowDO> list = baseOrgPatientDao.findByDoctorAndPatient(doctorid, patientid);
        if ("1".equals(type)) {//关注
            if (list.isEmpty()) {
                BaseDoctorPatientFollowDO baseOrgPatientFollowDO = new BaseDoctorPatientFollowDO();
                BaseDoctorPatientFollowDO baseOrgPatientFollowDO = new BaseDoctorPatientFollowDO();
                baseOrgPatientFollowDO.setDoctor(doctorid);
                baseOrgPatientFollowDO.setDoctor(doctorid);
                baseOrgPatientFollowDO.setPatient(patientid);
                baseOrgPatientFollowDO.setPatient(patientid);
                baseOrgPatientDao.save(baseOrgPatientFollowDO);
                baseOrgPatientDao.save(baseOrgPatientFollowDO);
            }
            }
        }
        }
        if("0".equals(type)){//取消关注
            if(!list.isEmpty()){
                for (BaseDoctorPatientFollowDO baseOrgPatientFollowDO:list){
        if ("0".equals(type)) {//取消关注
            if (!list.isEmpty()) {
                for (BaseDoctorPatientFollowDO baseOrgPatientFollowDO : list) {
                    baseOrgPatientDao.delete(baseOrgPatientFollowDO.getId());
                    baseOrgPatientDao.delete(baseOrgPatientFollowDO.getId());
                }
                }
            }
            }
        }
        }
    }
    }
    public List<Map<String,Object>> findDeptByKeyWord(String keyWord,Integer page,Integer pagesize) {
    public List<Map<String, Object>> findDeptByKeyWord(String keyWord, Integer page, Integer pagesize) {
        String sql ="SELECT " +
        String sql = "SELECT " +
                "dept.code AS \"deptCode\"," +
                "dept.code AS \"deptCode\"," +
                "dept.name AS \"deptName\"," +
                "dept.name AS \"deptName\"," +
                "org.CODE AS \"orgCode\", " +
                "org.CODE AS \"orgCode\", " +
@ -5880,21 +6079,21 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "WHERE org.CODE=dept.org_code " +
                "WHERE org.CODE=dept.org_code " +
                "AND org.del=1 ";
                "AND org.del=1 ";
        if(StringUtils.isNoneBlank(keyWord)){
            sql = sql + "AND dept.NAME LIKE '%"+keyWord+"%' ";
        if (StringUtils.isNoneBlank(keyWord)) {
            sql = sql + "AND dept.NAME LIKE '%" + keyWord + "%' ";
        }
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pagesize);
        logger.info("sql:"+sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql, page, pagesize);
        logger.info("sql:" + sql);
        return list;
        return list;
    }
    }
    public List<Map<String,Object>> findDeptWithDoctorWorkTime(String hospital,String keyWord,Integer page,Integer pagesize ){
    public List<Map<String, Object>> findDeptWithDoctorWorkTime(String hospital, String keyWord, Integer page, Integer pagesize) {
        String now = DateUtil.dateToStr(new Date(),"yyyy-MM-dd");
        String now = DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
//        Date startDate = DateUtil.stringToDate(now+" 00:00:00","yyyy-MM-dd HH:mm:ss");
//        Date startDate = DateUtil.stringToDate(now+" 00:00:00","yyyy-MM-dd HH:mm:ss");
//        Date endDate = DateUtil.stringToDate(now+" 23:59:59","yyyy-MM-dd HH:mm:ss");
//        Date endDate = DateUtil.stringToDate(now+" 23:59:59","yyyy-MM-dd HH:mm:ss");
        String sql ="SELECT  " +
        String sql = "SELECT  " +
                " DISTINCT " +
                " DISTINCT " +
                " h.dept_code AS \"deptCode\", " +
                " h.dept_code AS \"deptCode\", " +
                " h.dept_name AS \"deptName\"," +
                " h.dept_name AS \"deptName\"," +
@ -5916,25 +6115,24 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                " ) OR d.consult_status ='1') " +
                " ) OR d.consult_status ='1') " +
                " AND h.dept_code IS NOT NULL " +
                " AND h.dept_code IS NOT NULL " +
                " AND h.dept_code !=''";
                " AND h.dept_code !=''";
        Map<String,Object> params = new HashedMap();
        params.put("startTime",new Date());
        params.put("endDate",new Date());
        if(StringUtils.isNotBlank(hospital)){
            sql +=" AND h.org_code =:hospital";
            params.put("hospital",hospital);
        Map<String, Object> params = new HashedMap();
        params.put("startTime", new Date());
        params.put("endDate", new Date());
        if (StringUtils.isNotBlank(hospital)) {
            sql += " AND h.org_code =:hospital";
            params.put("hospital", hospital);
        }
        }
        if(StringUtils.isNotBlank(keyWord)){
            sql +=" AND h.dept_name like:keyWord";
            params.put("keyWord","%"+keyWord+"%");
        if (StringUtils.isNotBlank(keyWord)) {
            sql += " AND h.dept_name like:keyWord";
            params.put("keyWord", "%" + keyWord + "%");
        }
        }
        logger.info(sql);
        logger.info(sql);
        return hibenateUtils.createSQLQuery(sql,params,page,pagesize);
        return hibenateUtils.createSQLQuery(sql, params, page, pagesize);
    }
    }
    public List<Map<String,Object>> selectByCondition(String hospital, String dept, String checkStatus, String startTime, String endTime, String nameInfo, Integer page, Integer pagesize, String wxId){
        List<Map<String,Object>> maps = new ArrayList<>();
    public List<Map<String, Object>> selectByCondition(String hospital, String dept, String checkStatus, String startTime, String endTime, String nameInfo, Integer page, Integer pagesize, String wxId) {
        List<Map<String, Object>> maps = new ArrayList<>();
        String sql = "SELECT\n" +
        String sql = "SELECT\n" +
                "\tp.doctor as \"doctor\",\n" +
                "\tp.doctor as \"doctor\",\n" +
                "\tp.id as \"id\",\n" +
                "\tp.id as \"id\",\n" +
@ -5947,12 +6145,12 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "\tp.patient_name as \"patientName\",\n" +
                "\tp.patient_name as \"patientName\",\n" +
                "\tp.idcard as \"idcard\",\n" +
                "\tp.idcard as \"idcard\",\n" +
                "\tp.ssc as \"ssc\",\n";
                "\tp.ssc as \"ssc\",\n";
        if("xm_ykyy_wx".equals(wxId)){
        if ("xm_ykyy_wx".equals(wxId)) {
            sql = sql + "to_char(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
            sql = sql + "to_char(p.create_time,'YYYY-MM-DD hh24:mi:ss')  AS \"createTime\",";
        }else{
        } else {
            sql = sql + "date_format(p.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
            sql = sql + "date_format(p.create_time,'%Y-%m-%d %H:%i:%S' )  AS \"createTime\",";
        }
        }
        sql +="\tp.status as \"status\",\n" +
        sql += "\tp.status as \"status\",\n" +
                "\tp.check_status as \"checkStatus\",\n" +
                "\tp.check_status as \"checkStatus\",\n" +
                "\tp.check_reason as \"checkReason\",\n" +
                "\tp.check_reason as \"checkReason\",\n" +
                "\tp.pay_type as \"payType\"\n" +
                "\tp.pay_type as \"payType\"\n" +
@ -5960,99 +6158,101 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "\twlyy_prescription P\n" +
                "\twlyy_prescription P\n" +
                "WHERE\n" +
                "WHERE\n" +
                "\t1 = 1  ";
                "\t1 = 1  ";
        Map<String,Object> params = new HashedMap();
        if (StringUtils.isNoneBlank(hospital)){
            sql +=" and p.hospital =:hospital";
            params.put("hospital",hospital);
        Map<String, Object> params = new HashedMap();
        if (StringUtils.isNoneBlank(hospital)) {
            sql += " and p.hospital =:hospital";
            params.put("hospital", hospital);
        }
        }
        if (StringUtils.isNoneBlank(dept)){
            sql +=" and p.dept =:dept";
            params.put("dept",dept);
        if (StringUtils.isNoneBlank(dept)) {
            sql += " and p.dept =:dept";
            params.put("dept", dept);
        }
        }
        if (StringUtils.isNoneBlank(checkStatus)){
            sql +=" and p.check_status =:checkStatus";
            params.put("checkStatus",checkStatus);
        if (StringUtils.isNoneBlank(checkStatus)) {
            sql += " and p.check_status =:checkStatus";
            params.put("checkStatus", checkStatus);
        }
        }
        if (StringUtils.isNoneBlank(startTime)){
            sql +=" and p.create_time >=:startTime";
            params.put("startTime",DateUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss"));
        if (StringUtils.isNoneBlank(startTime)) {
            sql += " and p.create_time >=:startTime";
            params.put("startTime", DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss"));
        }
        }
        if (StringUtils.isNoneBlank(endTime)){
            sql +=" and p.create_time <=:endTime";
            params.put("endTime",DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss"));
        if (StringUtils.isNoneBlank(endTime)) {
            sql += " and p.create_time <=:endTime";
            params.put("endTime", DateUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss"));
        }
        }
        if (StringUtils.isNoneBlank(nameInfo)){
            sql +=" and (p.patient_name like '%"+nameInfo+"%' or p.doctor_name like '%"+nameInfo+"%')";
        if (StringUtils.isNoneBlank(nameInfo)) {
            sql += " and (p.patient_name like '%" + nameInfo + "%' or p.doctor_name like '%" + nameInfo + "%')";
        }
        }
        sql +=" order by p.create_time desc";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql,params,page,pagesize);
        sql += " order by p.create_time desc";
        List<Map<String, Object>> mapList = hibenateUtils.createSQLQuery(sql, params, page, pagesize);
        String sqlTotal = "select COUNT(1) AS \"total\" from wlyy_prescription p where 1=1  ";
        String sqlTotal = "select COUNT(1) AS \"total\" from wlyy_prescription p where 1=1  ";
        Map<String,Object> params1 = new HashedMap();
        if (StringUtils.isNoneBlank(hospital)){
            sqlTotal +=" and p.hospital =:hospital";
            params1.put("hospital",hospital);
        Map<String, Object> params1 = new HashedMap();
        if (StringUtils.isNoneBlank(hospital)) {
            sqlTotal += " and p.hospital =:hospital";
            params1.put("hospital", hospital);
        }
        }
        if (StringUtils.isNoneBlank(dept)){
            sqlTotal +=" and p.dept =:dept";
            params1.put("dept",dept);
        if (StringUtils.isNoneBlank(dept)) {
            sqlTotal += " and p.dept =:dept";
            params1.put("dept", dept);
        }
        }
        if (StringUtils.isNoneBlank(checkStatus)){
            sqlTotal +=" and p.check_status =:checkStatus";
            params1.put("checkStatus",checkStatus);
        if (StringUtils.isNoneBlank(checkStatus)) {
            sqlTotal += " and p.check_status =:checkStatus";
            params1.put("checkStatus", checkStatus);
        }
        }
        if (StringUtils.isNoneBlank(startTime)){
            sqlTotal +=" and p.create_time >=:startTime";
            params1.put("startTime",DateUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss"));
        if (StringUtils.isNoneBlank(startTime)) {
            sqlTotal += " and p.create_time >=:startTime";
            params1.put("startTime", DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss"));
        }
        }
        if (StringUtils.isNoneBlank(endTime)){
            sqlTotal +=" and p.create_time <=:endTime";
            params1.put("endTime",DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss"));
        if (StringUtils.isNoneBlank(endTime)) {
            sqlTotal += " and p.create_time <=:endTime";
            params1.put("endTime", DateUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss"));
        }
        }
        if (StringUtils.isNoneBlank(nameInfo)){
            sqlTotal +=" and (p.patient_name like '%"+nameInfo+"%' or p.doctor_name like '%"+nameInfo+"%')";
        if (StringUtils.isNoneBlank(nameInfo)) {
            sqlTotal += " and (p.patient_name like '%" + nameInfo + "%' or p.doctor_name like '%" + nameInfo + "%')";
        }
        }
        Long count = 0L;
        Long count = 0L;
        List<Map<String,Object>> total = hibenateUtils.createSQLQuery(sqlTotal,params1);
        if(total!=null){
        List<Map<String, Object>> total = hibenateUtils.createSQLQuery(sqlTotal, params1);
        if (total != null) {
            //mysql 与 Oracle 聚合函数返回类型不一致,需要判断装换
            //mysql 与 Oracle 聚合函数返回类型不一致,需要判断装换
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
            count = hibenateUtils.objTransformLong(total.get(0).get("total"));
        }
        }
        Map<String,Object> map = new HashedMap();
        map.put("count",count);
        map.put("list",mapList);
        Map<String, Object> map = new HashedMap();
        map.put("count", count);
        map.put("list", mapList);
        maps.add(map);
        maps.add(map);
        return maps;
        return maps;
    }
    }
    /**
    /**
     * 修改处方状态
     * 修改处方状态
     *
     * @param prescriptionId
     * @param prescriptionId
     * @param status
     * @param status
     */
     */
    public void updateStatus(String prescriptionId,Integer status){
    public void updateStatus(String prescriptionId, Integer status) {
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        prescriptionDao.updateStatus(prescriptionId,status,new Date());
        prescriptionLogService.addPrescriptionLog(prescriptionId,status,1,wlyyPrescriptionDO.getPatientCode(),wlyyPrescriptionDO.getPatientName(),null,new Date());
        prescriptionDao.updateStatus(prescriptionId, status, new Date());
        prescriptionLogService.addPrescriptionLog(prescriptionId, status, 1, wlyyPrescriptionDO.getPatientCode(), wlyyPrescriptionDO.getPatientName(), null, new Date());
    }
    }
    /**
    /**
     *  更改订单号
     * 更改订单号
     *
     *
     * @param id
     * @param id
     * @param mailNo
     * @param mailNo
     */
     */
    public void updateMailNoById(String id,String mailNo){
        prescriptionExpressageDao.updateMailNoById(id,mailNo);
    public void updateMailNoById(String id, String mailNo) {
        prescriptionExpressageDao.updateMailNoById(id, mailNo);
    }
    }
    /**
    /**
     * 审方
     * 审方
     *
     * @param operate
     * @param operate
     * @param operateName
     * @param operateName
     * @param reason
     * @param reason
@ -6060,7 +6260,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
     * @param prescriptionId
     * @param prescriptionId
     * @return
     * @return
     */
     */
    public WlyyPrescriptionCheckDO saveCheck(String operate,String operateName,String reason,Integer status,String prescriptionId,String wxId){
    public WlyyPrescriptionCheckDO saveCheck(String operate, String operateName, String reason, Integer status, String prescriptionId, String wxId) {
        WlyyPrescriptionCheckDO prescriptionCheckDO = new WlyyPrescriptionCheckDO();
        WlyyPrescriptionCheckDO prescriptionCheckDO = new WlyyPrescriptionCheckDO();
        prescriptionCheckDO.setCreateTime(new Date());
        prescriptionCheckDO.setCreateTime(new Date());
        prescriptionCheckDO.setOperate(operate);
        prescriptionCheckDO.setOperate(operate);
@ -6073,66 +6273,66 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (status==2){
        if (status == 2) {
            /*prescriptionDao.updateCheckStatus(prescriptionId,2,reason,20);*/
            /*prescriptionDao.updateCheckStatus(prescriptionId,2,reason,20);*/
            logger.info("开始====="+wlyyPrescriptionDO.getCheckStatus());
            logger.info("开始=====" + wlyyPrescriptionDO.getCheckStatus());
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(wlyyPrescriptionDO.getOutpatientId());
            if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
            if (wxId.equalsIgnoreCase("xm_zsyy_wx")) {
                try {
                try {
                    List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId,1);
                    List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId,1);
                    List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
                    List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
                    DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
                    DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
                    //his处方拼接开方条件
                    //his处方拼接开方条件
                    com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
                    com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
                    for (WlyyPrescriptionInfoDO info:infoDOS){
                    for (WlyyPrescriptionInfoDO info : infoDOS) {
                        //设置his药品查询条件
                        //设置his药品查询条件
                        setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, info, outpatientDO.getIcd10());
                        setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, info, outpatientDO.getIcd10());
                    }
                    }
                    for (WlyyInspectionDO ins:inspectionDOS){
                    for (WlyyInspectionDO ins : inspectionDOS) {
                        //设置his药品查询条件
                        //设置his药品查询条件
                        setInspectionParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, ins, outpatientDO.getIcd10());
                        setInspectionParam(jsonData, doctorMappingDO, outpatientDO, wlyyPrescriptionDO, ins, outpatientDO.getIcd10());
                    }
                    }
                    Map<String,Object> map = sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);
                    Map<String, Object> map = sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);
                    //同步电子病历
                    //同步电子病历
                    WlyyPrescriptionEmrDO prescriptionEmrDO = prescriptionEmrDao.findEmrByPrescriptionId(prescriptionId);
                    WlyyPrescriptionEmrDO prescriptionEmrDO = prescriptionEmrDao.findEmrByPrescriptionId(prescriptionId);
                    if (prescriptionEmrDO!=null){
                    if (prescriptionEmrDO != null) {
                        String doctorId = doctorMappingDO.getMappingCode();
                        String doctorId = doctorMappingDO.getMappingCode();
                        String doctorName =doctorMappingDO.getDoctorName();
                        writeOutPatient(outpatientDO.getRegisterNo(),prescriptionEmrDO.getComplaint(),prescriptionEmrDO.getMedicalHistory(),prescriptionEmrDO.getPastHistory(),prescriptionEmrDO.getPhysicalExamination(),prescriptionEmrDO.getAssistExamination(),doctorId,doctorName);
                        String doctorName = doctorMappingDO.getDoctorName();
                        writeOutPatient(outpatientDO.getRegisterNo(), prescriptionEmrDO.getComplaint(), prescriptionEmrDO.getMedicalHistory(), prescriptionEmrDO.getPastHistory(), prescriptionEmrDO.getPhysicalExamination(), prescriptionEmrDO.getAssistExamination(), doctorId, doctorName);
                    }
                    }
                    if (map.get("code").toString().equalsIgnoreCase("1")){
                    if (map.get("code").toString().equalsIgnoreCase("1")) {
                        //  * @param applyDepaName @param applyDoctorName
                        //  * @param applyDepaName @param applyDoctorName
                        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
                        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
                        String patientCode = prescriptionDO.getPatientCode();
                        String patientCode = prescriptionDO.getPatientCode();
                        String realerOrder = prescriptionDO.getRealOrder();
                        String realerOrder = prescriptionDO.getRealOrder();
                        String free  = prescriptionDO.getDrugFee()+"";
                        String recipeTime = DateUtil.dateToStr(prescriptionDO.getCreateTime(),"yyyyMMddHHmmss");
                        String free = prescriptionDO.getDrugFee() + "";
                        String recipeTime = DateUtil.dateToStr(prescriptionDO.getCreateTime(), "yyyyMMddHHmmss");
                        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(prescriptionDO.getDoctor());
                        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(prescriptionDO.getDoctor());
                        String applyDepaName = null;
                        String applyDepaName = null;
                        if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
                        if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
                            applyDepaName = doctorHospitalDOS.get(0).getDeptName();
                            applyDepaName = doctorHospitalDOS.get(0).getDeptName();
                        }
                        }
                        String voucherNo = map.get("voucherNo")+"";
                        String voucherNo = map.get("voucherNo") + "";
                        String applyDoctorName = prescriptionDO.getDoctorName();
                        String applyDoctorName = prescriptionDO.getDoctorName();
                        BasePatientDO patientDO = basePatientDao.findById(patientCode);
                        BasePatientDO patientDO = basePatientDao.findById(patientCode);
                        String userName = null;
                        String userName = null;
                        String idcard = null;
                        String idcard = null;
                        if (patientDO!=null){
                        if (patientDO != null) {
                            userName = patientDO.getName();
                            userName = patientDO.getName();
                            idcard = patientDO.getIdcard();
                            idcard = patientDO.getIdcard();
                        }
                        }
                        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patientCode);
                        PatientMappingDO patientMappingDO = patientMappingDao.findByPatient(patientCode);
                        String userNo = null;
                        String userNo = null;
                        if (patientMappingDO!=null){
                        if (patientMappingDO != null) {
                            userNo = patientMappingDO.getMappingCode();
                            userNo = patientMappingDO.getMappingCode();
                        }
                        }
                        String cardNo = null;
                        String cardNo = null;
                        if (StringUtils.isNoneBlank(outpatientDO.getCardNo())){
                        if (StringUtils.isNoneBlank(outpatientDO.getCardNo())) {
                            cardNo = outpatientDO.getCardNo();
                            cardNo = outpatientDO.getCardNo();
                        }
                        }
                        logger.info("cardNo:"+cardNo);
                        ylzPayService.msgPush("01",cardNo,"01",patientDO.getMobile(),"00",userNo,userName,idcard,voucherNo,applyDepaName,applyDoctorName,recipeTime,free,"1");
                        logger.info("cardNo:" + cardNo);
                        ylzPayService.msgPush("01", cardNo, "01", patientDO.getMobile(), "00", userNo, userName, idcard, voucherNo, applyDepaName, applyDoctorName, recipeTime, free, "1");
                    }
                    }
                    //sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);
                    //sendHisDiagnosis(jsonData, outpatientDO, wlyyPrescriptionDO);
@ -6141,7 +6341,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                }
                }
            }
            }
            prescriptionLogService.addPrescriptionLog(prescriptionId,20,2,operate,operateName,reason,new Date());
            prescriptionLogService.addPrescriptionLog(prescriptionId, 20, 2, operate, operateName, reason, new Date());
            wlyyPrescriptionDO.setCheckStatus(2);
            wlyyPrescriptionDO.setCheckStatus(2);
            wlyyPrescriptionDO.setCheckReason(reason);
            wlyyPrescriptionDO.setCheckReason(reason);
            wlyyPrescriptionDO.setStatus(20);
            wlyyPrescriptionDO.setStatus(20);
@ -6154,17 +6354,17 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            messageDO.setTitle("处方支付提醒");
            messageDO.setTitle("处方支付提醒");
            messageDO.setSender(outpatientDO.getDoctor());
            messageDO.setSender(outpatientDO.getDoctor());
            messageDO.setSenderName(outpatientDO.getDoctorName());
            messageDO.setSenderName(outpatientDO.getDoctorName());
            messageDO.setRelationCode(outpatientDO.getId()+","+wlyyPrescriptionDO.getId());
            messageDO.setRelationCode(outpatientDO.getId() + "," + wlyyPrescriptionDO.getId());
            messageDO.setReceiver(outpatientDO.getPatient());
            messageDO.setReceiver(outpatientDO.getPatient());
            messageDO.setReceiverName(outpatientDO.getPatientName());
            messageDO.setReceiverName(outpatientDO.getPatientName());
            JSONObject data = new JSONObject();
            JSONObject data = new JSONObject();
            try {
            try {
                data.put("name",outpatientDO.getPatientName());
                data.put("name", outpatientDO.getPatientName());
                data.put("age", IdCardUtil.getAgeForIdcard(outpatientDO.getIdcard()));
                data.put("age", IdCardUtil.getAgeForIdcard(outpatientDO.getIdcard()));
                data.put("gender",IdCardUtil.getSexForIdcard_new(outpatientDO.getIdcard()));
                data.put("question","");
                String msg=outpatientDO.getPatientName()+",您好!医生已为您开具处方,请及时支付。如您已支付请忽略本条信息。";
                data.put("msg",msg);
                data.put("gender", IdCardUtil.getSexForIdcard_new(outpatientDO.getIdcard()));
                data.put("question", "");
                String msg = outpatientDO.getPatientName() + ",您好!医生已为您开具处方,请及时支付。如您已支付请忽略本条信息。";
                data.put("msg", msg);
                messageDO.setData(data.toString());
                messageDO.setData(data.toString());
                systemMessageService.saveMessage(messageDO);
                systemMessageService.saveMessage(messageDO);
@ -6172,19 +6372,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                e.printStackTrace();
                e.printStackTrace();
            }
            }
            BasePatientDO patient = basePatientDao.findById(outpatientDO.getPatient());
            BasePatientDO patient = basePatientDao.findById(outpatientDO.getPatient());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                ykyyService.pushNotificationToYktPatient(patient.getYktId(),messageDO.getTitle(),data.get("msg").toString());
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)) {
                ykyyService.pushNotificationToYktPatient(patient.getYktId(), messageDO.getTitle(), data.get("msg").toString());
            }
            }
        }else{
            sendWxTemplateMsg(wxId, outpatientDO.getId(), "", "prescriptionPayRemind", null);
        } else {
            wlyyPrescriptionDO.setId(prescriptionId);
            wlyyPrescriptionDO.setId(prescriptionId);
            wlyyPrescriptionDO.setCheckStatus(status);
            wlyyPrescriptionDO.setCheckStatus(status);
            wlyyPrescriptionDO.setCheckReason(reason);
            wlyyPrescriptionDO.setCheckReason(reason);
            wlyyPrescriptionDO.setStatus(11);
            wlyyPrescriptionDO.setStatus(11);
        }
        }
        prescriptionDao.save(wlyyPrescriptionDO);
        prescriptionDao.save(wlyyPrescriptionDO);
        if (status==2||status==1){
            sendCheckMessage(status,wlyyPrescriptionDO,operate,operateName);
        if (status == 2 || status == 1) {
            sendCheckMessage(status, wlyyPrescriptionDO, operate, operateName);
        }
        }
@ -6192,21 +6392,20 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    }
    public WlyyPrescriptionCheckDO savePrescriptionCheck(String operate,String reason,Integer status,String prescriptionId){
    public WlyyPrescriptionCheckDO savePrescriptionCheck(String operate, String reason, Integer status, String prescriptionId) {
        String dept = null;
        String dept = null;
        String deptName = null;
        String deptName = null;
        String job = null;
        String job = null;
        String jobName = null;
        String jobName = null;
        BaseDoctorDO doctorDO = baseDoctorDao.findById(operate);
        BaseDoctorDO doctorDO = baseDoctorDao.findById(operate);
        String operateName = null;
        String operateName = null;
        if (doctorDO!=null){
        if (doctorDO != null) {
            operateName = doctorDO.getName();
            operateName = doctorDO.getName();
            job = doctorDO.getJobTitleCode();
            job = doctorDO.getJobTitleCode();
            jobName = doctorDO.getJobTitleName();
            jobName = doctorDO.getJobTitleName();
        }
        }
        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(operate);
        List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(operate);
        if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
        if (doctorHospitalDOS != null && doctorHospitalDOS.size() != 0) {
            BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
            BaseDoctorHospitalDO doctorHospitalDO = doctorHospitalDOS.get(0);
            dept = doctorHospitalDO.getDeptCode();
            dept = doctorHospitalDO.getDeptCode();
            deptName = doctorHospitalDO.getDeptName();
            deptName = doctorHospitalDO.getDeptName();
@ -6227,19 +6426,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO.setPrescriptionId(prescriptionId);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        prescriptionCheckDO = prescriptionCheckDao.save(prescriptionCheckDO);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (status==3){
        if (status == 3) {
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setDealStatus(1);
            wlyyPrescriptionDO.setDealStatus(1);
            wlyyPrescriptionDO.setDealReason(reason);
            wlyyPrescriptionDO.setDealReason(reason);
        }else if (status==4){
        } else if (status == 4) {
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setStatus(10);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setDealStatus(2);
            wlyyPrescriptionDO.setDealStatus(2);
            wlyyPrescriptionDO.setDealReason(reason);
            wlyyPrescriptionDO.setDealReason(reason);
        }else if (status==5){
        } else if (status == 5) {
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckStatus(0);
            wlyyPrescriptionDO.setCheckReason("未审核");
            wlyyPrescriptionDO.setCheckReason("未审核");
        }
        }
@ -6250,25 +6449,27 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询审批记录
     * 查询审批记录
     *
     * @param prescriptionId
     * @param prescriptionId
     * @return
     * @return
     */
     */
    public List<WlyyPrescriptionCheckDO> findPrescriptionCheck(String prescriptionId){
        return  prescriptionCheckDao.findByPrescriptionId(prescriptionId);
    public List<WlyyPrescriptionCheckDO> findPrescriptionCheck(String prescriptionId) {
        return prescriptionCheckDao.findByPrescriptionId(prescriptionId);
    }
    }
    /**
    /**
     * 发送处方审核消息
     * 发送处方审核消息
     *
     * @param status
     * @param status
     * @param prescriptionDO
     * @param prescriptionDO
     * @param operate
     * @param operate
     * @param operateName
     * @param operateName
     * @return
     * @return
     */
     */
    public SystemMessageDO sendCheckMessage(Integer status,WlyyPrescriptionDO prescriptionDO,String operate,String operateName){
    public SystemMessageDO sendCheckMessage(Integer status, WlyyPrescriptionDO prescriptionDO, String operate, String operateName) {
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        SystemMessageDO systemMessageDO = new SystemMessageDO();
        try{
        try {
            systemMessageDO.setReceiver(prescriptionDO.getDoctor());
            systemMessageDO.setReceiver(prescriptionDO.getDoctor());
            systemMessageDO.setReceiverName(prescriptionDO.getDoctorName());
            systemMessageDO.setReceiverName(prescriptionDO.getDoctorName());
@ -6278,21 +6479,21 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            JSONObject data = new JSONObject();
            JSONObject data = new JSONObject();
            Integer age = 0;
            Integer age = 0;
            String gender = "";
            String gender = "";
            if (StringUtils.isNoneBlank(prescriptionDO.getIdcard())){
            if (StringUtils.isNoneBlank(prescriptionDO.getIdcard())) {
                age = IdCardUtil.getAgeForIdcard(prescriptionDO.getIdcard());
                age = IdCardUtil.getAgeForIdcard(prescriptionDO.getIdcard());
                gender=IdCardUtil.getSexForIdcard(prescriptionDO.getIdcard());
                gender = IdCardUtil.getSexForIdcard(prescriptionDO.getIdcard());
            }
            }
            BasePatientDO patientDO = basePatientDao.findById(prescriptionDO.getPatientCode());
            BasePatientDO patientDO = basePatientDao.findById(prescriptionDO.getPatientCode());
            data.put("name",prescriptionDO.getPatientName());
            data.put("age",age);
            data.put("gender",gender);
            data.put("outpatientId",prescriptionDO.getOutpatientId());
            data.put("prescriptionId",prescriptionDO.getId());
            if (status==2){
            data.put("name", prescriptionDO.getPatientName());
            data.put("age", age);
            data.put("gender", gender);
            data.put("outpatientId", prescriptionDO.getOutpatientId());
            data.put("prescriptionId", prescriptionDO.getId());
            if (status == 2) {
                systemMessageDO.setType("9");
                systemMessageDO.setType("9");
                systemMessageDO.setTitle("审方通过");
                systemMessageDO.setTitle("审方通过");
                data.put("message","审方通过");
                data.put("message","您为"+prescriptionDO.getPatientName()+"("+age+"岁 "+gender+")开具的处方已审核通过。");
                data.put("message", "审方通过");
                data.put("message", "您为" + prescriptionDO.getPatientName() + "(" + age + "岁 " + gender + ")开具的处方已审核通过。");
                /**
                /**
                 *  * @param userName      推送人姓名
                 *  * @param userName      推送人姓名
                 * @param idCard        推送人身份证
                 * @param idCard        推送人身份证
@ -6314,16 +6515,16 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    title = patientDO.getName()+",您好!医生已为您开具处方,请及时支付";
                    title = patientDO.getName()+",您好!医生已为您开具处方,请及时支付";
                }
                }
                entranceService.ehospitalNotice(prescriptionDO.getPatientName())*/
                entranceService.ehospitalNotice(prescriptionDO.getPatientName())*/
            } else if (status==1) {
            } else if (status == 1) {
                systemMessageDO.setType("8");
                systemMessageDO.setType("8");
                systemMessageDO.setTitle("审方退回");
                systemMessageDO.setTitle("审方退回");
                data.put("message","审方退回");
                data.put("message","您为"+prescriptionDO.getPatientName()+"("+age+"岁 "+gender+")开具的处方被审方退回,请尽快处理");
                data.put("message", "审方退回");
                data.put("message", "您为" + prescriptionDO.getPatientName() + "(" + age + "岁 " + gender + ")开具的处方被审方退回,请尽快处理");
            }
            }
            systemMessageDO.setData(data.toString());
            systemMessageDO.setData(data.toString());
            systemMessageService.saveMessage(systemMessageDO);
            systemMessageService.saveMessage(systemMessageDO);
        }catch (Exception e){
            logger.error("sendPatientGetDrugMes :"+e.toString());
        } catch (Exception e) {
            logger.error("sendPatientGetDrugMes :" + e.toString());
        }
        }
        return systemMessageDO;
        return systemMessageDO;
    }
    }
@ -6331,85 +6532,82 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询单条处方记录
     * 查询单条处方记录
     *
     * @param prescriptionId
     * @param prescriptionId
     * @return
     * @return
     * @throws Exception
     * @throws Exception
     */
     */
    public WlyyPrescriptionVO selectByPrescriptionId(String prescriptionId) throws Exception {
    public WlyyPrescriptionVO selectByPrescriptionId(String prescriptionId) throws Exception {
        WlyyPrescriptionDO  wlyyPrescriptionDO= prescriptionDao.findOne(prescriptionId);
        if (wlyyPrescriptionDO!=null){
        WlyyPrescriptionDO wlyyPrescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (wlyyPrescriptionDO != null) {
            com.alibaba.fastjson.JSONObject objectString = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(wlyyPrescriptionDO);
            com.alibaba.fastjson.JSONObject objectString = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(wlyyPrescriptionDO);
            WlyyPrescriptionVO prescriptionVO =  com.alibaba.fastjson.JSONObject.toJavaObject(objectString,WlyyPrescriptionVO.class);
            List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId,1);
            WlyyPrescriptionVO prescriptionVO = com.alibaba.fastjson.JSONObject.toJavaObject(objectString, WlyyPrescriptionVO.class);
            List<WlyyPrescriptionInfoDO> wlyyPrescriptionInfoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
            List<WlyyPrescriptionInfoVO> wlyyPrescriptionInfoVOS = new ArrayList<>();
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO:wlyyPrescriptionInfoDOS){
            for (WlyyPrescriptionInfoDO wlyyPrescriptionInfoDO : wlyyPrescriptionInfoDOS) {
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(wlyyPrescriptionInfoDO);
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(wlyyPrescriptionInfoDO);
                logger.info("wlyyPrescriptionInfoDO参数入参"+object.toJSONString());
                WlyyPrescriptionInfoVO prescriptionInfoVO = com.alibaba.fastjson.JSONObject.toJavaObject(object,WlyyPrescriptionInfoVO.class);
                logger.info("wlyyPrescriptionInfoDO参数入参" + object.toJSONString());
                WlyyPrescriptionInfoVO prescriptionInfoVO = com.alibaba.fastjson.JSONObject.toJavaObject(object, WlyyPrescriptionInfoVO.class);
                wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
                wlyyPrescriptionInfoVOS.add(prescriptionInfoVO);
            }
            }
            prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
            prescriptionVO.setInfoVOs(wlyyPrescriptionInfoVOS);
            List<WlyyPrescriptionDiagnosisDO> wlyyPrescriptionDiagnosisDOS = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId,1);
            List<WlyyPrescriptionDiagnosisDO> wlyyPrescriptionDiagnosisDOS = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyPrescriptionDiagnosisVO> wlyyPrescriptionDiagnosisVOS = new ArrayList<>();
            List<WlyyPrescriptionDiagnosisVO> wlyyPrescriptionDiagnosisVOS = new ArrayList<>();
            for (WlyyPrescriptionDiagnosisDO prescriptionDiagnosisDO:wlyyPrescriptionDiagnosisDOS){
            for (WlyyPrescriptionDiagnosisDO prescriptionDiagnosisDO : wlyyPrescriptionDiagnosisDOS) {
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(prescriptionDiagnosisDO);
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(prescriptionDiagnosisDO);
                logger.info("prescriptionDiagnosisDO参数入参"+object.toJSONString());
                WlyyPrescriptionDiagnosisVO prescriptionDiagnosisVO = com.alibaba.fastjson.JSONObject.toJavaObject(object,WlyyPrescriptionDiagnosisVO.class);
                logger.info("prescriptionDiagnosisDO参数入参" + object.toJSONString());
                WlyyPrescriptionDiagnosisVO prescriptionDiagnosisVO = com.alibaba.fastjson.JSONObject.toJavaObject(object, WlyyPrescriptionDiagnosisVO.class);
                wlyyPrescriptionDiagnosisVOS.add(prescriptionDiagnosisVO);
                wlyyPrescriptionDiagnosisVOS.add(prescriptionDiagnosisVO);
            }
            }
            prescriptionVO.setDiagnosisVOs(wlyyPrescriptionDiagnosisVOS);
            prescriptionVO.setDiagnosisVOs(wlyyPrescriptionDiagnosisVOS);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId,1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyInspectionVO> inspectionVOList = new ArrayList<>();
            List<WlyyInspectionVO> inspectionVOList = new ArrayList<>();
            for (WlyyInspectionDO inspectionDO:inspectionDOS){
            for (WlyyInspectionDO inspectionDO : inspectionDOS) {
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(inspectionDO);
                com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(inspectionDO);
                logger.info("prescriptionDiagnosisDO参数入参"+object.toJSONString());
                WlyyInspectionVO inspectionVO = com.alibaba.fastjson.JSONObject.toJavaObject(object,WlyyInspectionVO.class);
                logger.info("prescriptionDiagnosisDO参数入参" + object.toJSONString());
                WlyyInspectionVO inspectionVO = com.alibaba.fastjson.JSONObject.toJavaObject(object, WlyyInspectionVO.class);
                inspectionVOList.add(inspectionVO);
                inspectionVOList.add(inspectionVO);
            }
            }
            prescriptionVO.setInspectionVOs(inspectionVOList);
            prescriptionVO.setInspectionVOs(inspectionVOList);
            prescriptionVO.setAge(StringUtils.isNoneBlank(wlyyPrescriptionDO.getIdcard())?IdCardUtil.getAgeForIdcard(wlyyPrescriptionDO.getIdcard())+"":null);
            prescriptionVO.setSex(StringUtils.isNoneBlank(wlyyPrescriptionDO.getIdcard())?IdCardUtil.getSexForIdcard_new(wlyyPrescriptionDO.getIdcard()):null);
            prescriptionVO.setAge(StringUtils.isNoneBlank(wlyyPrescriptionDO.getIdcard()) ? IdCardUtil.getAgeForIdcard(wlyyPrescriptionDO.getIdcard()) + "" : null);
            prescriptionVO.setSex(StringUtils.isNoneBlank(wlyyPrescriptionDO.getIdcard()) ? IdCardUtil.getSexForIdcard_new(wlyyPrescriptionDO.getIdcard()) : null);
            return prescriptionVO;
            return prescriptionVO;
        }
        }
        return null;
        return null;
    }
    }
    public void deleteById(Integer flag,String id){
        if (flag ==1){
    public void deleteById(Integer flag, String id) {
        if (flag == 1) {
            //药品
            //药品
            prescriptionInfoDao.deleteById(id);
            prescriptionInfoDao.deleteById(id);
        }else if (flag==2){
        } else if (flag == 2) {
            //诊断
            //诊断
            prescriptionDiagnosisDao.deleteById(id);
            prescriptionDiagnosisDao.deleteById(id);
        }else if (flag==3){
        } else if (flag == 3) {
            //检查检验
            //检查检验
            wlyyInspectionDao.deleteById(id);
            wlyyInspectionDao.deleteById(id);
        }
        }
    }
    }
    public void zsSynHis(String prescriptionId){
    public void zsSynHis(String prescriptionId) {
        try {
        try {
            WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
            WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
            List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId,1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId,1);
            List<WlyyPrescriptionInfoDO> infoDOS = prescriptionInfoDao.findByPrescriptionId(prescriptionId, 1);
            List<WlyyInspectionDO> inspectionDOS = wlyyInspectionDao.findByPrescriptionId(prescriptionId, 1);
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
            WlyyOutpatientDO outpatientDO = outpatientDao.findById(prescriptionDO.getOutpatientId());
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
            DoctorMappingDO doctorMappingDO = doctorMappingService.findMappingCode(outpatientDO.getDoctor(), outpatientDO.getHospital());
            //his处方拼接开方条件
            //his处方拼接开方条件
            com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
            com.alibaba.fastjson.JSONArray jsonData = new com.alibaba.fastjson.JSONArray();
            for (WlyyPrescriptionInfoDO info:infoDOS){
            for (WlyyPrescriptionInfoDO info : infoDOS) {
                //设置his药品查询条件
                //设置his药品查询条件
                setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, outpatientDO.getIcd10());
                setInfoJsonParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, info, outpatientDO.getIcd10());
            }
            }
            for (WlyyInspectionDO ins:inspectionDOS){
            for (WlyyInspectionDO ins : inspectionDOS) {
                //设置his药品查询条件
                //设置his药品查询条件
                setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, outpatientDO.getIcd10());
                setInspectionParam(jsonData, doctorMappingDO, outpatientDO, prescriptionDO, ins, outpatientDO.getIcd10());
            }
            }
@ -6422,10 +6620,11 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 创建电子病历
     * 创建电子病历
     *
     * @param wlyyPrescriptionEmrDO
     * @param wlyyPrescriptionEmrDO
     * @return
     * @return
     */
     */
    public WlyyPrescriptionEmrDO saveEmr(WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO){
    public WlyyPrescriptionEmrDO saveEmr(WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO) {
        wlyyPrescriptionEmrDO.setCreateTime(new Date());
        wlyyPrescriptionEmrDO.setCreateTime(new Date());
        wlyyPrescriptionEmrDO.setUpdateTime(new Date());
        wlyyPrescriptionEmrDO.setUpdateTime(new Date());
        wlyyPrescriptionEmrDO.setDel(1);
        wlyyPrescriptionEmrDO.setDel(1);
@ -6435,20 +6634,22 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询电子病历
     * 查询电子病历
     *
     * @param prescriptionId
     * @param prescriptionId
     * @return
     * @return
     */
     */
    public List<WlyyPrescriptionEmrDO> findByPrescriptionId(String  prescriptionId){
    public List<WlyyPrescriptionEmrDO> findByPrescriptionId(String prescriptionId) {
        return prescriptionEmrDao.findByPrescriptionId(prescriptionId);
        return prescriptionEmrDao.findByPrescriptionId(prescriptionId);
    }
    }
    /**
    /**
     * 保存排班规则
     * 保存排班规则
     *
     * @param advicesJson
     * @param advicesJson
     * @return
     * @return
     */
     */
    public Boolean sendOutPatientSuggest(String advicesJson){
    public Boolean sendOutPatientSuggest(String advicesJson) {
        List<WlyyConsultAdvice> advices = (List<WlyyConsultAdvice>) com.alibaba.fastjson.JSONArray.parseArray(advicesJson, WlyyConsultAdvice.class);
        List<WlyyConsultAdvice> advices = (List<WlyyConsultAdvice>) com.alibaba.fastjson.JSONArray.parseArray(advicesJson, WlyyConsultAdvice.class);
        wlyyConsultAdviceDao.save(advices);
        wlyyConsultAdviceDao.save(advices);
        return true;
        return true;
@ -6456,6 +6657,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 获取咨询建议
     * 获取咨询建议
     *
     * @param consultcode
     * @param consultcode
     * @return
     * @return
     */
     */
@ -6466,6 +6668,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 电子病历html
     * 电子病历html
     *
     * @param registerSn
     * @param registerSn
     * @return
     * @return
     * @throws Exception
     * @throws Exception
@ -6473,19 +6676,19 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    public String readOutPatient(String registerSn) throws Exception {
    public String readOutPatient(String registerSn) throws Exception {
        String url = "";
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO!=null){
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<HtRequest>\n";
                "<HtRequest>\n";
        xmlStr+="<REGISTER_SN>"+registerSn+"</REGISTER_SN>";
        String reqTime = DateUtil.dateToStr(new Date(),"yyyyMMddHHmmssSSS");
        xmlStr+="<REQ_TIME>"+reqTime+"</REQ_TIME>";
        xmlStr+="</HtRequest>";
        xmlStr += "<REGISTER_SN>" + registerSn + "</REGISTER_SN>";
        String reqTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmssSSS");
        xmlStr += "<REQ_TIME>" + reqTime + "</REQ_TIME>";
        xmlStr += "</HtRequest>";
        String returnValue = "";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        Map<String, String> params = new HashedMap();
        params.put("type","readOutPatient");
        params.put("xmlStr",xmlStr);
        params.put("type", "readOutPatient");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                "manageOutRegister",
@ -6494,7 +6697,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        logger.info("调用电子病历查询接口请求成功,返回值xmlstr:" + returnValue);
        logger.info("调用电子病历查询接口请求成功,返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json"+json);
        logger.info("返回json" + json);
        return json.toString();
        return json.toString();
    }
    }
@ -6502,6 +6705,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 电子病历xml
     * 电子病历xml
     *
     * @param registerSn
     * @param registerSn
     * @return
     * @return
     * @throws Exception
     * @throws Exception
@ -6510,20 +6714,20 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = new WlyyPrescriptionEmrDO();
        WlyyPrescriptionEmrDO wlyyPrescriptionEmrDO = new WlyyPrescriptionEmrDO();
        String url = "";
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO!=null){
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<HtRequest>\n";
                "<HtRequest>\n";
        xmlStr+="<REGISTER_SN>"+registerSn+"</REGISTER_SN>";
        xmlStr+="<SEARCH_IDS>CHIEF_COMPLAINT,HPI,ELAPSEMHIS,BODYCHECK,ASSISTANTCHECK</SEARCH_IDS>";
        String reqTime = DateUtil.dateToStr(new Date(),"yyyyMMddHHmmss");
        xmlStr+="<REQ_TIME>"+reqTime+"</REQ_TIME>";
        xmlStr+="</HtRequest>";
        xmlStr += "<REGISTER_SN>" + registerSn + "</REGISTER_SN>";
        xmlStr += "<SEARCH_IDS>CHIEF_COMPLAINT,HPI,ELAPSEMHIS,BODYCHECK,ASSISTANTCHECK</SEARCH_IDS>";
        String reqTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss");
        xmlStr += "<REQ_TIME>" + reqTime + "</REQ_TIME>";
        xmlStr += "</HtRequest>";
        String returnValue = "";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        Map<String, String> params = new HashedMap();
        params.put("type","readOutPatientDetail");
        params.put("xmlStr",xmlStr);
        params.put("type", "readOutPatientDetail");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                "manageOutRegister",
@ -6532,7 +6736,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        logger.info("调用电子病历查询接口请求成功,返回值xmlstr:" + returnValue);
        logger.info("调用电子病历查询接口请求成功,返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json"+json);
        logger.info("返回json" + json);
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(json.toString());
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(json.toString());
        wlyyPrescriptionEmrDO.setComplaint(object.getString("CHIEF_COMPLAINT"));
        wlyyPrescriptionEmrDO.setComplaint(object.getString("CHIEF_COMPLAINT"));
        wlyyPrescriptionEmrDO.setMedicalHistory(object.getString("HPI"));
        wlyyPrescriptionEmrDO.setMedicalHistory(object.getString("HPI"));
@ -6542,32 +6746,32 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        return wlyyPrescriptionEmrDO;
        return wlyyPrescriptionEmrDO;
    }
    }
    public String writeOutPatient(String registerSn,String chiefComplaint,String hpi,String elapsemhis,String bodycheck,String assistanTcheck,String doctorId,String doctorName) throws Exception {
    public String writeOutPatient(String registerSn, String chiefComplaint, String hpi, String elapsemhis, String bodycheck, String assistanTcheck, String doctorId, String doctorName) throws Exception {
        String url = "";
        String url = "";
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("HAI_TAI_URL");
        if (wlyyHospitalSysDictDO!=null){
        if (wlyyHospitalSysDictDO != null) {
            url = wlyyHospitalSysDictDO.getDictCode();
            url = wlyyHospitalSysDictDO.getDictCode();
        }
        }
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
        String xmlStr = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<HtRequest>\n";
                "<HtRequest>\n";
        xmlStr+="<REGISTER_SN>"+registerSn+"</REGISTER_SN>";
        String reqTime = DateUtil.dateToStr(new Date(),"yyyyMMddHHmmss");
        xmlStr+="<REQ_TIME>"+reqTime+"</REQ_TIME>";
        xmlStr+="<TREAT_DOCTOR_ID>"+doctorId+"</TREAT_DOCTOR_ID>";
        xmlStr+="<TREAT_DOCTOR_NAME>"+doctorName+"</TREAT_DOCTOR_NAME>";
        xmlStr+="<IS_SGIN>Y</IS_SGIN>";
        xmlStr+="<OUTPATIENT_INFO>";
        xmlStr+="<CHIEF_COMPLAINT>"+chiefComplaint+"</CHIEF_COMPLAINT>";
        xmlStr+="<HPI>"+hpi+"</HPI>";
        xmlStr+="<ELAPSEMHIS>"+elapsemhis+"</ELAPSEMHIS>";
        xmlStr+="<BODYCHECK>"+bodycheck+"</BODYCHECK>";
        xmlStr+="<ASSISTANTCHECK>"+assistanTcheck+"</ASSISTANTCHECK>";
        xmlStr+="</OUTPATIENT_INFO>";
        xmlStr+="</HtRequest>";
        xmlStr += "<REGISTER_SN>" + registerSn + "</REGISTER_SN>";
        String reqTime = DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss");
        xmlStr += "<REQ_TIME>" + reqTime + "</REQ_TIME>";
        xmlStr += "<TREAT_DOCTOR_ID>" + doctorId + "</TREAT_DOCTOR_ID>";
        xmlStr += "<TREAT_DOCTOR_NAME>" + doctorName + "</TREAT_DOCTOR_NAME>";
        xmlStr += "<IS_SGIN>Y</IS_SGIN>";
        xmlStr += "<OUTPATIENT_INFO>";
        xmlStr += "<CHIEF_COMPLAINT>" + chiefComplaint + "</CHIEF_COMPLAINT>";
        xmlStr += "<HPI>" + hpi + "</HPI>";
        xmlStr += "<ELAPSEMHIS>" + elapsemhis + "</ELAPSEMHIS>";
        xmlStr += "<BODYCHECK>" + bodycheck + "</BODYCHECK>";
        xmlStr += "<ASSISTANTCHECK>" + assistanTcheck + "</ASSISTANTCHECK>";
        xmlStr += "</OUTPATIENT_INFO>";
        xmlStr += "</HtRequest>";
        String returnValue = "";
        String returnValue = "";
        Map<String, String> params = new HashedMap();
        Map<String, String> params = new HashedMap();
        params.put("type","writeOutPatient");
        params.put("xmlStr",xmlStr);
        params.put("type", "writeOutPatient");
        params.put("xmlStr", xmlStr);
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
        returnValue = com.yihu.jw.utils.WebserviceUtil.post(url,
                "http://business.htemr.haitaiinc.com",
                "http://business.htemr.haitaiinc.com",
                "manageOutRegister",
                "manageOutRegister",
@ -6576,15 +6780,12 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        logger.info("调用电子病历写入接口请求成功,返回值xmlstr:" + returnValue);
        logger.info("调用电子病历写入接口请求成功,返回值xmlstr:" + returnValue);
        XMLSerializer xmlSerializer = new XMLSerializer();
        XMLSerializer xmlSerializer = new XMLSerializer();
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        net.sf.json.JSON json = xmlSerializer.read(returnValue);
        logger.info("返回json"+json);
        logger.info("返回json" + json);
        return json.toString();
        return json.toString();
    }
    }
    /**
    /**
     * 关注医生
     * 关注医生
     * @param doctorId
     * @param doctorId
@ -6785,48 +6986,49 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    /**
    /**
     * 查询患者所有处方信息
     * 查询患者所有处方信息
     *
     * @param page
     * @param page
     * @param size
     * @param size
     * @return
     * @return
     */
     */
    public PageEnvelop findPatientAllPrescription(String keyName,String status,Integer page, Integer size) {
    public PageEnvelop findPatientAllPrescription(String keyName, String status, Integer page, Integer size) {
        String uid = userAgent.getUID();
        String uid = userAgent.getUID();
        StringBuffer sql = new StringBuffer(" SELECT b.*, c.oneself_pickup_flg,f.job_title_code,f.job_title_name  FROM (SELECT a.* FROM wlyy_prescription a WHERE a.patient_code = '");
        StringBuffer sql = new StringBuffer(" SELECT b.*, c.oneself_pickup_flg,f.job_title_code,f.job_title_name  FROM (SELECT a.* FROM wlyy_prescription a WHERE a.patient_code = '");
        StringBuffer countSql = new StringBuffer("select COUNT(b.id) count FROM (SELECT a.* FROM wlyy_prescription a WHERE a.patient_code = '");
        StringBuffer countSql = new StringBuffer("select COUNT(b.id) count FROM (SELECT a.* FROM wlyy_prescription a WHERE a.patient_code = '");
        sql.append(uid).append("') b LEFT JOIN wlyy_prescription_info d ON b.id = d.prescription_id LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        sql.append(uid).append("') b LEFT JOIN wlyy_prescription_info d ON b.id = d.prescription_id LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        countSql.append(uid).append("') b LEFT JOIN wlyy_prescription_info d ON b.id = d.prescription_id LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        countSql.append(uid).append("') b LEFT JOIN wlyy_prescription_info d ON b.id = d.prescription_id LEFT JOIN wlyy_prescription_expressage c ON c.outpatient_id = b.outpatient_id LEFT JOIN base_doctor f ON b.doctor=f.id  ");
        if (StringUtils.isNotEmpty(status)){
            status= status.substring(1, status.length() - 1);
        if (StringUtils.isNotEmpty(status)) {
            status = status.substring(1, status.length() - 1);
            sql.append(" where b.status IN(").append(status).append(")");
            sql.append(" where b.status IN(").append(status).append(")");
            countSql.append(" where b.status IN(").append(status).append(")");
            countSql.append(" where b.status IN(").append(status).append(")");
        }else {
        } else {
            sql.append("  where b.status IN(20,21,30,31,32,100,101)");
            sql.append("  where b.status IN(20,21,30,31,32,100,101)");
            countSql.append(" where b.status IN(20,21,30,31,32,100,101) ");
            countSql.append(" where b.status IN(20,21,30,31,32,100,101) ");
        }
        }
        if (StringUtils.isNotEmpty(keyName)){
        if (StringUtils.isNotEmpty(keyName)) {
            sql.append(" and (" +
            sql.append(" and (" +
                    " b.doctor_name LIKE '%"+keyName+"%' " +
                    " OR b.dept_name LIKE'%"+keyName+"%' " +
                    " OR b.hospital_name LIKE '%"+keyName+"%' " +
                    " OR d.drug_name LIKE '%"+keyName+"%' " +
                    " OR b.real_order LIKE '%"+keyName+"%' " +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR d.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
                    ")");
            countSql.append(" and (" +
            countSql.append(" and (" +
                    " b.doctor_name LIKE '%"+keyName+"%' " +
                    " OR b.dept_name LIKE'%"+keyName+"%' " +
                    " OR b.hospital_name LIKE '%"+keyName+"%' " +
                    " OR d.drug_name LIKE '%"+keyName+"%' " +
                    " OR b.real_order LIKE '%"+keyName+"%' " +
                    " b.doctor_name LIKE '%" + keyName + "%' " +
                    " OR b.dept_name LIKE'%" + keyName + "%' " +
                    " OR b.hospital_name LIKE '%" + keyName + "%' " +
                    " OR d.drug_name LIKE '%" + keyName + "%' " +
                    " OR b.real_order LIKE '%" + keyName + "%' " +
                    ")");
                    ")");
        }
        }
        sql.append(" order by b.prescribe_time DESC ");
        sql.append(" order by b.prescribe_time DESC ");
        List<WlyyPrescriptionVO>  list=null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String oracleSql="SELECT\n" +
        List<WlyyPrescriptionVO> list = null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)) {
            String oracleSql = "SELECT\n" +
                    "\t*\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t(\n" +
@ -6835,42 +7037,42 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                    "\t\tFROM\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";
                    "\t\t\t(";
            oracleSql+=sql.toString();
            oracleSql += sql.toString();
            oracleSql+="\t\t\t) A\n" +
            oracleSql += "\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <="+page*size +
                    "  ROWNUM <=" + page * size +
                    "\t) \n" +
                    "\t) \n" +
                    "WHERE\n" +
                    "WHERE\n" +
                    "\tROWNUM >= "+(page-1)*size;
            logger.info("oracleSql="+oracleSql);
                    "\tROWNUM >= " + (page - 1) * size;
            logger.info("oracleSql=" + oracleSql);
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        }else {
        } else {
//            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
//            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
            sql.append("  limit ").append((page-1)*size).append(",").append(size);
            sql.append("  limit ").append((page - 1) * size).append(",").append(size);
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
            list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        }
        }
//        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
//        List<WlyyPrescriptionVO> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(WlyyPrescriptionVO.class));
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(countSql.toString());
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(countSql.toString());
        long count = Long.parseLong(mapList.get(0).get("count").toString());
        long count = Long.parseLong(mapList.get(0).get("count").toString());
        logger.info("sql="+sql.toString());
        logger.info("countSql="+countSql.toString());
        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find, list,page,size,count);
        logger.info("sql=" + sql.toString());
        logger.info("countSql=" + countSql.toString());
        return PageEnvelop.getSuccessListWithPage(IotRequestMapping.Common.message_success_find, list, page, size, count);
    }
    }
    /**
    /**
     * 查询取药地址
     * 查询取药地址
     *
     * @param outpatientId
     * @param outpatientId
     * @param longitude
     * @param longitude
     * @param dimension
     * @param dimension
     * @return
     * @return
     */
     */
    public MixEnvelop findDrugAddress(String outpatientId, String longitude, String dimension) {
    public MixEnvelop findDrugAddress(String outpatientId, String longitude, String dimension) {
        String sql="SELECT\n" +
        String sql = "SELECT\n" +
                "\ta.*\n" +
                "\ta.*\n" +
                "FROM\n" +
                "FROM\n" +
                "\tbase_org a\n" +
                "\tbase_org a\n" +
@ -6880,90 +7082,101 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                "\tFROM\n" +
                "\tFROM\n" +
                "\t\twlyy_prescription_expressage c\n" +
                "\t\twlyy_prescription_expressage c\n" +
                "\tWHERE\n" +
                "\tWHERE\n" +
                " c.outpatient_id = '"+outpatientId+"'" +
                " c.outpatient_id = '" + outpatientId + "'" +
                " ) d ON a.`code` = d.hospital_code";
                " ) d ON a.`code` = d.hospital_code";
        BaseOrgDO baseOrgDO = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BaseOrgDO.class)).get(0);
        BaseOrgDO baseOrgDO = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BaseOrgDO.class)).get(0);
        Map<String, String> rs = new HashMap<>();
        Map<String, String> rs = new HashMap<>();
        rs.put("hospital",baseOrgDO.getName());
        rs.put("address",baseOrgDO.getAddress());
        rs.put("hospital", baseOrgDO.getName());
        rs.put("address", baseOrgDO.getAddress());
        String distance = LatitudeUtils.getDistance(longitude, dimension, baseOrgDO.getLongitude(), baseOrgDO.getLatitude());
        String distance = LatitudeUtils.getDistance(longitude, dimension, baseOrgDO.getLongitude(), baseOrgDO.getLatitude());
        rs.put("distance",distance);
        rs.put("longitude",baseOrgDO.getLongitude());
        rs.put("dimension",baseOrgDO.getLatitude());
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find,rs);
        rs.put("distance", distance);
        rs.put("longitude", baseOrgDO.getLongitude());
        rs.put("dimension", baseOrgDO.getLatitude());
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, rs);
    }
    }
    public MixEnvelop selectByUrl(String oupatientId,String prescriptionId,String wxId) throws Exception {
    public MixEnvelop selectByUrl(String oupatientId, String prescriptionId, String wxId) throws Exception {
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        if (wxWechatDO==null){
        if (wxWechatDO == null) {
            throw new Exception("微信配置不存在!");
            throw new Exception("微信配置不存在!");
        }
        }
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        WlyyPrescriptionDO prescriptionDO = prescriptionDao.findOne(prescriptionId);
        if (prescriptionDO==null){
        if (prescriptionDO == null) {
            throw new Exception("处方不存在!");
            throw new Exception("处方不存在!");
        }
        }
        List<BasePatientWechatDo> patientWechatDos =patientWechatDao.findByWechatIdAndPatientId(wxId,prescriptionDO.getPatientCode());
        if (patientWechatDos==null||patientWechatDos.size()==0){
        List<BasePatientWechatDo> patientWechatDos = patientWechatDao.findByWechatIdAndPatientId(wxId, prescriptionDO.getPatientCode());
        if (patientWechatDos == null || patientWechatDos.size() == 0) {
            throw new Exception("openid不存在!");
            throw new Exception("openid不存在!");
        }
        }
        BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
        BasePatientWechatDo patientWechatDo = patientWechatDos.get(0);
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(oupatientId);
        WlyyOutpatientDO wlyyOutpatientDO = outpatientDao.findById(oupatientId);
        String idcard=null;
        if (wlyyOutpatientDO!=null){
            idcard=wlyyOutpatientDO.getCardNo();
        String idcard = null;
        if (wlyyOutpatientDO != null) {
            idcard = wlyyOutpatientDO.getCardNo();
        }
        }
        if (!StringUtils.isNoneBlank(idcard)){
        if (!StringUtils.isNoneBlank(idcard)) {
            throw new Exception("就诊卡不存在!");
            throw new Exception("就诊卡不存在!");
        }
        }
        String url = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(),patientWechatDo.getOpenid(),idcard,"WX");
        String url = ylzPayService.createSicardPayUrl(wxWechatDO.getAppOriginId(), patientWechatDo.getOpenid(), idcard, "WX");
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(url);
        com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(url);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find,object);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, object);
    }
    }
    /**
    /**
     * 获取居民openId
     * 获取居民openId
     *
     * @param patientCode
     * @param patientCode
     * @return
     * @return
     */
     */
    public MixEnvelop findPatientOpenId(String patientCode) {
    public MixEnvelop findPatientOpenId(String patientCode) {
        List<BasePatientWechatDo> basePatientWechatDo = patientWechatDao.findByWechatIdAndPatientId(wechatId, patientCode);
        List<BasePatientWechatDo> basePatientWechatDo = patientWechatDao.findByWechatIdAndPatientId(wechatId, patientCode);
        if (basePatientWechatDo.isEmpty()){
            return MixEnvelop.getSuccess("居民openID不存在",null);
        if (basePatientWechatDo.isEmpty()) {
            return MixEnvelop.getSuccess("居民openID不存在", null);
        }
        }
        String openid = basePatientWechatDo.get(0).getOpenid();
        String openid = basePatientWechatDo.get(0).getOpenid();
        if (StringUtils.isEmpty(openid)){
            return MixEnvelop.getSuccess("居民openID不存在",null);
        if (StringUtils.isEmpty(openid)) {
            return MixEnvelop.getSuccess("居民openID不存在", null);
        }
        }
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find,openid);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, openid);
    }
    }
    /**
    /**
     * 查询科室简介
     * 查询科室简介
     *
     * @param orgCode
     * @param orgCode
     * @param deptCode
     * @param deptCode
     * @return
     * @return
     */
     */
    public MixEnvelop findDeptDesc(String orgCode, String deptCode) {
    public MixEnvelop findDeptDesc(String orgCode, String deptCode) {
        DictDeptDescDO deptDescDO = dictDeptDescDao.findByDeptCodeAndOrgCode(deptCode, orgCode);
        DictDeptDescDO deptDescDO = dictDeptDescDao.findByDeptCodeAndOrgCode(deptCode, orgCode);
        if (deptDescDO!=null){
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find,deptDescDO);
        }else {
        if (deptDescDO != null) {
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, deptDescDO);
        } else {
            return MixEnvelop.getError("无该科室简介");
            return MixEnvelop.getError("无该科室简介");
        }
        }
    }
    }
    /**
    /**
     * 查询机构科室
     * 查询机构科室
     *
     * @param orgCode
     * @param orgCode
     * @return
     * @return
     */
     */
    public MixEnvelop findDeptByOrgCode(String orgCode) {
        List<DictDeptDescDO> deptDescDOList = dictDeptDescDao.findByOrgCode(orgCode);
        if (deptDescDOList==null || deptDescDOList.size()==0){
    public MixEnvelop findDeptByOrgCode(String orgCode, String keyName) {
        List<DictDeptDescDO> deptDescDOList = new ArrayList<DictDeptDescDO>();
        if (StringUtils.isEmpty(keyName)) {
            deptDescDOList = dictDeptDescDao.findByOrgCode(orgCode);
        } else {
            deptDescDOList = dictDeptDescDao.findByOrgCode(orgCode, keyName);
        }
        deptDescDOList.forEach(one -> {
            one.setDeptDescription(null);
        });
        if (deptDescDOList == null || deptDescDOList.size() == 0) {
            return MixEnvelop.getError("无科室信息");
            return MixEnvelop.getError("无科室信息");
        }
        }
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find,deptDescDOList);
        return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, deptDescDOList);
    }
    }
}
}

+ 1 - 1
svr/svr-base/src/main/resources/application.yml

@ -469,7 +469,7 @@ hospital:
wlyy:
wlyy:
  url: http://ehr.yihu.com/wlyy/
  url: http://ehr.yihu.com/wlyy/
wechat:
wechat:
  id: xm_zsyy_wx
  id: xm_ykyy_wx
#文件服务器上传配置 0本地,1.I健康,2.内网调用
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
testPattern:
  sign: 0
  sign: 0